Initial version

This commit is contained in:
Flatlogic Bot 2026-02-13 04:52:40 +00:00
commit c4feaa9816
644 changed files with 203000 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>Pro Se Litigant AI</h2>
<p>AI-powered legal assistant to draft, research, analyze files, manage matters, and simulate hearings in one secure workspace.</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 @@
# Pro Se Litigant AI
## 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_38392
DB_USER=app_38392
DB_PASS=08ae486b-c3d8-4340-96e0-db8c1c385762
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 @@
#Pro Se Litigant AI - 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_pro_se_litigant_ai;`
- Then give that new user privileges to the new database then quit the `psql`.
- `postgres=> GRANT ALL PRIVILEGES ON DATABASE db_pro_se_litigant_ai 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": "proselitigantai",
"description": "Pro Se Litigant AI - 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});
});
}

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

@ -0,0 +1,78 @@
const os = require('os');
const config = {
gcloud: {
bucket: "fldemo-files",
hash: "afeefb9d49f5b7977577876b99532ac7"
},
bcrypt: {
saltRounds: 12
},
admin_pass: "08ae486b",
user_pass: "db8c1c385762",
admin_email: "admin@flatlogic.com",
providers: {
LOCAL: 'local',
GOOGLE: 'google',
MICROSOFT: 'microsoft'
},
secret_key: process.env.SECRET_KEY || '08ae486b-c3d8-4340-96e0-db8c1c385762',
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: 'Pro Se Litigant AI <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: 'User',
},
project_uuid: '08ae486b-c3d8-4340-96e0-db8c1c385762',
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 = 'Compass over open notebook';
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,701 @@
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_jobsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const ai_jobs = await db.ai_jobs.create(
{
id: data.id || undefined,
job_type: data.job_type
||
null
,
status: data.status
||
null
,
input_summary: data.input_summary
||
null
,
output_summary: data.output_summary
||
null
,
cost_usd: data.cost_usd
||
null
,
queued_at: data.queued_at
||
null
,
started_at: data.started_at
||
null
,
completed_at: data.completed_at
||
null
,
error_message: data.error_message
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await ai_jobs.setRequested_by( data.requested_by || null, {
transaction,
});
await ai_jobs.setMatter( data.matter || null, {
transaction,
});
await ai_jobs.setFile( data.file || null, {
transaction,
});
return ai_jobs;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const ai_jobsData = data.map((item, index) => ({
id: item.id || undefined,
job_type: item.job_type
||
null
,
status: item.status
||
null
,
input_summary: item.input_summary
||
null
,
output_summary: item.output_summary
||
null
,
cost_usd: item.cost_usd
||
null
,
queued_at: item.queued_at
||
null
,
started_at: item.started_at
||
null
,
completed_at: item.completed_at
||
null
,
error_message: item.error_message
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const ai_jobs = await db.ai_jobs.bulkCreate(ai_jobsData, { transaction });
// For each item created, replace relation files
return ai_jobs;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const ai_jobs = await db.ai_jobs.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.job_type !== undefined) updatePayload.job_type = data.job_type;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.input_summary !== undefined) updatePayload.input_summary = data.input_summary;
if (data.output_summary !== undefined) updatePayload.output_summary = data.output_summary;
if (data.cost_usd !== undefined) updatePayload.cost_usd = data.cost_usd;
if (data.queued_at !== undefined) updatePayload.queued_at = data.queued_at;
if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
if (data.completed_at !== undefined) updatePayload.completed_at = data.completed_at;
if (data.error_message !== undefined) updatePayload.error_message = data.error_message;
updatePayload.updatedById = currentUser.id;
await ai_jobs.update(updatePayload, {transaction});
if (data.requested_by !== undefined) {
await ai_jobs.setRequested_by(
data.requested_by,
{ transaction }
);
}
if (data.matter !== undefined) {
await ai_jobs.setMatter(
data.matter,
{ transaction }
);
}
if (data.file !== undefined) {
await ai_jobs.setFile(
data.file,
{ transaction }
);
}
return ai_jobs;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const ai_jobs = await db.ai_jobs.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of ai_jobs) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of ai_jobs) {
await record.destroy({transaction});
}
});
return ai_jobs;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const ai_jobs = await db.ai_jobs.findByPk(id, options);
await ai_jobs.update({
deletedBy: currentUser.id
}, {
transaction,
});
await ai_jobs.destroy({
transaction
});
return ai_jobs;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const ai_jobs = await db.ai_jobs.findOne(
{ where },
{ transaction },
);
if (!ai_jobs) {
return ai_jobs;
}
const output = ai_jobs.get({plain: true});
output.requested_by = await ai_jobs.getRequested_by({
transaction
});
output.matter = await ai_jobs.getMatter({
transaction
});
output.file = await ai_jobs.getFile({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.users,
as: 'requested_by',
where: filter.requested_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.requested_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.requested_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.matters,
as: 'matter',
where: filter.matter ? {
[Op.or]: [
{ id: { [Op.in]: filter.matter.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.matter.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.files,
as: 'file',
where: filter.file ? {
[Op.or]: [
{ id: { [Op.in]: filter.file.split('|').map(term => Utils.uuid(term)) } },
{
file_name: {
[Op.or]: filter.file.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.input_summary) {
where = {
...where,
[Op.and]: Utils.ilike(
'ai_jobs',
'input_summary',
filter.input_summary,
),
};
}
if (filter.output_summary) {
where = {
...where,
[Op.and]: Utils.ilike(
'ai_jobs',
'output_summary',
filter.output_summary,
),
};
}
if (filter.error_message) {
where = {
...where,
[Op.and]: Utils.ilike(
'ai_jobs',
'error_message',
filter.error_message,
),
};
}
if (filter.cost_usdRange) {
const [start, end] = filter.cost_usdRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
cost_usd: {
...where.cost_usd,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
cost_usd: {
...where.cost_usd,
[Op.lte]: end,
},
};
}
}
if (filter.queued_atRange) {
const [start, end] = filter.queued_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
queued_at: {
...where.queued_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
queued_at: {
...where.queued_at,
[Op.lte]: end,
},
};
}
}
if (filter.started_atRange) {
const [start, end] = filter.started_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
started_at: {
...where.started_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
started_at: {
...where.started_at,
[Op.lte]: end,
},
};
}
}
if (filter.completed_atRange) {
const [start, end] = filter.completed_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
completed_at: {
...where.completed_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
completed_at: {
...where.completed_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.job_type) {
where = {
...where,
job_type: filter.job_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_jobs.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'ai_jobs',
'job_type',
query,
),
],
};
}
const records = await db.ai_jobs.findAll({
attributes: [ 'id', 'job_type' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['job_type', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.job_type,
}));
}
};

View File

@ -0,0 +1,546 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Assistant_messagesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const assistant_messages = await db.assistant_messages.create(
{
id: data.id || undefined,
sender: data.sender
||
null
,
content: data.content
||
null
,
model_name: data.model_name
||
null
,
prompt_tokens: data.prompt_tokens
||
null
,
completion_tokens: data.completion_tokens
||
null
,
sent_at: data.sent_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await assistant_messages.setThread( data.thread || null, {
transaction,
});
return assistant_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 assistant_messagesData = data.map((item, index) => ({
id: item.id || undefined,
sender: item.sender
||
null
,
content: item.content
||
null
,
model_name: item.model_name
||
null
,
prompt_tokens: item.prompt_tokens
||
null
,
completion_tokens: item.completion_tokens
||
null
,
sent_at: item.sent_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const assistant_messages = await db.assistant_messages.bulkCreate(assistant_messagesData, { transaction });
// For each item created, replace relation files
return assistant_messages;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const assistant_messages = await db.assistant_messages.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.sender !== undefined) updatePayload.sender = data.sender;
if (data.content !== undefined) updatePayload.content = data.content;
if (data.model_name !== undefined) updatePayload.model_name = data.model_name;
if (data.prompt_tokens !== undefined) updatePayload.prompt_tokens = data.prompt_tokens;
if (data.completion_tokens !== undefined) updatePayload.completion_tokens = data.completion_tokens;
if (data.sent_at !== undefined) updatePayload.sent_at = data.sent_at;
updatePayload.updatedById = currentUser.id;
await assistant_messages.update(updatePayload, {transaction});
if (data.thread !== undefined) {
await assistant_messages.setThread(
data.thread,
{ transaction }
);
}
return assistant_messages;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const assistant_messages = await db.assistant_messages.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of assistant_messages) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of assistant_messages) {
await record.destroy({transaction});
}
});
return assistant_messages;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const assistant_messages = await db.assistant_messages.findByPk(id, options);
await assistant_messages.update({
deletedBy: currentUser.id
}, {
transaction,
});
await assistant_messages.destroy({
transaction
});
return assistant_messages;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const assistant_messages = await db.assistant_messages.findOne(
{ where },
{ transaction },
);
if (!assistant_messages) {
return assistant_messages;
}
const output = assistant_messages.get({plain: true});
output.thread = await assistant_messages.getThread({
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.assistant_threads,
as: 'thread',
where: filter.thread ? {
[Op.or]: [
{ id: { [Op.in]: filter.thread.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.thread.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.content) {
where = {
...where,
[Op.and]: Utils.ilike(
'assistant_messages',
'content',
filter.content,
),
};
}
if (filter.model_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'assistant_messages',
'model_name',
filter.model_name,
),
};
}
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.sent_atRange) {
const [start, end] = filter.sent_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sent_at: {
...where.sent_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sent_at: {
...where.sent_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.sender) {
where = {
...where,
sender: filter.sender,
};
}
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.assistant_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(
'assistant_messages',
'model_name',
query,
),
],
};
}
const records = await db.assistant_messages.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,511 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Assistant_threadsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const assistant_threads = await db.assistant_threads.create(
{
id: data.id || undefined,
title: data.title
||
null
,
thread_scope: data.thread_scope
||
null
,
is_pinned: data.is_pinned
||
false
,
last_activity_at: data.last_activity_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await assistant_threads.setOwner( data.owner || null, {
transaction,
});
await assistant_threads.setMatter( data.matter || null, {
transaction,
});
return assistant_threads;
}
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 assistant_threadsData = data.map((item, index) => ({
id: item.id || undefined,
title: item.title
||
null
,
thread_scope: item.thread_scope
||
null
,
is_pinned: item.is_pinned
||
false
,
last_activity_at: item.last_activity_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const assistant_threads = await db.assistant_threads.bulkCreate(assistant_threadsData, { transaction });
// For each item created, replace relation files
return assistant_threads;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const assistant_threads = await db.assistant_threads.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.title !== undefined) updatePayload.title = data.title;
if (data.thread_scope !== undefined) updatePayload.thread_scope = data.thread_scope;
if (data.is_pinned !== undefined) updatePayload.is_pinned = data.is_pinned;
if (data.last_activity_at !== undefined) updatePayload.last_activity_at = data.last_activity_at;
updatePayload.updatedById = currentUser.id;
await assistant_threads.update(updatePayload, {transaction});
if (data.owner !== undefined) {
await assistant_threads.setOwner(
data.owner,
{ transaction }
);
}
if (data.matter !== undefined) {
await assistant_threads.setMatter(
data.matter,
{ transaction }
);
}
return assistant_threads;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const assistant_threads = await db.assistant_threads.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of assistant_threads) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of assistant_threads) {
await record.destroy({transaction});
}
});
return assistant_threads;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const assistant_threads = await db.assistant_threads.findByPk(id, options);
await assistant_threads.update({
deletedBy: currentUser.id
}, {
transaction,
});
await assistant_threads.destroy({
transaction
});
return assistant_threads;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const assistant_threads = await db.assistant_threads.findOne(
{ where },
{ transaction },
);
if (!assistant_threads) {
return assistant_threads;
}
const output = assistant_threads.get({plain: true});
output.assistant_messages_thread = await assistant_threads.getAssistant_messages_thread({
transaction
});
output.owner = await assistant_threads.getOwner({
transaction
});
output.matter = await assistant_threads.getMatter({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.users,
as: 'owner',
where: filter.owner ? {
[Op.or]: [
{ id: { [Op.in]: filter.owner.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.owner.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.matters,
as: 'matter',
where: filter.matter ? {
[Op.or]: [
{ id: { [Op.in]: filter.matter.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.matter.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(
'assistant_threads',
'title',
filter.title,
),
};
}
if (filter.last_activity_atRange) {
const [start, end] = filter.last_activity_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
last_activity_at: {
...where.last_activity_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
last_activity_at: {
...where.last_activity_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.thread_scope) {
where = {
...where,
thread_scope: filter.thread_scope,
};
}
if (filter.is_pinned) {
where = {
...where,
is_pinned: filter.is_pinned,
};
}
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.assistant_threads.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(
'assistant_threads',
'title',
query,
),
],
};
}
const records = await db.assistant_threads.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,557 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Audit_eventsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const audit_events = await db.audit_events.create(
{
id: data.id || undefined,
event_name: data.event_name
||
null
,
event_category: data.event_category
||
null
,
event_details: data.event_details
||
null
,
occurred_at: data.occurred_at
||
null
,
ip_address: data.ip_address
||
null
,
user_agent: data.user_agent
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await audit_events.setActor( data.actor || null, {
transaction,
});
await audit_events.setMatter( data.matter || null, {
transaction,
});
return audit_events;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const audit_eventsData = data.map((item, index) => ({
id: item.id || undefined,
event_name: item.event_name
||
null
,
event_category: item.event_category
||
null
,
event_details: item.event_details
||
null
,
occurred_at: item.occurred_at
||
null
,
ip_address: item.ip_address
||
null
,
user_agent: item.user_agent
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const audit_events = await db.audit_events.bulkCreate(audit_eventsData, { transaction });
// For each item created, replace relation files
return audit_events;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const audit_events = await db.audit_events.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.event_name !== undefined) updatePayload.event_name = data.event_name;
if (data.event_category !== undefined) updatePayload.event_category = data.event_category;
if (data.event_details !== undefined) updatePayload.event_details = data.event_details;
if (data.occurred_at !== undefined) updatePayload.occurred_at = data.occurred_at;
if (data.ip_address !== undefined) updatePayload.ip_address = data.ip_address;
if (data.user_agent !== undefined) updatePayload.user_agent = data.user_agent;
updatePayload.updatedById = currentUser.id;
await audit_events.update(updatePayload, {transaction});
if (data.actor !== undefined) {
await audit_events.setActor(
data.actor,
{ transaction }
);
}
if (data.matter !== undefined) {
await audit_events.setMatter(
data.matter,
{ transaction }
);
}
return audit_events;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const audit_events = await db.audit_events.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of audit_events) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of audit_events) {
await record.destroy({transaction});
}
});
return audit_events;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const audit_events = await db.audit_events.findByPk(id, options);
await audit_events.update({
deletedBy: currentUser.id
}, {
transaction,
});
await audit_events.destroy({
transaction
});
return audit_events;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const audit_events = await db.audit_events.findOne(
{ where },
{ transaction },
);
if (!audit_events) {
return audit_events;
}
const output = audit_events.get({plain: true});
output.actor = await audit_events.getActor({
transaction
});
output.matter = await audit_events.getMatter({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.users,
as: 'actor',
where: filter.actor ? {
[Op.or]: [
{ id: { [Op.in]: filter.actor.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.actor.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.matters,
as: 'matter',
where: filter.matter ? {
[Op.or]: [
{ id: { [Op.in]: filter.matter.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.matter.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.event_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'audit_events',
'event_name',
filter.event_name,
),
};
}
if (filter.event_details) {
where = {
...where,
[Op.and]: Utils.ilike(
'audit_events',
'event_details',
filter.event_details,
),
};
}
if (filter.ip_address) {
where = {
...where,
[Op.and]: Utils.ilike(
'audit_events',
'ip_address',
filter.ip_address,
),
};
}
if (filter.user_agent) {
where = {
...where,
[Op.and]: Utils.ilike(
'audit_events',
'user_agent',
filter.user_agent,
),
};
}
if (filter.occurred_atRange) {
const [start, end] = filter.occurred_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
occurred_at: {
...where.occurred_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
occurred_at: {
...where.occurred_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.event_category) {
where = {
...where,
event_category: filter.event_category,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.audit_events.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'audit_events',
'event_name',
query,
),
],
};
}
const records = await db.audit_events.findAll({
attributes: [ 'id', 'event_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['event_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.event_name,
}));
}
};

View File

@ -0,0 +1,636 @@
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 Causation_analysesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const causation_analyses = await db.causation_analyses.create(
{
id: data.id || undefined,
analysis_title: data.analysis_title
||
null
,
status: data.status
||
null
,
theory_of_causation: data.theory_of_causation
||
null
,
supporting_facts: data.supporting_facts
||
null
,
weaknesses_and_gaps: data.weaknesses_and_gaps
||
null
,
generated_at: data.generated_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await causation_analyses.setRequested_by( data.requested_by || null, {
transaction,
});
await causation_analyses.setMatter( data.matter || null, {
transaction,
});
await causation_analyses.setExport_file( data.export_file || null, {
transaction,
});
await causation_analyses.setSource_files(data.source_files || [], {
transaction,
});
return causation_analyses;
}
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 causation_analysesData = data.map((item, index) => ({
id: item.id || undefined,
analysis_title: item.analysis_title
||
null
,
status: item.status
||
null
,
theory_of_causation: item.theory_of_causation
||
null
,
supporting_facts: item.supporting_facts
||
null
,
weaknesses_and_gaps: item.weaknesses_and_gaps
||
null
,
generated_at: item.generated_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const causation_analyses = await db.causation_analyses.bulkCreate(causation_analysesData, { transaction });
// For each item created, replace relation files
return causation_analyses;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const causation_analyses = await db.causation_analyses.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.analysis_title !== undefined) updatePayload.analysis_title = data.analysis_title;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.theory_of_causation !== undefined) updatePayload.theory_of_causation = data.theory_of_causation;
if (data.supporting_facts !== undefined) updatePayload.supporting_facts = data.supporting_facts;
if (data.weaknesses_and_gaps !== undefined) updatePayload.weaknesses_and_gaps = data.weaknesses_and_gaps;
if (data.generated_at !== undefined) updatePayload.generated_at = data.generated_at;
updatePayload.updatedById = currentUser.id;
await causation_analyses.update(updatePayload, {transaction});
if (data.requested_by !== undefined) {
await causation_analyses.setRequested_by(
data.requested_by,
{ transaction }
);
}
if (data.matter !== undefined) {
await causation_analyses.setMatter(
data.matter,
{ transaction }
);
}
if (data.export_file !== undefined) {
await causation_analyses.setExport_file(
data.export_file,
{ transaction }
);
}
if (data.source_files !== undefined) {
await causation_analyses.setSource_files(data.source_files, { transaction });
}
return causation_analyses;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const causation_analyses = await db.causation_analyses.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of causation_analyses) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of causation_analyses) {
await record.destroy({transaction});
}
});
return causation_analyses;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const causation_analyses = await db.causation_analyses.findByPk(id, options);
await causation_analyses.update({
deletedBy: currentUser.id
}, {
transaction,
});
await causation_analyses.destroy({
transaction
});
return causation_analyses;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const causation_analyses = await db.causation_analyses.findOne(
{ where },
{ transaction },
);
if (!causation_analyses) {
return causation_analyses;
}
const output = causation_analyses.get({plain: true});
output.requested_by = await causation_analyses.getRequested_by({
transaction
});
output.matter = await causation_analyses.getMatter({
transaction
});
output.source_files = await causation_analyses.getSource_files({
transaction
});
output.export_file = await causation_analyses.getExport_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.users,
as: 'requested_by',
where: filter.requested_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.requested_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.requested_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.matters,
as: 'matter',
where: filter.matter ? {
[Op.or]: [
{ id: { [Op.in]: filter.matter.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.matter.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.files,
as: 'export_file',
where: filter.export_file ? {
[Op.or]: [
{ id: { [Op.in]: filter.export_file.split('|').map(term => Utils.uuid(term)) } },
{
file_name: {
[Op.or]: filter.export_file.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.files,
as: 'source_files',
required: false,
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.analysis_title) {
where = {
...where,
[Op.and]: Utils.ilike(
'causation_analyses',
'analysis_title',
filter.analysis_title,
),
};
}
if (filter.theory_of_causation) {
where = {
...where,
[Op.and]: Utils.ilike(
'causation_analyses',
'theory_of_causation',
filter.theory_of_causation,
),
};
}
if (filter.supporting_facts) {
where = {
...where,
[Op.and]: Utils.ilike(
'causation_analyses',
'supporting_facts',
filter.supporting_facts,
),
};
}
if (filter.weaknesses_and_gaps) {
where = {
...where,
[Op.and]: Utils.ilike(
'causation_analyses',
'weaknesses_and_gaps',
filter.weaknesses_and_gaps,
),
};
}
if (filter.generated_atRange) {
const [start, end] = filter.generated_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
generated_at: {
...where.generated_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
generated_at: {
...where.generated_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.source_files) {
const searchTerms = filter.source_files.split('|');
include = [
{
model: db.files,
as: 'source_files_filter',
required: searchTerms.length > 0,
where: searchTerms.length > 0 ? {
[Op.or]: [
{ id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
{
file_name: {
[Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
}
}
]
} : undefined
},
...include,
]
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
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.causation_analyses.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(
'causation_analyses',
'analysis_title',
query,
),
],
};
}
const records = await db.causation_analyses.findAll({
attributes: [ 'id', 'analysis_title' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['analysis_title', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.analysis_title,
}));
}
};

View File

@ -0,0 +1,546 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Citator_checksDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const citator_checks = await db.citator_checks.create(
{
id: data.id || undefined,
standing: data.standing
||
null
,
analysis: data.analysis
||
null
,
conflicts_summary: data.conflicts_summary
||
null
,
checked_at: data.checked_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await citator_checks.setRequested_by( data.requested_by || null, {
transaction,
});
await citator_checks.setMatter( data.matter || null, {
transaction,
});
await citator_checks.setLegal_source( data.legal_source || null, {
transaction,
});
return citator_checks;
}
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 citator_checksData = data.map((item, index) => ({
id: item.id || undefined,
standing: item.standing
||
null
,
analysis: item.analysis
||
null
,
conflicts_summary: item.conflicts_summary
||
null
,
checked_at: item.checked_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const citator_checks = await db.citator_checks.bulkCreate(citator_checksData, { transaction });
// For each item created, replace relation files
return citator_checks;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const citator_checks = await db.citator_checks.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.standing !== undefined) updatePayload.standing = data.standing;
if (data.analysis !== undefined) updatePayload.analysis = data.analysis;
if (data.conflicts_summary !== undefined) updatePayload.conflicts_summary = data.conflicts_summary;
if (data.checked_at !== undefined) updatePayload.checked_at = data.checked_at;
updatePayload.updatedById = currentUser.id;
await citator_checks.update(updatePayload, {transaction});
if (data.requested_by !== undefined) {
await citator_checks.setRequested_by(
data.requested_by,
{ transaction }
);
}
if (data.matter !== undefined) {
await citator_checks.setMatter(
data.matter,
{ transaction }
);
}
if (data.legal_source !== undefined) {
await citator_checks.setLegal_source(
data.legal_source,
{ transaction }
);
}
return citator_checks;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const citator_checks = await db.citator_checks.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of citator_checks) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of citator_checks) {
await record.destroy({transaction});
}
});
return citator_checks;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const citator_checks = await db.citator_checks.findByPk(id, options);
await citator_checks.update({
deletedBy: currentUser.id
}, {
transaction,
});
await citator_checks.destroy({
transaction
});
return citator_checks;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const citator_checks = await db.citator_checks.findOne(
{ where },
{ transaction },
);
if (!citator_checks) {
return citator_checks;
}
const output = citator_checks.get({plain: true});
output.requested_by = await citator_checks.getRequested_by({
transaction
});
output.matter = await citator_checks.getMatter({
transaction
});
output.legal_source = await citator_checks.getLegal_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.users,
as: 'requested_by',
where: filter.requested_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.requested_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.requested_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.matters,
as: 'matter',
where: filter.matter ? {
[Op.or]: [
{ id: { [Op.in]: filter.matter.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.matter.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.legal_sources,
as: 'legal_source',
where: filter.legal_source ? {
[Op.or]: [
{ id: { [Op.in]: filter.legal_source.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.legal_source.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.analysis) {
where = {
...where,
[Op.and]: Utils.ilike(
'citator_checks',
'analysis',
filter.analysis,
),
};
}
if (filter.conflicts_summary) {
where = {
...where,
[Op.and]: Utils.ilike(
'citator_checks',
'conflicts_summary',
filter.conflicts_summary,
),
};
}
if (filter.checked_atRange) {
const [start, end] = filter.checked_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
checked_at: {
...where.checked_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
checked_at: {
...where.checked_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.standing) {
where = {
...where,
standing: filter.standing,
};
}
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.citator_checks.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(
'citator_checks',
'standing',
query,
),
],
};
}
const records = await db.citator_checks.findAll({
attributes: [ 'id', 'standing' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['standing', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.standing,
}));
}
};

View File

@ -0,0 +1,485 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Document_versionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const document_versions = await db.document_versions.create(
{
id: data.id || undefined,
version_number: data.version_number
||
null
,
change_source: data.change_source
||
null
,
content_snapshot: data.content_snapshot
||
null
,
saved_at: data.saved_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await document_versions.setDocument( data.document || null, {
transaction,
});
return document_versions;
}
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 document_versionsData = data.map((item, index) => ({
id: item.id || undefined,
version_number: item.version_number
||
null
,
change_source: item.change_source
||
null
,
content_snapshot: item.content_snapshot
||
null
,
saved_at: item.saved_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const document_versions = await db.document_versions.bulkCreate(document_versionsData, { transaction });
// For each item created, replace relation files
return document_versions;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const document_versions = await db.document_versions.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.version_number !== undefined) updatePayload.version_number = data.version_number;
if (data.change_source !== undefined) updatePayload.change_source = data.change_source;
if (data.content_snapshot !== undefined) updatePayload.content_snapshot = data.content_snapshot;
if (data.saved_at !== undefined) updatePayload.saved_at = data.saved_at;
updatePayload.updatedById = currentUser.id;
await document_versions.update(updatePayload, {transaction});
if (data.document !== undefined) {
await document_versions.setDocument(
data.document,
{ transaction }
);
}
return document_versions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const document_versions = await db.document_versions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of document_versions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of document_versions) {
await record.destroy({transaction});
}
});
return document_versions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const document_versions = await db.document_versions.findByPk(id, options);
await document_versions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await document_versions.destroy({
transaction
});
return document_versions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const document_versions = await db.document_versions.findOne(
{ where },
{ transaction },
);
if (!document_versions) {
return document_versions;
}
const output = document_versions.get({plain: true});
output.document = await document_versions.getDocument({
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.generated_documents,
as: 'document',
where: filter.document ? {
[Op.or]: [
{ id: { [Op.in]: filter.document.split('|').map(term => Utils.uuid(term)) } },
{
document_title: {
[Op.or]: filter.document.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.content_snapshot) {
where = {
...where,
[Op.and]: Utils.ilike(
'document_versions',
'content_snapshot',
filter.content_snapshot,
),
};
}
if (filter.version_numberRange) {
const [start, end] = filter.version_numberRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
version_number: {
...where.version_number,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
version_number: {
...where.version_number,
[Op.lte]: end,
},
};
}
}
if (filter.saved_atRange) {
const [start, end] = filter.saved_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
saved_at: {
...where.saved_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
saved_at: {
...where.saved_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.change_source) {
where = {
...where,
change_source: filter.change_source,
};
}
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.document_versions.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(
'document_versions',
'change_source',
query,
),
],
};
}
const records = await db.document_versions.findAll({
attributes: [ 'id', 'change_source' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['change_source', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.change_source,
}));
}
};

View File

@ -0,0 +1,444 @@
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 Feature_flagsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const feature_flags = await db.feature_flags.create(
{
id: data.id || undefined,
key: data.key
||
null
,
name: data.name
||
null
,
description: data.description
||
null
,
default_plan_access: data.default_plan_access
||
null
,
is_enabled: data.is_enabled
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return feature_flags;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const feature_flagsData = data.map((item, index) => ({
id: item.id || undefined,
key: item.key
||
null
,
name: item.name
||
null
,
description: item.description
||
null
,
default_plan_access: item.default_plan_access
||
null
,
is_enabled: item.is_enabled
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const feature_flags = await db.feature_flags.bulkCreate(feature_flagsData, { transaction });
// For each item created, replace relation files
return feature_flags;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const feature_flags = await db.feature_flags.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.key !== undefined) updatePayload.key = data.key;
if (data.name !== undefined) updatePayload.name = data.name;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.default_plan_access !== undefined) updatePayload.default_plan_access = data.default_plan_access;
if (data.is_enabled !== undefined) updatePayload.is_enabled = data.is_enabled;
updatePayload.updatedById = currentUser.id;
await feature_flags.update(updatePayload, {transaction});
return feature_flags;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const feature_flags = await db.feature_flags.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of feature_flags) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of feature_flags) {
await record.destroy({transaction});
}
});
return feature_flags;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const feature_flags = await db.feature_flags.findByPk(id, options);
await feature_flags.update({
deletedBy: currentUser.id
}, {
transaction,
});
await feature_flags.destroy({
transaction
});
return feature_flags;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const feature_flags = await db.feature_flags.findOne(
{ where },
{ transaction },
);
if (!feature_flags) {
return feature_flags;
}
const output = feature_flags.get({plain: true});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.key) {
where = {
...where,
[Op.and]: Utils.ilike(
'feature_flags',
'key',
filter.key,
),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'feature_flags',
'name',
filter.name,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'feature_flags',
'description',
filter.description,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.default_plan_access) {
where = {
...where,
default_plan_access: filter.default_plan_access,
};
}
if (filter.is_enabled) {
where = {
...where,
is_enabled: filter.is_enabled,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.feature_flags.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'feature_flags',
'name',
query,
),
],
};
}
const records = await db.feature_flags.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,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,590 @@
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 File_extractionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const file_extractions = await db.file_extractions.create(
{
id: data.id || undefined,
extraction_type: data.extraction_type
||
null
,
status: data.status
||
null
,
language: data.language
||
null
,
page_count: data.page_count
||
null
,
result_text: data.result_text
||
null
,
started_at: data.started_at
||
null
,
finished_at: data.finished_at
||
null
,
error_message: data.error_message
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await file_extractions.setFile( data.file || null, {
transaction,
});
return file_extractions;
}
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 file_extractionsData = data.map((item, index) => ({
id: item.id || undefined,
extraction_type: item.extraction_type
||
null
,
status: item.status
||
null
,
language: item.language
||
null
,
page_count: item.page_count
||
null
,
result_text: item.result_text
||
null
,
started_at: item.started_at
||
null
,
finished_at: item.finished_at
||
null
,
error_message: item.error_message
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const file_extractions = await db.file_extractions.bulkCreate(file_extractionsData, { transaction });
// For each item created, replace relation files
return file_extractions;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const file_extractions = await db.file_extractions.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.extraction_type !== undefined) updatePayload.extraction_type = data.extraction_type;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.language !== undefined) updatePayload.language = data.language;
if (data.page_count !== undefined) updatePayload.page_count = data.page_count;
if (data.result_text !== undefined) updatePayload.result_text = data.result_text;
if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
if (data.finished_at !== undefined) updatePayload.finished_at = data.finished_at;
if (data.error_message !== undefined) updatePayload.error_message = data.error_message;
updatePayload.updatedById = currentUser.id;
await file_extractions.update(updatePayload, {transaction});
if (data.file !== undefined) {
await file_extractions.setFile(
data.file,
{ transaction }
);
}
return file_extractions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const file_extractions = await db.file_extractions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of file_extractions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of file_extractions) {
await record.destroy({transaction});
}
});
return file_extractions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const file_extractions = await db.file_extractions.findByPk(id, options);
await file_extractions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await file_extractions.destroy({
transaction
});
return file_extractions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const file_extractions = await db.file_extractions.findOne(
{ where },
{ transaction },
);
if (!file_extractions) {
return file_extractions;
}
const output = file_extractions.get({plain: true});
output.file = await file_extractions.getFile({
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.files,
as: 'file',
where: filter.file ? {
[Op.or]: [
{ id: { [Op.in]: filter.file.split('|').map(term => Utils.uuid(term)) } },
{
file_name: {
[Op.or]: filter.file.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.language) {
where = {
...where,
[Op.and]: Utils.ilike(
'file_extractions',
'language',
filter.language,
),
};
}
if (filter.result_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'file_extractions',
'result_text',
filter.result_text,
),
};
}
if (filter.error_message) {
where = {
...where,
[Op.and]: Utils.ilike(
'file_extractions',
'error_message',
filter.error_message,
),
};
}
if (filter.page_countRange) {
const [start, end] = filter.page_countRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
page_count: {
...where.page_count,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
page_count: {
...where.page_count,
[Op.lte]: end,
},
};
}
}
if (filter.started_atRange) {
const [start, end] = filter.started_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
started_at: {
...where.started_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
started_at: {
...where.started_at,
[Op.lte]: end,
},
};
}
}
if (filter.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.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.extraction_type) {
where = {
...where,
extraction_type: filter.extraction_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.file_extractions.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(
'file_extractions',
'extraction_type',
query,
),
],
};
}
const records = await db.file_extractions.findAll({
attributes: [ 'id', 'extraction_type' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['extraction_type', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.extraction_type,
}));
}
};

728
backend/src/db/api/files.js Normal file
View File

@ -0,0 +1,728 @@
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 FilesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const files = await db.files.create(
{
id: data.id || undefined,
file_name: data.file_name
||
null
,
content_type: data.content_type
||
null
,
file_extension: data.file_extension
||
null
,
size_bytes: data.size_bytes
||
null
,
storage_provider: data.storage_provider
||
null
,
storage_key: data.storage_key
||
null
,
checksum_sha256: data.checksum_sha256
||
null
,
is_ocr_required: data.is_ocr_required
||
false
,
processing_status: data.processing_status
||
null
,
uploaded_at: data.uploaded_at
||
null
,
tags: data.tags
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await files.setOwner( data.owner || null, {
transaction,
});
await files.setMatter( data.matter || null, {
transaction,
});
return files;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const filesData = data.map((item, index) => ({
id: item.id || undefined,
file_name: item.file_name
||
null
,
content_type: item.content_type
||
null
,
file_extension: item.file_extension
||
null
,
size_bytes: item.size_bytes
||
null
,
storage_provider: item.storage_provider
||
null
,
storage_key: item.storage_key
||
null
,
checksum_sha256: item.checksum_sha256
||
null
,
is_ocr_required: item.is_ocr_required
||
false
,
processing_status: item.processing_status
||
null
,
uploaded_at: item.uploaded_at
||
null
,
tags: item.tags
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const files = await db.files.bulkCreate(filesData, { transaction });
// For each item created, replace relation files
return files;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const files = await db.files.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.file_name !== undefined) updatePayload.file_name = data.file_name;
if (data.content_type !== undefined) updatePayload.content_type = data.content_type;
if (data.file_extension !== undefined) updatePayload.file_extension = data.file_extension;
if (data.size_bytes !== undefined) updatePayload.size_bytes = data.size_bytes;
if (data.storage_provider !== undefined) updatePayload.storage_provider = data.storage_provider;
if (data.storage_key !== undefined) updatePayload.storage_key = data.storage_key;
if (data.checksum_sha256 !== undefined) updatePayload.checksum_sha256 = data.checksum_sha256;
if (data.is_ocr_required !== undefined) updatePayload.is_ocr_required = data.is_ocr_required;
if (data.processing_status !== undefined) updatePayload.processing_status = data.processing_status;
if (data.uploaded_at !== undefined) updatePayload.uploaded_at = data.uploaded_at;
if (data.tags !== undefined) updatePayload.tags = data.tags;
updatePayload.updatedById = currentUser.id;
await files.update(updatePayload, {transaction});
if (data.owner !== undefined) {
await files.setOwner(
data.owner,
{ transaction }
);
}
if (data.matter !== undefined) {
await files.setMatter(
data.matter,
{ transaction }
);
}
return files;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const files = await db.files.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of files) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of files) {
await record.destroy({transaction});
}
});
return files;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const files = await db.files.findByPk(id, options);
await files.update({
deletedBy: currentUser.id
}, {
transaction,
});
await files.destroy({
transaction
});
return files;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const files = await db.files.findOne(
{ where },
{ transaction },
);
if (!files) {
return files;
}
const output = files.get({plain: true});
output.file_extractions_file = await files.getFile_extractions_file({
transaction
});
output.ai_jobs_file = await files.getAi_jobs_file({
transaction
});
output.legal_templates_source_file = await files.getLegal_templates_source_file({
transaction
});
output.generated_documents_export_file = await files.getGenerated_documents_export_file({
transaction
});
output.mock_trial_turns_audio_file = await files.getMock_trial_turns_audio_file({
transaction
});
output.transcription_jobs_media_file = await files.getTranscription_jobs_media_file({
transaction
});
output.transcription_jobs_export_file = await files.getTranscription_jobs_export_file({
transaction
});
output.medical_chronology_reports_export_file = await files.getMedical_chronology_reports_export_file({
transaction
});
output.medical_events_linked_file = await files.getMedical_events_linked_file({
transaction
});
output.causation_analyses_export_file = await files.getCausation_analyses_export_file({
transaction
});
output.owner = await files.getOwner({
transaction
});
output.matter = await files.getMatter({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.users,
as: 'owner',
where: filter.owner ? {
[Op.or]: [
{ id: { [Op.in]: filter.owner.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.owner.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.matters,
as: 'matter',
where: filter.matter ? {
[Op.or]: [
{ id: { [Op.in]: filter.matter.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.matter.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.file_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'files',
'file_name',
filter.file_name,
),
};
}
if (filter.content_type) {
where = {
...where,
[Op.and]: Utils.ilike(
'files',
'content_type',
filter.content_type,
),
};
}
if (filter.file_extension) {
where = {
...where,
[Op.and]: Utils.ilike(
'files',
'file_extension',
filter.file_extension,
),
};
}
if (filter.storage_provider) {
where = {
...where,
[Op.and]: Utils.ilike(
'files',
'storage_provider',
filter.storage_provider,
),
};
}
if (filter.storage_key) {
where = {
...where,
[Op.and]: Utils.ilike(
'files',
'storage_key',
filter.storage_key,
),
};
}
if (filter.checksum_sha256) {
where = {
...where,
[Op.and]: Utils.ilike(
'files',
'checksum_sha256',
filter.checksum_sha256,
),
};
}
if (filter.tags) {
where = {
...where,
[Op.and]: Utils.ilike(
'files',
'tags',
filter.tags,
),
};
}
if (filter.size_bytesRange) {
const [start, end] = filter.size_bytesRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
size_bytes: {
...where.size_bytes,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
size_bytes: {
...where.size_bytes,
[Op.lte]: end,
},
};
}
}
if (filter.uploaded_atRange) {
const [start, end] = filter.uploaded_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
uploaded_at: {
...where.uploaded_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
uploaded_at: {
...where.uploaded_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.is_ocr_required) {
where = {
...where,
is_ocr_required: filter.is_ocr_required,
};
}
if (filter.processing_status) {
where = {
...where,
processing_status: filter.processing_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.files.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'files',
'file_name',
query,
),
],
};
}
const records = await db.files.findAll({
attributes: [ 'id', 'file_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['file_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.file_name,
}));
}
};

View File

@ -0,0 +1,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 Generated_documentsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const generated_documents = await db.generated_documents.create(
{
id: data.id || undefined,
document_title: data.document_title
||
null
,
document_type: data.document_type
||
null
,
format: data.format
||
null
,
content: data.content
||
null
,
last_edited_at: data.last_edited_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await generated_documents.setOwner( data.owner || null, {
transaction,
});
await generated_documents.setMatter( data.matter || null, {
transaction,
});
await generated_documents.setTemplate( data.template || null, {
transaction,
});
await generated_documents.setExport_file( data.export_file || null, {
transaction,
});
return generated_documents;
}
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 generated_documentsData = data.map((item, index) => ({
id: item.id || undefined,
document_title: item.document_title
||
null
,
document_type: item.document_type
||
null
,
format: item.format
||
null
,
content: item.content
||
null
,
last_edited_at: item.last_edited_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const generated_documents = await db.generated_documents.bulkCreate(generated_documentsData, { transaction });
// For each item created, replace relation files
return generated_documents;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const generated_documents = await db.generated_documents.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.document_title !== undefined) updatePayload.document_title = data.document_title;
if (data.document_type !== undefined) updatePayload.document_type = data.document_type;
if (data.format !== undefined) updatePayload.format = data.format;
if (data.content !== undefined) updatePayload.content = data.content;
if (data.last_edited_at !== undefined) updatePayload.last_edited_at = data.last_edited_at;
updatePayload.updatedById = currentUser.id;
await generated_documents.update(updatePayload, {transaction});
if (data.owner !== undefined) {
await generated_documents.setOwner(
data.owner,
{ transaction }
);
}
if (data.matter !== undefined) {
await generated_documents.setMatter(
data.matter,
{ transaction }
);
}
if (data.template !== undefined) {
await generated_documents.setTemplate(
data.template,
{ transaction }
);
}
if (data.export_file !== undefined) {
await generated_documents.setExport_file(
data.export_file,
{ transaction }
);
}
return generated_documents;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const generated_documents = await db.generated_documents.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of generated_documents) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of generated_documents) {
await record.destroy({transaction});
}
});
return generated_documents;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const generated_documents = await db.generated_documents.findByPk(id, options);
await generated_documents.update({
deletedBy: currentUser.id
}, {
transaction,
});
await generated_documents.destroy({
transaction
});
return generated_documents;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const generated_documents = await db.generated_documents.findOne(
{ where },
{ transaction },
);
if (!generated_documents) {
return generated_documents;
}
const output = generated_documents.get({plain: true});
output.document_versions_document = await generated_documents.getDocument_versions_document({
transaction
});
output.owner = await generated_documents.getOwner({
transaction
});
output.matter = await generated_documents.getMatter({
transaction
});
output.template = await generated_documents.getTemplate({
transaction
});
output.export_file = await generated_documents.getExport_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.users,
as: 'owner',
where: filter.owner ? {
[Op.or]: [
{ id: { [Op.in]: filter.owner.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.owner.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.matters,
as: 'matter',
where: filter.matter ? {
[Op.or]: [
{ id: { [Op.in]: filter.matter.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.matter.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.legal_templates,
as: 'template',
where: filter.template ? {
[Op.or]: [
{ id: { [Op.in]: filter.template.split('|').map(term => Utils.uuid(term)) } },
{
template_name: {
[Op.or]: filter.template.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.files,
as: 'export_file',
where: filter.export_file ? {
[Op.or]: [
{ id: { [Op.in]: filter.export_file.split('|').map(term => Utils.uuid(term)) } },
{
file_name: {
[Op.or]: filter.export_file.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.document_title) {
where = {
...where,
[Op.and]: Utils.ilike(
'generated_documents',
'document_title',
filter.document_title,
),
};
}
if (filter.content) {
where = {
...where,
[Op.and]: Utils.ilike(
'generated_documents',
'content',
filter.content,
),
};
}
if (filter.last_edited_atRange) {
const [start, end] = filter.last_edited_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
last_edited_at: {
...where.last_edited_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
last_edited_at: {
...where.last_edited_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.document_type) {
where = {
...where,
document_type: filter.document_type,
};
}
if (filter.format) {
where = {
...where,
format: filter.format,
};
}
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.generated_documents.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(
'generated_documents',
'document_title',
query,
),
],
};
}
const records = await db.generated_documents.findAll({
attributes: [ 'id', 'document_title' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['document_title', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.document_title,
}));
}
};

View File

@ -0,0 +1,600 @@
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 Legal_sourcesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const legal_sources = await db.legal_sources.create(
{
id: data.id || undefined,
source_type: data.source_type
||
null
,
jurisdiction: data.jurisdiction
||
null
,
title: data.title
||
null
,
citation: data.citation
||
null
,
decision_date: data.decision_date
||
null
,
court: data.court
||
null
,
full_text: data.full_text
||
null
,
summary: data.summary
||
null
,
source_url: data.source_url
||
null
,
last_updated_at: data.last_updated_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return legal_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 legal_sourcesData = data.map((item, index) => ({
id: item.id || undefined,
source_type: item.source_type
||
null
,
jurisdiction: item.jurisdiction
||
null
,
title: item.title
||
null
,
citation: item.citation
||
null
,
decision_date: item.decision_date
||
null
,
court: item.court
||
null
,
full_text: item.full_text
||
null
,
summary: item.summary
||
null
,
source_url: item.source_url
||
null
,
last_updated_at: item.last_updated_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const legal_sources = await db.legal_sources.bulkCreate(legal_sourcesData, { transaction });
// For each item created, replace relation files
return legal_sources;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const legal_sources = await db.legal_sources.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.source_type !== undefined) updatePayload.source_type = data.source_type;
if (data.jurisdiction !== undefined) updatePayload.jurisdiction = data.jurisdiction;
if (data.title !== undefined) updatePayload.title = data.title;
if (data.citation !== undefined) updatePayload.citation = data.citation;
if (data.decision_date !== undefined) updatePayload.decision_date = data.decision_date;
if (data.court !== undefined) updatePayload.court = data.court;
if (data.full_text !== undefined) updatePayload.full_text = data.full_text;
if (data.summary !== undefined) updatePayload.summary = data.summary;
if (data.source_url !== undefined) updatePayload.source_url = data.source_url;
if (data.last_updated_at !== undefined) updatePayload.last_updated_at = data.last_updated_at;
updatePayload.updatedById = currentUser.id;
await legal_sources.update(updatePayload, {transaction});
return legal_sources;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const legal_sources = await db.legal_sources.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of legal_sources) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of legal_sources) {
await record.destroy({transaction});
}
});
return legal_sources;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const legal_sources = await db.legal_sources.findByPk(id, options);
await legal_sources.update({
deletedBy: currentUser.id
}, {
transaction,
});
await legal_sources.destroy({
transaction
});
return legal_sources;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const legal_sources = await db.legal_sources.findOne(
{ where },
{ transaction },
);
if (!legal_sources) {
return legal_sources;
}
const output = legal_sources.get({plain: true});
output.research_results_legal_source = await legal_sources.getResearch_results_legal_source({
transaction
});
output.citator_checks_legal_source = await legal_sources.getCitator_checks_legal_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 = [
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.jurisdiction) {
where = {
...where,
[Op.and]: Utils.ilike(
'legal_sources',
'jurisdiction',
filter.jurisdiction,
),
};
}
if (filter.title) {
where = {
...where,
[Op.and]: Utils.ilike(
'legal_sources',
'title',
filter.title,
),
};
}
if (filter.citation) {
where = {
...where,
[Op.and]: Utils.ilike(
'legal_sources',
'citation',
filter.citation,
),
};
}
if (filter.court) {
where = {
...where,
[Op.and]: Utils.ilike(
'legal_sources',
'court',
filter.court,
),
};
}
if (filter.full_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'legal_sources',
'full_text',
filter.full_text,
),
};
}
if (filter.summary) {
where = {
...where,
[Op.and]: Utils.ilike(
'legal_sources',
'summary',
filter.summary,
),
};
}
if (filter.source_url) {
where = {
...where,
[Op.and]: Utils.ilike(
'legal_sources',
'source_url',
filter.source_url,
),
};
}
if (filter.decision_dateRange) {
const [start, end] = filter.decision_dateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
decision_date: {
...where.decision_date,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
decision_date: {
...where.decision_date,
[Op.lte]: end,
},
};
}
}
if (filter.last_updated_atRange) {
const [start, end] = filter.last_updated_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
last_updated_at: {
...where.last_updated_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
last_updated_at: {
...where.last_updated_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.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.legal_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(
'legal_sources',
'title',
query,
),
],
};
}
const records = await db.legal_sources.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,550 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Legal_templatesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const legal_templates = await db.legal_templates.create(
{
id: data.id || undefined,
template_name: data.template_name
||
null
,
template_category: data.template_category
||
null
,
jurisdiction: data.jurisdiction
||
null
,
description: data.description
||
null
,
template_body: data.template_body
||
null
,
is_public: data.is_public
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await legal_templates.setOwner( data.owner || null, {
transaction,
});
await legal_templates.setSource_file( data.source_file || null, {
transaction,
});
return legal_templates;
}
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 legal_templatesData = data.map((item, index) => ({
id: item.id || undefined,
template_name: item.template_name
||
null
,
template_category: item.template_category
||
null
,
jurisdiction: item.jurisdiction
||
null
,
description: item.description
||
null
,
template_body: item.template_body
||
null
,
is_public: item.is_public
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const legal_templates = await db.legal_templates.bulkCreate(legal_templatesData, { transaction });
// For each item created, replace relation files
return legal_templates;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const legal_templates = await db.legal_templates.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.template_name !== undefined) updatePayload.template_name = data.template_name;
if (data.template_category !== undefined) updatePayload.template_category = data.template_category;
if (data.jurisdiction !== undefined) updatePayload.jurisdiction = data.jurisdiction;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.template_body !== undefined) updatePayload.template_body = data.template_body;
if (data.is_public !== undefined) updatePayload.is_public = data.is_public;
updatePayload.updatedById = currentUser.id;
await legal_templates.update(updatePayload, {transaction});
if (data.owner !== undefined) {
await legal_templates.setOwner(
data.owner,
{ transaction }
);
}
if (data.source_file !== undefined) {
await legal_templates.setSource_file(
data.source_file,
{ transaction }
);
}
return legal_templates;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const legal_templates = await db.legal_templates.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of legal_templates) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of legal_templates) {
await record.destroy({transaction});
}
});
return legal_templates;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const legal_templates = await db.legal_templates.findByPk(id, options);
await legal_templates.update({
deletedBy: currentUser.id
}, {
transaction,
});
await legal_templates.destroy({
transaction
});
return legal_templates;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const legal_templates = await db.legal_templates.findOne(
{ where },
{ transaction },
);
if (!legal_templates) {
return legal_templates;
}
const output = legal_templates.get({plain: true});
output.template_fields_template = await legal_templates.getTemplate_fields_template({
transaction
});
output.generated_documents_template = await legal_templates.getGenerated_documents_template({
transaction
});
output.owner = await legal_templates.getOwner({
transaction
});
output.source_file = await legal_templates.getSource_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.users,
as: 'owner',
where: filter.owner ? {
[Op.or]: [
{ id: { [Op.in]: filter.owner.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.owner.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.files,
as: 'source_file',
where: filter.source_file ? {
[Op.or]: [
{ id: { [Op.in]: filter.source_file.split('|').map(term => Utils.uuid(term)) } },
{
file_name: {
[Op.or]: filter.source_file.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.template_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'legal_templates',
'template_name',
filter.template_name,
),
};
}
if (filter.jurisdiction) {
where = {
...where,
[Op.and]: Utils.ilike(
'legal_templates',
'jurisdiction',
filter.jurisdiction,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'legal_templates',
'description',
filter.description,
),
};
}
if (filter.template_body) {
where = {
...where,
[Op.and]: Utils.ilike(
'legal_templates',
'template_body',
filter.template_body,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.template_category) {
where = {
...where,
template_category: filter.template_category,
};
}
if (filter.is_public) {
where = {
...where,
is_public: filter.is_public,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.legal_templates.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(
'legal_templates',
'template_name',
query,
),
],
};
}
const records = await db.legal_templates.findAll({
attributes: [ 'id', 'template_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['template_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.template_name,
}));
}
};

View File

@ -0,0 +1,531 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Matter_partiesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const matter_parties = await db.matter_parties.create(
{
id: data.id || undefined,
party_role: data.party_role
||
null
,
display_name: data.display_name
||
null
,
organization_name: data.organization_name
||
null
,
email: data.email
||
null
,
phone: data.phone
||
null
,
address: data.address
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await matter_parties.setMatter( data.matter || null, {
transaction,
});
return matter_parties;
}
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 matter_partiesData = data.map((item, index) => ({
id: item.id || undefined,
party_role: item.party_role
||
null
,
display_name: item.display_name
||
null
,
organization_name: item.organization_name
||
null
,
email: item.email
||
null
,
phone: item.phone
||
null
,
address: item.address
||
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 matter_parties = await db.matter_parties.bulkCreate(matter_partiesData, { transaction });
// For each item created, replace relation files
return matter_parties;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const matter_parties = await db.matter_parties.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.party_role !== undefined) updatePayload.party_role = data.party_role;
if (data.display_name !== undefined) updatePayload.display_name = data.display_name;
if (data.organization_name !== undefined) updatePayload.organization_name = data.organization_name;
if (data.email !== undefined) updatePayload.email = data.email;
if (data.phone !== undefined) updatePayload.phone = data.phone;
if (data.address !== undefined) updatePayload.address = data.address;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await matter_parties.update(updatePayload, {transaction});
if (data.matter !== undefined) {
await matter_parties.setMatter(
data.matter,
{ transaction }
);
}
return matter_parties;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const matter_parties = await db.matter_parties.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of matter_parties) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of matter_parties) {
await record.destroy({transaction});
}
});
return matter_parties;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const matter_parties = await db.matter_parties.findByPk(id, options);
await matter_parties.update({
deletedBy: currentUser.id
}, {
transaction,
});
await matter_parties.destroy({
transaction
});
return matter_parties;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const matter_parties = await db.matter_parties.findOne(
{ where },
{ transaction },
);
if (!matter_parties) {
return matter_parties;
}
const output = matter_parties.get({plain: true});
output.matter = await matter_parties.getMatter({
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.matters,
as: 'matter',
where: filter.matter ? {
[Op.or]: [
{ id: { [Op.in]: filter.matter.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.matter.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.display_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'matter_parties',
'display_name',
filter.display_name,
),
};
}
if (filter.organization_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'matter_parties',
'organization_name',
filter.organization_name,
),
};
}
if (filter.email) {
where = {
...where,
[Op.and]: Utils.ilike(
'matter_parties',
'email',
filter.email,
),
};
}
if (filter.phone) {
where = {
...where,
[Op.and]: Utils.ilike(
'matter_parties',
'phone',
filter.phone,
),
};
}
if (filter.address) {
where = {
...where,
[Op.and]: Utils.ilike(
'matter_parties',
'address',
filter.address,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'matter_parties',
'notes',
filter.notes,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.party_role) {
where = {
...where,
party_role: filter.party_role,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.matter_parties.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(
'matter_parties',
'display_name',
query,
),
],
};
}
const records = await db.matter_parties.findAll({
attributes: [ 'id', 'display_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['display_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.display_name,
}));
}
};

View File

@ -0,0 +1,649 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class MattersDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const matters = await db.matters.create(
{
id: data.id || undefined,
title: data.title
||
null
,
matter_type: data.matter_type
||
null
,
status: data.status
||
null
,
jurisdiction: data.jurisdiction
||
null
,
court_name: data.court_name
||
null
,
case_number: data.case_number
||
null
,
filed_at: data.filed_at
||
null
,
next_hearing_at: data.next_hearing_at
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await matters.setOwner( data.owner || null, {
transaction,
});
return matters;
}
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 mattersData = data.map((item, index) => ({
id: item.id || undefined,
title: item.title
||
null
,
matter_type: item.matter_type
||
null
,
status: item.status
||
null
,
jurisdiction: item.jurisdiction
||
null
,
court_name: item.court_name
||
null
,
case_number: item.case_number
||
null
,
filed_at: item.filed_at
||
null
,
next_hearing_at: item.next_hearing_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 matters = await db.matters.bulkCreate(mattersData, { transaction });
// For each item created, replace relation files
return matters;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const matters = await db.matters.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.title !== undefined) updatePayload.title = data.title;
if (data.matter_type !== undefined) updatePayload.matter_type = data.matter_type;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.jurisdiction !== undefined) updatePayload.jurisdiction = data.jurisdiction;
if (data.court_name !== undefined) updatePayload.court_name = data.court_name;
if (data.case_number !== undefined) updatePayload.case_number = data.case_number;
if (data.filed_at !== undefined) updatePayload.filed_at = data.filed_at;
if (data.next_hearing_at !== undefined) updatePayload.next_hearing_at = data.next_hearing_at;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await matters.update(updatePayload, {transaction});
if (data.owner !== undefined) {
await matters.setOwner(
data.owner,
{ transaction }
);
}
return matters;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const matters = await db.matters.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of matters) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of matters) {
await record.destroy({transaction});
}
});
return matters;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const matters = await db.matters.findByPk(id, options);
await matters.update({
deletedBy: currentUser.id
}, {
transaction,
});
await matters.destroy({
transaction
});
return matters;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const matters = await db.matters.findOne(
{ where },
{ transaction },
);
if (!matters) {
return matters;
}
const output = matters.get({plain: true});
output.matter_parties_matter = await matters.getMatter_parties_matter({
transaction
});
output.files_matter = await matters.getFiles_matter({
transaction
});
output.assistant_threads_matter = await matters.getAssistant_threads_matter({
transaction
});
output.ai_jobs_matter = await matters.getAi_jobs_matter({
transaction
});
output.generated_documents_matter = await matters.getGenerated_documents_matter({
transaction
});
output.research_queries_matter = await matters.getResearch_queries_matter({
transaction
});
output.citator_checks_matter = await matters.getCitator_checks_matter({
transaction
});
output.mock_trials_matter = await matters.getMock_trials_matter({
transaction
});
output.transcription_jobs_matter = await matters.getTranscription_jobs_matter({
transaction
});
output.medical_chronology_reports_matter = await matters.getMedical_chronology_reports_matter({
transaction
});
output.causation_analyses_matter = await matters.getCausation_analyses_matter({
transaction
});
output.audit_events_matter = await matters.getAudit_events_matter({
transaction
});
output.owner = await matters.getOwner({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.users,
as: 'owner',
where: filter.owner ? {
[Op.or]: [
{ id: { [Op.in]: filter.owner.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.owner.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.title) {
where = {
...where,
[Op.and]: Utils.ilike(
'matters',
'title',
filter.title,
),
};
}
if (filter.jurisdiction) {
where = {
...where,
[Op.and]: Utils.ilike(
'matters',
'jurisdiction',
filter.jurisdiction,
),
};
}
if (filter.court_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'matters',
'court_name',
filter.court_name,
),
};
}
if (filter.case_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'matters',
'case_number',
filter.case_number,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'matters',
'notes',
filter.notes,
),
};
}
if (filter.filed_atRange) {
const [start, end] = filter.filed_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
filed_at: {
...where.filed_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
filed_at: {
...where.filed_at,
[Op.lte]: end,
},
};
}
}
if (filter.next_hearing_atRange) {
const [start, end] = filter.next_hearing_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
next_hearing_at: {
...where.next_hearing_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
next_hearing_at: {
...where.next_hearing_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.matter_type) {
where = {
...where,
matter_type: filter.matter_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.matters.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(
'matters',
'title',
query,
),
],
};
}
const records = await db.matters.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,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 Medical_chronology_reportsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const medical_chronology_reports = await db.medical_chronology_reports.create(
{
id: data.id || undefined,
report_title: data.report_title
||
null
,
status: data.status
||
null
,
overview: data.overview
||
null
,
generated_at: data.generated_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await medical_chronology_reports.setRequested_by( data.requested_by || null, {
transaction,
});
await medical_chronology_reports.setMatter( data.matter || null, {
transaction,
});
await medical_chronology_reports.setExport_file( data.export_file || null, {
transaction,
});
await medical_chronology_reports.setSource_files(data.source_files || [], {
transaction,
});
return medical_chronology_reports;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const medical_chronology_reportsData = data.map((item, index) => ({
id: item.id || undefined,
report_title: item.report_title
||
null
,
status: item.status
||
null
,
overview: item.overview
||
null
,
generated_at: item.generated_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const medical_chronology_reports = await db.medical_chronology_reports.bulkCreate(medical_chronology_reportsData, { transaction });
// For each item created, replace relation files
return medical_chronology_reports;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const medical_chronology_reports = await db.medical_chronology_reports.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.report_title !== undefined) updatePayload.report_title = data.report_title;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.overview !== undefined) updatePayload.overview = data.overview;
if (data.generated_at !== undefined) updatePayload.generated_at = data.generated_at;
updatePayload.updatedById = currentUser.id;
await medical_chronology_reports.update(updatePayload, {transaction});
if (data.requested_by !== undefined) {
await medical_chronology_reports.setRequested_by(
data.requested_by,
{ transaction }
);
}
if (data.matter !== undefined) {
await medical_chronology_reports.setMatter(
data.matter,
{ transaction }
);
}
if (data.export_file !== undefined) {
await medical_chronology_reports.setExport_file(
data.export_file,
{ transaction }
);
}
if (data.source_files !== undefined) {
await medical_chronology_reports.setSource_files(data.source_files, { transaction });
}
return medical_chronology_reports;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const medical_chronology_reports = await db.medical_chronology_reports.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of medical_chronology_reports) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of medical_chronology_reports) {
await record.destroy({transaction});
}
});
return medical_chronology_reports;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const medical_chronology_reports = await db.medical_chronology_reports.findByPk(id, options);
await medical_chronology_reports.update({
deletedBy: currentUser.id
}, {
transaction,
});
await medical_chronology_reports.destroy({
transaction
});
return medical_chronology_reports;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const medical_chronology_reports = await db.medical_chronology_reports.findOne(
{ where },
{ transaction },
);
if (!medical_chronology_reports) {
return medical_chronology_reports;
}
const output = medical_chronology_reports.get({plain: true});
output.medical_events_report = await medical_chronology_reports.getMedical_events_report({
transaction
});
output.requested_by = await medical_chronology_reports.getRequested_by({
transaction
});
output.matter = await medical_chronology_reports.getMatter({
transaction
});
output.source_files = await medical_chronology_reports.getSource_files({
transaction
});
output.export_file = await medical_chronology_reports.getExport_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.users,
as: 'requested_by',
where: filter.requested_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.requested_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.requested_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.matters,
as: 'matter',
where: filter.matter ? {
[Op.or]: [
{ id: { [Op.in]: filter.matter.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.matter.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.files,
as: 'export_file',
where: filter.export_file ? {
[Op.or]: [
{ id: { [Op.in]: filter.export_file.split('|').map(term => Utils.uuid(term)) } },
{
file_name: {
[Op.or]: filter.export_file.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.files,
as: 'source_files',
required: false,
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.report_title) {
where = {
...where,
[Op.and]: Utils.ilike(
'medical_chronology_reports',
'report_title',
filter.report_title,
),
};
}
if (filter.overview) {
where = {
...where,
[Op.and]: Utils.ilike(
'medical_chronology_reports',
'overview',
filter.overview,
),
};
}
if (filter.generated_atRange) {
const [start, end] = filter.generated_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
generated_at: {
...where.generated_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
generated_at: {
...where.generated_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.source_files) {
const searchTerms = filter.source_files.split('|');
include = [
{
model: db.files,
as: 'source_files_filter',
required: searchTerms.length > 0,
where: searchTerms.length > 0 ? {
[Op.or]: [
{ id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
{
file_name: {
[Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
}
}
]
} : undefined
},
...include,
]
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
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.medical_chronology_reports.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'medical_chronology_reports',
'report_title',
query,
),
],
};
}
const records = await db.medical_chronology_reports.findAll({
attributes: [ 'id', 'report_title' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['report_title', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.report_title,
}));
}
};

View File

@ -0,0 +1,627 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Medical_eventsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const medical_events = await db.medical_events.create(
{
id: data.id || undefined,
event_at: data.event_at
||
null
,
provider_name: data.provider_name
||
null
,
facility_name: data.facility_name
||
null
,
diagnoses: data.diagnoses
||
null
,
icd10_codes: data.icd10_codes
||
null
,
procedures: data.procedures
||
null
,
medications: data.medications
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await medical_events.setReport( data.report || null, {
transaction,
});
await medical_events.setLinked_file( data.linked_file || null, {
transaction,
});
return medical_events;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const medical_eventsData = data.map((item, index) => ({
id: item.id || undefined,
event_at: item.event_at
||
null
,
provider_name: item.provider_name
||
null
,
facility_name: item.facility_name
||
null
,
diagnoses: item.diagnoses
||
null
,
icd10_codes: item.icd10_codes
||
null
,
procedures: item.procedures
||
null
,
medications: item.medications
||
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 medical_events = await db.medical_events.bulkCreate(medical_eventsData, { transaction });
// For each item created, replace relation files
return medical_events;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const medical_events = await db.medical_events.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.event_at !== undefined) updatePayload.event_at = data.event_at;
if (data.provider_name !== undefined) updatePayload.provider_name = data.provider_name;
if (data.facility_name !== undefined) updatePayload.facility_name = data.facility_name;
if (data.diagnoses !== undefined) updatePayload.diagnoses = data.diagnoses;
if (data.icd10_codes !== undefined) updatePayload.icd10_codes = data.icd10_codes;
if (data.procedures !== undefined) updatePayload.procedures = data.procedures;
if (data.medications !== undefined) updatePayload.medications = data.medications;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await medical_events.update(updatePayload, {transaction});
if (data.report !== undefined) {
await medical_events.setReport(
data.report,
{ transaction }
);
}
if (data.linked_file !== undefined) {
await medical_events.setLinked_file(
data.linked_file,
{ transaction }
);
}
return medical_events;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const medical_events = await db.medical_events.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of medical_events) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of medical_events) {
await record.destroy({transaction});
}
});
return medical_events;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const medical_events = await db.medical_events.findByPk(id, options);
await medical_events.update({
deletedBy: currentUser.id
}, {
transaction,
});
await medical_events.destroy({
transaction
});
return medical_events;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const medical_events = await db.medical_events.findOne(
{ where },
{ transaction },
);
if (!medical_events) {
return medical_events;
}
const output = medical_events.get({plain: true});
output.report = await medical_events.getReport({
transaction
});
output.linked_file = await medical_events.getLinked_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.medical_chronology_reports,
as: 'report',
where: filter.report ? {
[Op.or]: [
{ id: { [Op.in]: filter.report.split('|').map(term => Utils.uuid(term)) } },
{
report_title: {
[Op.or]: filter.report.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.files,
as: 'linked_file',
where: filter.linked_file ? {
[Op.or]: [
{ id: { [Op.in]: filter.linked_file.split('|').map(term => Utils.uuid(term)) } },
{
file_name: {
[Op.or]: filter.linked_file.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.provider_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'medical_events',
'provider_name',
filter.provider_name,
),
};
}
if (filter.facility_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'medical_events',
'facility_name',
filter.facility_name,
),
};
}
if (filter.diagnoses) {
where = {
...where,
[Op.and]: Utils.ilike(
'medical_events',
'diagnoses',
filter.diagnoses,
),
};
}
if (filter.icd10_codes) {
where = {
...where,
[Op.and]: Utils.ilike(
'medical_events',
'icd10_codes',
filter.icd10_codes,
),
};
}
if (filter.procedures) {
where = {
...where,
[Op.and]: Utils.ilike(
'medical_events',
'procedures',
filter.procedures,
),
};
}
if (filter.medications) {
where = {
...where,
[Op.and]: Utils.ilike(
'medical_events',
'medications',
filter.medications,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'medical_events',
'notes',
filter.notes,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
event_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
event_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.event_atRange) {
const [start, end] = filter.event_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
event_at: {
...where.event_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
event_at: {
...where.event_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.medical_events.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'medical_events',
'provider_name',
query,
),
],
};
}
const records = await db.medical_events.findAll({
attributes: [ 'id', 'provider_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['provider_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.provider_name,
}));
}
};

View File

@ -0,0 +1,459 @@
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 Mock_trial_rolesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const mock_trial_roles = await db.mock_trial_roles.create(
{
id: data.id || undefined,
role_name: data.role_name
||
null
,
actor_type: data.actor_type
||
null
,
display_name: data.display_name
||
null
,
instructions: data.instructions
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await mock_trial_roles.setMock_trial( data.mock_trial || null, {
transaction,
});
return mock_trial_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 mock_trial_rolesData = data.map((item, index) => ({
id: item.id || undefined,
role_name: item.role_name
||
null
,
actor_type: item.actor_type
||
null
,
display_name: item.display_name
||
null
,
instructions: item.instructions
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const mock_trial_roles = await db.mock_trial_roles.bulkCreate(mock_trial_rolesData, { transaction });
// For each item created, replace relation files
return mock_trial_roles;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const mock_trial_roles = await db.mock_trial_roles.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.role_name !== undefined) updatePayload.role_name = data.role_name;
if (data.actor_type !== undefined) updatePayload.actor_type = data.actor_type;
if (data.display_name !== undefined) updatePayload.display_name = data.display_name;
if (data.instructions !== undefined) updatePayload.instructions = data.instructions;
updatePayload.updatedById = currentUser.id;
await mock_trial_roles.update(updatePayload, {transaction});
if (data.mock_trial !== undefined) {
await mock_trial_roles.setMock_trial(
data.mock_trial,
{ transaction }
);
}
return mock_trial_roles;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const mock_trial_roles = await db.mock_trial_roles.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of mock_trial_roles) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of mock_trial_roles) {
await record.destroy({transaction});
}
});
return mock_trial_roles;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const mock_trial_roles = await db.mock_trial_roles.findByPk(id, options);
await mock_trial_roles.update({
deletedBy: currentUser.id
}, {
transaction,
});
await mock_trial_roles.destroy({
transaction
});
return mock_trial_roles;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const mock_trial_roles = await db.mock_trial_roles.findOne(
{ where },
{ transaction },
);
if (!mock_trial_roles) {
return mock_trial_roles;
}
const output = mock_trial_roles.get({plain: true});
output.mock_trial_turns_role = await mock_trial_roles.getMock_trial_turns_role({
transaction
});
output.mock_trial = await mock_trial_roles.getMock_trial({
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.mock_trials,
as: 'mock_trial',
where: filter.mock_trial ? {
[Op.or]: [
{ id: { [Op.in]: filter.mock_trial.split('|').map(term => Utils.uuid(term)) } },
{
session_title: {
[Op.or]: filter.mock_trial.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.display_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'mock_trial_roles',
'display_name',
filter.display_name,
),
};
}
if (filter.instructions) {
where = {
...where,
[Op.and]: Utils.ilike(
'mock_trial_roles',
'instructions',
filter.instructions,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.role_name) {
where = {
...where,
role_name: filter.role_name,
};
}
if (filter.actor_type) {
where = {
...where,
actor_type: filter.actor_type,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.mock_trial_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(
'mock_trial_roles',
'display_name',
query,
),
],
};
}
const records = await db.mock_trial_roles.findAll({
attributes: [ 'id', 'display_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['display_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.display_name,
}));
}
};

View File

@ -0,0 +1,522 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Mock_trial_turnsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const mock_trial_turns = await db.mock_trial_turns.create(
{
id: data.id || undefined,
turn_type: data.turn_type
||
null
,
content: data.content
||
null
,
spoken_at: data.spoken_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await mock_trial_turns.setMock_trial( data.mock_trial || null, {
transaction,
});
await mock_trial_turns.setRole( data.role || null, {
transaction,
});
await mock_trial_turns.setAudio_file( data.audio_file || null, {
transaction,
});
return mock_trial_turns;
}
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 mock_trial_turnsData = data.map((item, index) => ({
id: item.id || undefined,
turn_type: item.turn_type
||
null
,
content: item.content
||
null
,
spoken_at: item.spoken_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const mock_trial_turns = await db.mock_trial_turns.bulkCreate(mock_trial_turnsData, { transaction });
// For each item created, replace relation files
return mock_trial_turns;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const mock_trial_turns = await db.mock_trial_turns.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.turn_type !== undefined) updatePayload.turn_type = data.turn_type;
if (data.content !== undefined) updatePayload.content = data.content;
if (data.spoken_at !== undefined) updatePayload.spoken_at = data.spoken_at;
updatePayload.updatedById = currentUser.id;
await mock_trial_turns.update(updatePayload, {transaction});
if (data.mock_trial !== undefined) {
await mock_trial_turns.setMock_trial(
data.mock_trial,
{ transaction }
);
}
if (data.role !== undefined) {
await mock_trial_turns.setRole(
data.role,
{ transaction }
);
}
if (data.audio_file !== undefined) {
await mock_trial_turns.setAudio_file(
data.audio_file,
{ transaction }
);
}
return mock_trial_turns;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const mock_trial_turns = await db.mock_trial_turns.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of mock_trial_turns) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of mock_trial_turns) {
await record.destroy({transaction});
}
});
return mock_trial_turns;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const mock_trial_turns = await db.mock_trial_turns.findByPk(id, options);
await mock_trial_turns.update({
deletedBy: currentUser.id
}, {
transaction,
});
await mock_trial_turns.destroy({
transaction
});
return mock_trial_turns;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const mock_trial_turns = await db.mock_trial_turns.findOne(
{ where },
{ transaction },
);
if (!mock_trial_turns) {
return mock_trial_turns;
}
const output = mock_trial_turns.get({plain: true});
output.mock_trial = await mock_trial_turns.getMock_trial({
transaction
});
output.role = await mock_trial_turns.getRole({
transaction
});
output.audio_file = await mock_trial_turns.getAudio_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.mock_trials,
as: 'mock_trial',
where: filter.mock_trial ? {
[Op.or]: [
{ id: { [Op.in]: filter.mock_trial.split('|').map(term => Utils.uuid(term)) } },
{
session_title: {
[Op.or]: filter.mock_trial.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.mock_trial_roles,
as: 'role',
where: filter.role ? {
[Op.or]: [
{ id: { [Op.in]: filter.role.split('|').map(term => Utils.uuid(term)) } },
{
display_name: {
[Op.or]: filter.role.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.files,
as: 'audio_file',
where: filter.audio_file ? {
[Op.or]: [
{ id: { [Op.in]: filter.audio_file.split('|').map(term => Utils.uuid(term)) } },
{
file_name: {
[Op.or]: filter.audio_file.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.content) {
where = {
...where,
[Op.and]: Utils.ilike(
'mock_trial_turns',
'content',
filter.content,
),
};
}
if (filter.spoken_atRange) {
const [start, end] = filter.spoken_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
spoken_at: {
...where.spoken_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
spoken_at: {
...where.spoken_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.turn_type) {
where = {
...where,
turn_type: filter.turn_type,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.mock_trial_turns.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(
'mock_trial_turns',
'turn_type',
query,
),
],
};
}
const records = await db.mock_trial_turns.findAll({
attributes: [ 'id', 'turn_type' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['turn_type', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.turn_type,
}));
}
};

View File

@ -0,0 +1,649 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Mock_trialsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const mock_trials = await db.mock_trials.create(
{
id: data.id || undefined,
session_title: data.session_title
||
null
,
mode: data.mode
||
null
,
input_type: data.input_type
||
null
,
status: data.status
||
null
,
scheduled_at: data.scheduled_at
||
null
,
started_at: data.started_at
||
null
,
ended_at: data.ended_at
||
null
,
scenario_brief: data.scenario_brief
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await mock_trials.setOwner( data.owner || null, {
transaction,
});
await mock_trials.setMatter( data.matter || null, {
transaction,
});
return mock_trials;
}
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 mock_trialsData = data.map((item, index) => ({
id: item.id || undefined,
session_title: item.session_title
||
null
,
mode: item.mode
||
null
,
input_type: item.input_type
||
null
,
status: item.status
||
null
,
scheduled_at: item.scheduled_at
||
null
,
started_at: item.started_at
||
null
,
ended_at: item.ended_at
||
null
,
scenario_brief: item.scenario_brief
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const mock_trials = await db.mock_trials.bulkCreate(mock_trialsData, { transaction });
// For each item created, replace relation files
return mock_trials;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const mock_trials = await db.mock_trials.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.session_title !== undefined) updatePayload.session_title = data.session_title;
if (data.mode !== undefined) updatePayload.mode = data.mode;
if (data.input_type !== undefined) updatePayload.input_type = data.input_type;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.scheduled_at !== undefined) updatePayload.scheduled_at = data.scheduled_at;
if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
if (data.ended_at !== undefined) updatePayload.ended_at = data.ended_at;
if (data.scenario_brief !== undefined) updatePayload.scenario_brief = data.scenario_brief;
updatePayload.updatedById = currentUser.id;
await mock_trials.update(updatePayload, {transaction});
if (data.owner !== undefined) {
await mock_trials.setOwner(
data.owner,
{ transaction }
);
}
if (data.matter !== undefined) {
await mock_trials.setMatter(
data.matter,
{ transaction }
);
}
return mock_trials;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const mock_trials = await db.mock_trials.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of mock_trials) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of mock_trials) {
await record.destroy({transaction});
}
});
return mock_trials;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const mock_trials = await db.mock_trials.findByPk(id, options);
await mock_trials.update({
deletedBy: currentUser.id
}, {
transaction,
});
await mock_trials.destroy({
transaction
});
return mock_trials;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const mock_trials = await db.mock_trials.findOne(
{ where },
{ transaction },
);
if (!mock_trials) {
return mock_trials;
}
const output = mock_trials.get({plain: true});
output.mock_trial_roles_mock_trial = await mock_trials.getMock_trial_roles_mock_trial({
transaction
});
output.mock_trial_turns_mock_trial = await mock_trials.getMock_trial_turns_mock_trial({
transaction
});
output.owner = await mock_trials.getOwner({
transaction
});
output.matter = await mock_trials.getMatter({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.users,
as: 'owner',
where: filter.owner ? {
[Op.or]: [
{ id: { [Op.in]: filter.owner.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.owner.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.matters,
as: 'matter',
where: filter.matter ? {
[Op.or]: [
{ id: { [Op.in]: filter.matter.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.matter.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.session_title) {
where = {
...where,
[Op.and]: Utils.ilike(
'mock_trials',
'session_title',
filter.session_title,
),
};
}
if (filter.scenario_brief) {
where = {
...where,
[Op.and]: Utils.ilike(
'mock_trials',
'scenario_brief',
filter.scenario_brief,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
scheduled_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
ended_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.scheduled_atRange) {
const [start, end] = filter.scheduled_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
scheduled_at: {
...where.scheduled_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
scheduled_at: {
...where.scheduled_at,
[Op.lte]: end,
},
};
}
}
if (filter.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.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.mode) {
where = {
...where,
mode: filter.mode,
};
}
if (filter.input_type) {
where = {
...where,
input_type: filter.input_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.mock_trials.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(
'mock_trials',
'session_title',
query,
),
],
};
}
const records = await db.mock_trials.findAll({
attributes: [ 'id', 'session_title' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['session_title', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.session_title,
}));
}
};

View File

@ -0,0 +1,354 @@
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,537 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Research_queriesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const research_queries = await db.research_queries.create(
{
id: data.id || undefined,
query_text: data.query_text
||
null
,
jurisdiction: data.jurisdiction
||
null
,
source_scope: data.source_scope
||
null
,
searched_at: data.searched_at
||
null
,
filters_json: data.filters_json
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await research_queries.setRequested_by( data.requested_by || null, {
transaction,
});
await research_queries.setMatter( data.matter || null, {
transaction,
});
return research_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 research_queriesData = data.map((item, index) => ({
id: item.id || undefined,
query_text: item.query_text
||
null
,
jurisdiction: item.jurisdiction
||
null
,
source_scope: item.source_scope
||
null
,
searched_at: item.searched_at
||
null
,
filters_json: item.filters_json
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const research_queries = await db.research_queries.bulkCreate(research_queriesData, { transaction });
// For each item created, replace relation files
return research_queries;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const research_queries = await db.research_queries.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.query_text !== undefined) updatePayload.query_text = data.query_text;
if (data.jurisdiction !== undefined) updatePayload.jurisdiction = data.jurisdiction;
if (data.source_scope !== undefined) updatePayload.source_scope = data.source_scope;
if (data.searched_at !== undefined) updatePayload.searched_at = data.searched_at;
if (data.filters_json !== undefined) updatePayload.filters_json = data.filters_json;
updatePayload.updatedById = currentUser.id;
await research_queries.update(updatePayload, {transaction});
if (data.requested_by !== undefined) {
await research_queries.setRequested_by(
data.requested_by,
{ transaction }
);
}
if (data.matter !== undefined) {
await research_queries.setMatter(
data.matter,
{ transaction }
);
}
return research_queries;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const research_queries = await db.research_queries.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of research_queries) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of research_queries) {
await record.destroy({transaction});
}
});
return research_queries;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const research_queries = await db.research_queries.findByPk(id, options);
await research_queries.update({
deletedBy: currentUser.id
}, {
transaction,
});
await research_queries.destroy({
transaction
});
return research_queries;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const research_queries = await db.research_queries.findOne(
{ where },
{ transaction },
);
if (!research_queries) {
return research_queries;
}
const output = research_queries.get({plain: true});
output.research_results_research_query = await research_queries.getResearch_results_research_query({
transaction
});
output.requested_by = await research_queries.getRequested_by({
transaction
});
output.matter = await research_queries.getMatter({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.users,
as: 'requested_by',
where: filter.requested_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.requested_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.requested_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.matters,
as: 'matter',
where: filter.matter ? {
[Op.or]: [
{ id: { [Op.in]: filter.matter.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.matter.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(
'research_queries',
'query_text',
filter.query_text,
),
};
}
if (filter.jurisdiction) {
where = {
...where,
[Op.and]: Utils.ilike(
'research_queries',
'jurisdiction',
filter.jurisdiction,
),
};
}
if (filter.filters_json) {
where = {
...where,
[Op.and]: Utils.ilike(
'research_queries',
'filters_json',
filter.filters_json,
),
};
}
if (filter.searched_atRange) {
const [start, end] = filter.searched_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
searched_at: {
...where.searched_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
searched_at: {
...where.searched_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.source_scope) {
where = {
...where,
source_scope: filter.source_scope,
};
}
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.research_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(
'research_queries',
'jurisdiction',
query,
),
],
};
}
const records = await db.research_queries.findAll({
attributes: [ 'id', 'jurisdiction' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['jurisdiction', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.jurisdiction,
}));
}
};

View File

@ -0,0 +1,489 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Research_resultsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const research_results = await db.research_results.create(
{
id: data.id || undefined,
relevance_score: data.relevance_score
||
null
,
snippet: data.snippet
||
null
,
rule_statement: data.rule_statement
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await research_results.setResearch_query( data.research_query || null, {
transaction,
});
await research_results.setLegal_source( data.legal_source || null, {
transaction,
});
return research_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 research_resultsData = data.map((item, index) => ({
id: item.id || undefined,
relevance_score: item.relevance_score
||
null
,
snippet: item.snippet
||
null
,
rule_statement: item.rule_statement
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const research_results = await db.research_results.bulkCreate(research_resultsData, { transaction });
// For each item created, replace relation files
return research_results;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const research_results = await db.research_results.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.relevance_score !== undefined) updatePayload.relevance_score = data.relevance_score;
if (data.snippet !== undefined) updatePayload.snippet = data.snippet;
if (data.rule_statement !== undefined) updatePayload.rule_statement = data.rule_statement;
updatePayload.updatedById = currentUser.id;
await research_results.update(updatePayload, {transaction});
if (data.research_query !== undefined) {
await research_results.setResearch_query(
data.research_query,
{ transaction }
);
}
if (data.legal_source !== undefined) {
await research_results.setLegal_source(
data.legal_source,
{ transaction }
);
}
return research_results;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const research_results = await db.research_results.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of research_results) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of research_results) {
await record.destroy({transaction});
}
});
return research_results;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const research_results = await db.research_results.findByPk(id, options);
await research_results.update({
deletedBy: currentUser.id
}, {
transaction,
});
await research_results.destroy({
transaction
});
return research_results;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const research_results = await db.research_results.findOne(
{ where },
{ transaction },
);
if (!research_results) {
return research_results;
}
const output = research_results.get({plain: true});
output.research_query = await research_results.getResearch_query({
transaction
});
output.legal_source = await research_results.getLegal_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.research_queries,
as: 'research_query',
where: filter.research_query ? {
[Op.or]: [
{ id: { [Op.in]: filter.research_query.split('|').map(term => Utils.uuid(term)) } },
{
jurisdiction: {
[Op.or]: filter.research_query.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.legal_sources,
as: 'legal_source',
where: filter.legal_source ? {
[Op.or]: [
{ id: { [Op.in]: filter.legal_source.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.legal_source.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(
'research_results',
'snippet',
filter.snippet,
),
};
}
if (filter.rule_statement) {
where = {
...where,
[Op.and]: Utils.ilike(
'research_results',
'rule_statement',
filter.rule_statement,
),
};
}
if (filter.relevance_scoreRange) {
const [start, end] = filter.relevance_scoreRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
relevance_score: {
...where.relevance_score,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
relevance_score: {
...where.relevance_score,
[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.research_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(
'research_results',
'snippet',
query,
),
],
};
}
const records = await db.research_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,
}));
}
};

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

@ -0,0 +1,424 @@
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,651 @@
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 SubscriptionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const subscriptions = await db.subscriptions.create(
{
id: data.id || undefined,
status: data.status
||
null
,
billing_period: data.billing_period
||
null
,
price_amount: data.price_amount
||
null
,
currency: data.currency
||
null
,
current_period_start: data.current_period_start
||
null
,
current_period_end: data.current_period_end
||
null
,
canceled_at: data.canceled_at
||
null
,
payment_provider: data.payment_provider
||
null
,
provider_customer_ref: data.provider_customer_ref
||
null
,
provider_subscription_ref: data.provider_subscription_ref
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await subscriptions.setUser( data.user || null, {
transaction,
});
return subscriptions;
}
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 subscriptionsData = data.map((item, index) => ({
id: item.id || undefined,
status: item.status
||
null
,
billing_period: item.billing_period
||
null
,
price_amount: item.price_amount
||
null
,
currency: item.currency
||
null
,
current_period_start: item.current_period_start
||
null
,
current_period_end: item.current_period_end
||
null
,
canceled_at: item.canceled_at
||
null
,
payment_provider: item.payment_provider
||
null
,
provider_customer_ref: item.provider_customer_ref
||
null
,
provider_subscription_ref: item.provider_subscription_ref
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const subscriptions = await db.subscriptions.bulkCreate(subscriptionsData, { transaction });
// For each item created, replace relation files
return subscriptions;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const subscriptions = await db.subscriptions.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.status !== undefined) updatePayload.status = data.status;
if (data.billing_period !== undefined) updatePayload.billing_period = data.billing_period;
if (data.price_amount !== undefined) updatePayload.price_amount = data.price_amount;
if (data.currency !== undefined) updatePayload.currency = data.currency;
if (data.current_period_start !== undefined) updatePayload.current_period_start = data.current_period_start;
if (data.current_period_end !== undefined) updatePayload.current_period_end = data.current_period_end;
if (data.canceled_at !== undefined) updatePayload.canceled_at = data.canceled_at;
if (data.payment_provider !== undefined) updatePayload.payment_provider = data.payment_provider;
if (data.provider_customer_ref !== undefined) updatePayload.provider_customer_ref = data.provider_customer_ref;
if (data.provider_subscription_ref !== undefined) updatePayload.provider_subscription_ref = data.provider_subscription_ref;
updatePayload.updatedById = currentUser.id;
await subscriptions.update(updatePayload, {transaction});
if (data.user !== undefined) {
await subscriptions.setUser(
data.user,
{ transaction }
);
}
return subscriptions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const subscriptions = await db.subscriptions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of subscriptions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of subscriptions) {
await record.destroy({transaction});
}
});
return subscriptions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const subscriptions = await db.subscriptions.findByPk(id, options);
await subscriptions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await subscriptions.destroy({
transaction
});
return subscriptions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const subscriptions = await db.subscriptions.findOne(
{ where },
{ transaction },
);
if (!subscriptions) {
return subscriptions;
}
const output = subscriptions.get({plain: true});
output.user = await subscriptions.getUser({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.users,
as: 'user',
where: filter.user ? {
[Op.or]: [
{ id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.currency) {
where = {
...where,
[Op.and]: Utils.ilike(
'subscriptions',
'currency',
filter.currency,
),
};
}
if (filter.payment_provider) {
where = {
...where,
[Op.and]: Utils.ilike(
'subscriptions',
'payment_provider',
filter.payment_provider,
),
};
}
if (filter.provider_customer_ref) {
where = {
...where,
[Op.and]: Utils.ilike(
'subscriptions',
'provider_customer_ref',
filter.provider_customer_ref,
),
};
}
if (filter.provider_subscription_ref) {
where = {
...where,
[Op.and]: Utils.ilike(
'subscriptions',
'provider_subscription_ref',
filter.provider_subscription_ref,
),
};
}
if (filter.price_amountRange) {
const [start, end] = filter.price_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
price_amount: {
...where.price_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
price_amount: {
...where.price_amount,
[Op.lte]: end,
},
};
}
}
if (filter.current_period_startRange) {
const [start, end] = filter.current_period_startRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
current_period_start: {
...where.current_period_start,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
current_period_start: {
...where.current_period_start,
[Op.lte]: end,
},
};
}
}
if (filter.current_period_endRange) {
const [start, end] = filter.current_period_endRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
current_period_end: {
...where.current_period_end,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
current_period_end: {
...where.current_period_end,
[Op.lte]: end,
},
};
}
}
if (filter.canceled_atRange) {
const [start, end] = filter.canceled_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
canceled_at: {
...where.canceled_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
canceled_at: {
...where.canceled_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.billing_period) {
where = {
...where,
billing_period: filter.billing_period,
};
}
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.subscriptions.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(
'subscriptions',
'provider_subscription_ref',
query,
),
],
};
}
const records = await db.subscriptions.findAll({
attributes: [ 'id', 'provider_subscription_ref' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['provider_subscription_ref', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.provider_subscription_ref,
}));
}
};

View File

@ -0,0 +1,542 @@
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 Template_fieldsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const template_fields = await db.template_fields.create(
{
id: data.id || undefined,
field_key: data.field_key
||
null
,
label: data.label
||
null
,
value_type: data.value_type
||
null
,
is_required: data.is_required
||
false
,
default_value: data.default_value
||
null
,
sort_order: data.sort_order
||
null
,
help_text: data.help_text
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await template_fields.setTemplate( data.template || null, {
transaction,
});
return template_fields;
}
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 template_fieldsData = data.map((item, index) => ({
id: item.id || undefined,
field_key: item.field_key
||
null
,
label: item.label
||
null
,
value_type: item.value_type
||
null
,
is_required: item.is_required
||
false
,
default_value: item.default_value
||
null
,
sort_order: item.sort_order
||
null
,
help_text: item.help_text
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const template_fields = await db.template_fields.bulkCreate(template_fieldsData, { transaction });
// For each item created, replace relation files
return template_fields;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const template_fields = await db.template_fields.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.field_key !== undefined) updatePayload.field_key = data.field_key;
if (data.label !== undefined) updatePayload.label = data.label;
if (data.value_type !== undefined) updatePayload.value_type = data.value_type;
if (data.is_required !== undefined) updatePayload.is_required = data.is_required;
if (data.default_value !== undefined) updatePayload.default_value = data.default_value;
if (data.sort_order !== undefined) updatePayload.sort_order = data.sort_order;
if (data.help_text !== undefined) updatePayload.help_text = data.help_text;
updatePayload.updatedById = currentUser.id;
await template_fields.update(updatePayload, {transaction});
if (data.template !== undefined) {
await template_fields.setTemplate(
data.template,
{ transaction }
);
}
return template_fields;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const template_fields = await db.template_fields.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of template_fields) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of template_fields) {
await record.destroy({transaction});
}
});
return template_fields;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const template_fields = await db.template_fields.findByPk(id, options);
await template_fields.update({
deletedBy: currentUser.id
}, {
transaction,
});
await template_fields.destroy({
transaction
});
return template_fields;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const template_fields = await db.template_fields.findOne(
{ where },
{ transaction },
);
if (!template_fields) {
return template_fields;
}
const output = template_fields.get({plain: true});
output.template = await template_fields.getTemplate({
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.legal_templates,
as: 'template',
where: filter.template ? {
[Op.or]: [
{ id: { [Op.in]: filter.template.split('|').map(term => Utils.uuid(term)) } },
{
template_name: {
[Op.or]: filter.template.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.field_key) {
where = {
...where,
[Op.and]: Utils.ilike(
'template_fields',
'field_key',
filter.field_key,
),
};
}
if (filter.label) {
where = {
...where,
[Op.and]: Utils.ilike(
'template_fields',
'label',
filter.label,
),
};
}
if (filter.default_value) {
where = {
...where,
[Op.and]: Utils.ilike(
'template_fields',
'default_value',
filter.default_value,
),
};
}
if (filter.help_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'template_fields',
'help_text',
filter.help_text,
),
};
}
if (filter.sort_orderRange) {
const [start, end] = filter.sort_orderRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sort_order: {
...where.sort_order,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sort_order: {
...where.sort_order,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.value_type) {
where = {
...where,
value_type: filter.value_type,
};
}
if (filter.is_required) {
where = {
...where,
is_required: filter.is_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.template_fields.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(
'template_fields',
'label',
query,
),
],
};
}
const records = await db.template_fields.findAll({
attributes: [ 'id', 'label' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['label', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.label,
}));
}
};

View File

@ -0,0 +1,751 @@
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 Transcription_jobsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const transcription_jobs = await db.transcription_jobs.create(
{
id: data.id || undefined,
status: data.status
||
null
,
source_language: data.source_language
||
null
,
target_language: data.target_language
||
null
,
speaker_diarization: data.speaker_diarization
||
false
,
confidence_avg: data.confidence_avg
||
null
,
transcript_text: data.transcript_text
||
null
,
summary_text: data.summary_text
||
null
,
started_at: data.started_at
||
null
,
finished_at: data.finished_at
||
null
,
error_message: data.error_message
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await transcription_jobs.setRequested_by( data.requested_by || null, {
transaction,
});
await transcription_jobs.setMatter( data.matter || null, {
transaction,
});
await transcription_jobs.setMedia_file( data.media_file || null, {
transaction,
});
await transcription_jobs.setExport_file( data.export_file || null, {
transaction,
});
return transcription_jobs;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const transcription_jobsData = data.map((item, index) => ({
id: item.id || undefined,
status: item.status
||
null
,
source_language: item.source_language
||
null
,
target_language: item.target_language
||
null
,
speaker_diarization: item.speaker_diarization
||
false
,
confidence_avg: item.confidence_avg
||
null
,
transcript_text: item.transcript_text
||
null
,
summary_text: item.summary_text
||
null
,
started_at: item.started_at
||
null
,
finished_at: item.finished_at
||
null
,
error_message: item.error_message
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const transcription_jobs = await db.transcription_jobs.bulkCreate(transcription_jobsData, { transaction });
// For each item created, replace relation files
return transcription_jobs;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const transcription_jobs = await db.transcription_jobs.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.status !== undefined) updatePayload.status = data.status;
if (data.source_language !== undefined) updatePayload.source_language = data.source_language;
if (data.target_language !== undefined) updatePayload.target_language = data.target_language;
if (data.speaker_diarization !== undefined) updatePayload.speaker_diarization = data.speaker_diarization;
if (data.confidence_avg !== undefined) updatePayload.confidence_avg = data.confidence_avg;
if (data.transcript_text !== undefined) updatePayload.transcript_text = data.transcript_text;
if (data.summary_text !== undefined) updatePayload.summary_text = data.summary_text;
if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
if (data.finished_at !== undefined) updatePayload.finished_at = data.finished_at;
if (data.error_message !== undefined) updatePayload.error_message = data.error_message;
updatePayload.updatedById = currentUser.id;
await transcription_jobs.update(updatePayload, {transaction});
if (data.requested_by !== undefined) {
await transcription_jobs.setRequested_by(
data.requested_by,
{ transaction }
);
}
if (data.matter !== undefined) {
await transcription_jobs.setMatter(
data.matter,
{ transaction }
);
}
if (data.media_file !== undefined) {
await transcription_jobs.setMedia_file(
data.media_file,
{ transaction }
);
}
if (data.export_file !== undefined) {
await transcription_jobs.setExport_file(
data.export_file,
{ transaction }
);
}
return transcription_jobs;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const transcription_jobs = await db.transcription_jobs.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of transcription_jobs) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of transcription_jobs) {
await record.destroy({transaction});
}
});
return transcription_jobs;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const transcription_jobs = await db.transcription_jobs.findByPk(id, options);
await transcription_jobs.update({
deletedBy: currentUser.id
}, {
transaction,
});
await transcription_jobs.destroy({
transaction
});
return transcription_jobs;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const transcription_jobs = await db.transcription_jobs.findOne(
{ where },
{ transaction },
);
if (!transcription_jobs) {
return transcription_jobs;
}
const output = transcription_jobs.get({plain: true});
output.requested_by = await transcription_jobs.getRequested_by({
transaction
});
output.matter = await transcription_jobs.getMatter({
transaction
});
output.media_file = await transcription_jobs.getMedia_file({
transaction
});
output.export_file = await transcription_jobs.getExport_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.users,
as: 'requested_by',
where: filter.requested_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.requested_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.requested_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.matters,
as: 'matter',
where: filter.matter ? {
[Op.or]: [
{ id: { [Op.in]: filter.matter.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.matter.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.files,
as: 'media_file',
where: filter.media_file ? {
[Op.or]: [
{ id: { [Op.in]: filter.media_file.split('|').map(term => Utils.uuid(term)) } },
{
file_name: {
[Op.or]: filter.media_file.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.files,
as: 'export_file',
where: filter.export_file ? {
[Op.or]: [
{ id: { [Op.in]: filter.export_file.split('|').map(term => Utils.uuid(term)) } },
{
file_name: {
[Op.or]: filter.export_file.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.source_language) {
where = {
...where,
[Op.and]: Utils.ilike(
'transcription_jobs',
'source_language',
filter.source_language,
),
};
}
if (filter.target_language) {
where = {
...where,
[Op.and]: Utils.ilike(
'transcription_jobs',
'target_language',
filter.target_language,
),
};
}
if (filter.transcript_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'transcription_jobs',
'transcript_text',
filter.transcript_text,
),
};
}
if (filter.summary_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'transcription_jobs',
'summary_text',
filter.summary_text,
),
};
}
if (filter.error_message) {
where = {
...where,
[Op.and]: Utils.ilike(
'transcription_jobs',
'error_message',
filter.error_message,
),
};
}
if (filter.confidence_avgRange) {
const [start, end] = filter.confidence_avgRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
confidence_avg: {
...where.confidence_avg,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
confidence_avg: {
...where.confidence_avg,
[Op.lte]: end,
},
};
}
}
if (filter.started_atRange) {
const [start, end] = filter.started_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
started_at: {
...where.started_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
started_at: {
...where.started_at,
[Op.lte]: end,
},
};
}
}
if (filter.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.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.speaker_diarization) {
where = {
...where,
speaker_diarization: filter.speaker_diarization,
};
}
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.transcription_jobs.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'transcription_jobs',
'status',
query,
),
],
};
}
const records = await db.transcription_jobs.findAll({
attributes: [ 'id', 'status' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['status', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.status,
}));
}
};

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

File diff suppressed because it is too large Load Diff

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_pro_se_litigant_ai',
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,224 @@
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_jobs = sequelize.define(
'ai_jobs',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
job_type: {
type: DataTypes.ENUM,
values: [
"drafting",
"file_analysis",
"legal_research",
"citator",
"transcription",
"translation",
"medical_chronology",
"causation",
"ocr",
"export"
],
},
status: {
type: DataTypes.ENUM,
values: [
"queued",
"running",
"completed",
"failed",
"canceled"
],
},
input_summary: {
type: DataTypes.TEXT,
},
output_summary: {
type: DataTypes.TEXT,
},
cost_usd: {
type: DataTypes.DECIMAL,
},
queued_at: {
type: DataTypes.DATE,
},
started_at: {
type: DataTypes.DATE,
},
completed_at: {
type: DataTypes.DATE,
},
error_message: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
ai_jobs.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.ai_jobs.belongsTo(db.users, {
as: 'requested_by',
foreignKey: {
name: 'requested_byId',
},
constraints: false,
});
db.ai_jobs.belongsTo(db.matters, {
as: 'matter',
foreignKey: {
name: 'matterId',
},
constraints: false,
});
db.ai_jobs.belongsTo(db.files, {
as: 'file',
foreignKey: {
name: 'fileId',
},
constraints: false,
});
db.ai_jobs.belongsTo(db.users, {
as: 'createdBy',
});
db.ai_jobs.belongsTo(db.users, {
as: 'updatedBy',
});
};
return ai_jobs;
};

View File

@ -0,0 +1,148 @@
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 assistant_messages = sequelize.define(
'assistant_messages',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
sender: {
type: DataTypes.ENUM,
values: [
"user",
"assistant",
"system"
],
},
content: {
type: DataTypes.TEXT,
},
model_name: {
type: DataTypes.TEXT,
},
prompt_tokens: {
type: DataTypes.INTEGER,
},
completion_tokens: {
type: DataTypes.INTEGER,
},
sent_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
assistant_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.assistant_messages.belongsTo(db.assistant_threads, {
as: 'thread',
foreignKey: {
name: 'threadId',
},
constraints: false,
});
db.assistant_messages.belongsTo(db.users, {
as: 'createdBy',
});
db.assistant_messages.belongsTo(db.users, {
as: 'updatedBy',
});
};
return assistant_messages;
};

View File

@ -0,0 +1,150 @@
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 assistant_threads = sequelize.define(
'assistant_threads',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
title: {
type: DataTypes.TEXT,
},
thread_scope: {
type: DataTypes.ENUM,
values: [
"general",
"matter"
],
},
is_pinned: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
last_activity_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
assistant_threads.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.assistant_threads.hasMany(db.assistant_messages, {
as: 'assistant_messages_thread',
foreignKey: {
name: 'threadId',
},
constraints: false,
});
//end loop
db.assistant_threads.belongsTo(db.users, {
as: 'owner',
foreignKey: {
name: 'ownerId',
},
constraints: false,
});
db.assistant_threads.belongsTo(db.matters, {
as: 'matter',
foreignKey: {
name: 'matterId',
},
constraints: false,
});
db.assistant_threads.belongsTo(db.users, {
as: 'createdBy',
});
db.assistant_threads.belongsTo(db.users, {
as: 'updatedBy',
});
};
return assistant_threads;
};

View File

@ -0,0 +1,180 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const audit_events = sequelize.define(
'audit_events',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
event_name: {
type: DataTypes.TEXT,
},
event_category: {
type: DataTypes.ENUM,
values: [
"auth",
"billing",
"matter",
"file",
"assistant",
"research",
"template",
"document",
"mock_trial",
"medical",
"admin"
],
},
event_details: {
type: DataTypes.TEXT,
},
occurred_at: {
type: DataTypes.DATE,
},
ip_address: {
type: DataTypes.TEXT,
},
user_agent: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
audit_events.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.audit_events.belongsTo(db.users, {
as: 'actor',
foreignKey: {
name: 'actorId',
},
constraints: false,
});
db.audit_events.belongsTo(db.matters, {
as: 'matter',
foreignKey: {
name: 'matterId',
},
constraints: false,
});
db.audit_events.belongsTo(db.users, {
as: 'createdBy',
});
db.audit_events.belongsTo(db.users, {
as: 'updatedBy',
});
};
return audit_events;
};

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 causation_analyses = sequelize.define(
'causation_analyses',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
analysis_title: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"draft",
"generated",
"exported"
],
},
theory_of_causation: {
type: DataTypes.TEXT,
},
supporting_facts: {
type: DataTypes.TEXT,
},
weaknesses_and_gaps: {
type: DataTypes.TEXT,
},
generated_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
causation_analyses.associate = (db) => {
db.causation_analyses.belongsToMany(db.files, {
as: 'source_files',
foreignKey: {
name: 'causation_analyses_source_filesId',
},
constraints: false,
through: 'causation_analysesSource_filesFiles',
});
db.causation_analyses.belongsToMany(db.files, {
as: 'source_files_filter',
foreignKey: {
name: 'causation_analyses_source_filesId',
},
constraints: false,
through: 'causation_analysesSource_filesFiles',
});
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.causation_analyses.belongsTo(db.users, {
as: 'requested_by',
foreignKey: {
name: 'requested_byId',
},
constraints: false,
});
db.causation_analyses.belongsTo(db.matters, {
as: 'matter',
foreignKey: {
name: 'matterId',
},
constraints: false,
});
db.causation_analyses.belongsTo(db.files, {
as: 'export_file',
foreignKey: {
name: 'export_fileId',
},
constraints: false,
});
db.causation_analyses.belongsTo(db.users, {
as: 'createdBy',
});
db.causation_analyses.belongsTo(db.users, {
as: 'updatedBy',
});
};
return causation_analyses;
};

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 citator_checks = sequelize.define(
'citator_checks',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
standing: {
type: DataTypes.ENUM,
values: [
"good_law",
"caution",
"overruled",
"distinguished",
"unknown"
],
},
analysis: {
type: DataTypes.TEXT,
},
conflicts_summary: {
type: DataTypes.TEXT,
},
checked_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
citator_checks.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.citator_checks.belongsTo(db.users, {
as: 'requested_by',
foreignKey: {
name: 'requested_byId',
},
constraints: false,
});
db.citator_checks.belongsTo(db.matters, {
as: 'matter',
foreignKey: {
name: 'matterId',
},
constraints: false,
});
db.citator_checks.belongsTo(db.legal_sources, {
as: 'legal_source',
foreignKey: {
name: 'legal_sourceId',
},
constraints: false,
});
db.citator_checks.belongsTo(db.users, {
as: 'createdBy',
});
db.citator_checks.belongsTo(db.users, {
as: 'updatedBy',
});
};
return citator_checks;
};

View File

@ -0,0 +1,134 @@
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 document_versions = sequelize.define(
'document_versions',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
version_number: {
type: DataTypes.INTEGER,
},
change_source: {
type: DataTypes.ENUM,
values: [
"user_edit",
"ai_regeneration",
"import"
],
},
content_snapshot: {
type: DataTypes.TEXT,
},
saved_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
document_versions.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.document_versions.belongsTo(db.generated_documents, {
as: 'document',
foreignKey: {
name: 'documentId',
},
constraints: false,
});
db.document_versions.belongsTo(db.users, {
as: 'createdBy',
});
db.document_versions.belongsTo(db.users, {
as: 'updatedBy',
});
};
return document_versions;
};

View File

@ -0,0 +1,136 @@
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 feature_flags = sequelize.define(
'feature_flags',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
key: {
type: DataTypes.TEXT,
},
name: {
type: DataTypes.TEXT,
},
description: {
type: DataTypes.TEXT,
},
default_plan_access: {
type: DataTypes.ENUM,
values: [
"free",
"premium",
"disabled"
],
},
is_enabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
feature_flags.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.feature_flags.belongsTo(db.users, {
as: 'createdBy',
});
db.feature_flags.belongsTo(db.users, {
as: 'updatedBy',
});
};
return feature_flags;
};

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,189 @@
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 file_extractions = sequelize.define(
'file_extractions',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
extraction_type: {
type: DataTypes.ENUM,
values: [
"text",
"ocr_text",
"metadata",
"clauses",
"summary",
"issues",
"citations"
],
},
status: {
type: DataTypes.ENUM,
values: [
"queued",
"running",
"completed",
"failed"
],
},
language: {
type: DataTypes.TEXT,
},
page_count: {
type: DataTypes.INTEGER,
},
result_text: {
type: DataTypes.TEXT,
},
started_at: {
type: DataTypes.DATE,
},
finished_at: {
type: DataTypes.DATE,
},
error_message: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
file_extractions.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.file_extractions.belongsTo(db.files, {
as: 'file',
foreignKey: {
name: 'fileId',
},
constraints: false,
});
db.file_extractions.belongsTo(db.users, {
as: 'createdBy',
});
db.file_extractions.belongsTo(db.users, {
as: 'updatedBy',
});
};
return file_extractions;
};

View File

@ -0,0 +1,277 @@
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 files = sequelize.define(
'files',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
file_name: {
type: DataTypes.TEXT,
},
content_type: {
type: DataTypes.TEXT,
},
file_extension: {
type: DataTypes.TEXT,
},
size_bytes: {
type: DataTypes.INTEGER,
},
storage_provider: {
type: DataTypes.TEXT,
},
storage_key: {
type: DataTypes.TEXT,
},
checksum_sha256: {
type: DataTypes.TEXT,
},
is_ocr_required: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
processing_status: {
type: DataTypes.ENUM,
values: [
"queued",
"processing",
"completed",
"failed"
],
},
uploaded_at: {
type: DataTypes.DATE,
},
tags: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
files.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.files.hasMany(db.file_extractions, {
as: 'file_extractions_file',
foreignKey: {
name: 'fileId',
},
constraints: false,
});
db.files.hasMany(db.ai_jobs, {
as: 'ai_jobs_file',
foreignKey: {
name: 'fileId',
},
constraints: false,
});
db.files.hasMany(db.legal_templates, {
as: 'legal_templates_source_file',
foreignKey: {
name: 'source_fileId',
},
constraints: false,
});
db.files.hasMany(db.generated_documents, {
as: 'generated_documents_export_file',
foreignKey: {
name: 'export_fileId',
},
constraints: false,
});
db.files.hasMany(db.mock_trial_turns, {
as: 'mock_trial_turns_audio_file',
foreignKey: {
name: 'audio_fileId',
},
constraints: false,
});
db.files.hasMany(db.transcription_jobs, {
as: 'transcription_jobs_media_file',
foreignKey: {
name: 'media_fileId',
},
constraints: false,
});
db.files.hasMany(db.transcription_jobs, {
as: 'transcription_jobs_export_file',
foreignKey: {
name: 'export_fileId',
},
constraints: false,
});
db.files.hasMany(db.medical_chronology_reports, {
as: 'medical_chronology_reports_export_file',
foreignKey: {
name: 'export_fileId',
},
constraints: false,
});
db.files.hasMany(db.medical_events, {
as: 'medical_events_linked_file',
foreignKey: {
name: 'linked_fileId',
},
constraints: false,
});
db.files.hasMany(db.causation_analyses, {
as: 'causation_analyses_export_file',
foreignKey: {
name: 'export_fileId',
},
constraints: false,
});
//end loop
db.files.belongsTo(db.users, {
as: 'owner',
foreignKey: {
name: 'ownerId',
},
constraints: false,
});
db.files.belongsTo(db.matters, {
as: 'matter',
foreignKey: {
name: 'matterId',
},
constraints: false,
});
db.files.belongsTo(db.users, {
as: 'createdBy',
});
db.files.belongsTo(db.users, {
as: 'updatedBy',
});
};
return files;
};

View File

@ -0,0 +1,188 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const generated_documents = sequelize.define(
'generated_documents',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
document_title: {
type: DataTypes.TEXT,
},
document_type: {
type: DataTypes.ENUM,
values: [
"draft",
"final",
"exported"
],
},
format: {
type: DataTypes.ENUM,
values: [
"canvas",
"docx",
"pdf",
"txt"
],
},
content: {
type: DataTypes.TEXT,
},
last_edited_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
generated_documents.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.generated_documents.hasMany(db.document_versions, {
as: 'document_versions_document',
foreignKey: {
name: 'documentId',
},
constraints: false,
});
//end loop
db.generated_documents.belongsTo(db.users, {
as: 'owner',
foreignKey: {
name: 'ownerId',
},
constraints: false,
});
db.generated_documents.belongsTo(db.matters, {
as: 'matter',
foreignKey: {
name: 'matterId',
},
constraints: false,
});
db.generated_documents.belongsTo(db.legal_templates, {
as: 'template',
foreignKey: {
name: 'templateId',
},
constraints: false,
});
db.generated_documents.belongsTo(db.files, {
as: 'export_file',
foreignKey: {
name: 'export_fileId',
},
constraints: false,
});
db.generated_documents.belongsTo(db.users, {
as: 'createdBy',
});
db.generated_documents.belongsTo(db.users, {
as: 'updatedBy',
});
};
return generated_documents;
};

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,187 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const legal_sources = sequelize.define(
'legal_sources',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
source_type: {
type: DataTypes.ENUM,
values: [
"case",
"statute",
"rule",
"regulation"
],
},
jurisdiction: {
type: DataTypes.TEXT,
},
title: {
type: DataTypes.TEXT,
},
citation: {
type: DataTypes.TEXT,
},
decision_date: {
type: DataTypes.DATE,
},
court: {
type: DataTypes.TEXT,
},
full_text: {
type: DataTypes.TEXT,
},
summary: {
type: DataTypes.TEXT,
},
source_url: {
type: DataTypes.TEXT,
},
last_updated_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
legal_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.legal_sources.hasMany(db.research_results, {
as: 'research_results_legal_source',
foreignKey: {
name: 'legal_sourceId',
},
constraints: false,
});
db.legal_sources.hasMany(db.citator_checks, {
as: 'citator_checks_legal_source',
foreignKey: {
name: 'legal_sourceId',
},
constraints: false,
});
//end loop
db.legal_sources.belongsTo(db.users, {
as: 'createdBy',
});
db.legal_sources.belongsTo(db.users, {
as: 'updatedBy',
});
};
return legal_sources;
};

View File

@ -0,0 +1,190 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const legal_templates = sequelize.define(
'legal_templates',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
template_name: {
type: DataTypes.TEXT,
},
template_category: {
type: DataTypes.ENUM,
values: [
"motion",
"pleading",
"brief",
"letter",
"contract",
"memo",
"form",
"other"
],
},
jurisdiction: {
type: DataTypes.TEXT,
},
description: {
type: DataTypes.TEXT,
},
template_body: {
type: DataTypes.TEXT,
},
is_public: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
legal_templates.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.legal_templates.hasMany(db.template_fields, {
as: 'template_fields_template',
foreignKey: {
name: 'templateId',
},
constraints: false,
});
db.legal_templates.hasMany(db.generated_documents, {
as: 'generated_documents_template',
foreignKey: {
name: 'templateId',
},
constraints: false,
});
//end loop
db.legal_templates.belongsTo(db.users, {
as: 'owner',
foreignKey: {
name: 'ownerId',
},
constraints: false,
});
db.legal_templates.belongsTo(db.files, {
as: 'source_file',
foreignKey: {
name: 'source_fileId',
},
constraints: false,
});
db.legal_templates.belongsTo(db.users, {
as: 'createdBy',
});
db.legal_templates.belongsTo(db.users, {
as: 'updatedBy',
});
};
return legal_templates;
};

View File

@ -0,0 +1,179 @@
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 matter_parties = sequelize.define(
'matter_parties',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
party_role: {
type: DataTypes.ENUM,
values: [
"plaintiff",
"defendant",
"petitioner",
"respondent",
"witness",
"judge",
"attorney",
"opposing_counsel",
"expert",
"provider",
"other"
],
},
display_name: {
type: DataTypes.TEXT,
},
organization_name: {
type: DataTypes.TEXT,
},
email: {
type: DataTypes.TEXT,
},
phone: {
type: DataTypes.TEXT,
},
address: {
type: DataTypes.TEXT,
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
matter_parties.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.matter_parties.belongsTo(db.matters, {
as: 'matter',
foreignKey: {
name: 'matterId',
},
constraints: false,
});
db.matter_parties.belongsTo(db.users, {
as: 'createdBy',
});
db.matter_parties.belongsTo(db.users, {
as: 'updatedBy',
});
};
return matter_parties;
};

View File

@ -0,0 +1,307 @@
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 matters = sequelize.define(
'matters',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
title: {
type: DataTypes.TEXT,
},
matter_type: {
type: DataTypes.ENUM,
values: [
"civil",
"criminal",
"family",
"employment",
"housing",
"small_claims",
"personal_injury",
"medical_malpractice",
"contract",
"administrative",
"other"
],
},
status: {
type: DataTypes.ENUM,
values: [
"intake",
"active",
"stayed",
"closed",
"archived"
],
},
jurisdiction: {
type: DataTypes.TEXT,
},
court_name: {
type: DataTypes.TEXT,
},
case_number: {
type: DataTypes.TEXT,
},
filed_at: {
type: DataTypes.DATE,
},
next_hearing_at: {
type: DataTypes.DATE,
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
matters.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.matters.hasMany(db.matter_parties, {
as: 'matter_parties_matter',
foreignKey: {
name: 'matterId',
},
constraints: false,
});
db.matters.hasMany(db.files, {
as: 'files_matter',
foreignKey: {
name: 'matterId',
},
constraints: false,
});
db.matters.hasMany(db.assistant_threads, {
as: 'assistant_threads_matter',
foreignKey: {
name: 'matterId',
},
constraints: false,
});
db.matters.hasMany(db.ai_jobs, {
as: 'ai_jobs_matter',
foreignKey: {
name: 'matterId',
},
constraints: false,
});
db.matters.hasMany(db.generated_documents, {
as: 'generated_documents_matter',
foreignKey: {
name: 'matterId',
},
constraints: false,
});
db.matters.hasMany(db.research_queries, {
as: 'research_queries_matter',
foreignKey: {
name: 'matterId',
},
constraints: false,
});
db.matters.hasMany(db.citator_checks, {
as: 'citator_checks_matter',
foreignKey: {
name: 'matterId',
},
constraints: false,
});
db.matters.hasMany(db.mock_trials, {
as: 'mock_trials_matter',
foreignKey: {
name: 'matterId',
},
constraints: false,
});
db.matters.hasMany(db.transcription_jobs, {
as: 'transcription_jobs_matter',
foreignKey: {
name: 'matterId',
},
constraints: false,
});
db.matters.hasMany(db.medical_chronology_reports, {
as: 'medical_chronology_reports_matter',
foreignKey: {
name: 'matterId',
},
constraints: false,
});
db.matters.hasMany(db.causation_analyses, {
as: 'causation_analyses_matter',
foreignKey: {
name: 'matterId',
},
constraints: false,
});
db.matters.hasMany(db.audit_events, {
as: 'audit_events_matter',
foreignKey: {
name: 'matterId',
},
constraints: false,
});
//end loop
db.matters.belongsTo(db.users, {
as: 'owner',
foreignKey: {
name: 'ownerId',
},
constraints: false,
});
db.matters.belongsTo(db.users, {
as: 'createdBy',
});
db.matters.belongsTo(db.users, {
as: 'updatedBy',
});
};
return matters;
};

View File

@ -0,0 +1,176 @@
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 medical_chronology_reports = sequelize.define(
'medical_chronology_reports',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
report_title: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"draft",
"generated",
"exported"
],
},
overview: {
type: DataTypes.TEXT,
},
generated_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
medical_chronology_reports.associate = (db) => {
db.medical_chronology_reports.belongsToMany(db.files, {
as: 'source_files',
foreignKey: {
name: 'medical_chronology_reports_source_filesId',
},
constraints: false,
through: 'medical_chronology_reportsSource_filesFiles',
});
db.medical_chronology_reports.belongsToMany(db.files, {
as: 'source_files_filter',
foreignKey: {
name: 'medical_chronology_reports_source_filesId',
},
constraints: false,
through: 'medical_chronology_reportsSource_filesFiles',
});
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.medical_chronology_reports.hasMany(db.medical_events, {
as: 'medical_events_report',
foreignKey: {
name: 'reportId',
},
constraints: false,
});
//end loop
db.medical_chronology_reports.belongsTo(db.users, {
as: 'requested_by',
foreignKey: {
name: 'requested_byId',
},
constraints: false,
});
db.medical_chronology_reports.belongsTo(db.matters, {
as: 'matter',
foreignKey: {
name: 'matterId',
},
constraints: false,
});
db.medical_chronology_reports.belongsTo(db.files, {
as: 'export_file',
foreignKey: {
name: 'export_fileId',
},
constraints: false,
});
db.medical_chronology_reports.belongsTo(db.users, {
as: 'createdBy',
});
db.medical_chronology_reports.belongsTo(db.users, {
as: 'updatedBy',
});
};
return medical_chronology_reports;
};

View File

@ -0,0 +1,158 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const medical_events = sequelize.define(
'medical_events',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
event_at: {
type: DataTypes.DATE,
},
provider_name: {
type: DataTypes.TEXT,
},
facility_name: {
type: DataTypes.TEXT,
},
diagnoses: {
type: DataTypes.TEXT,
},
icd10_codes: {
type: DataTypes.TEXT,
},
procedures: {
type: DataTypes.TEXT,
},
medications: {
type: DataTypes.TEXT,
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
medical_events.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.medical_events.belongsTo(db.medical_chronology_reports, {
as: 'report',
foreignKey: {
name: 'reportId',
},
constraints: false,
});
db.medical_events.belongsTo(db.files, {
as: 'linked_file',
foreignKey: {
name: 'linked_fileId',
},
constraints: false,
});
db.medical_events.belongsTo(db.users, {
as: 'createdBy',
});
db.medical_events.belongsTo(db.users, {
as: 'updatedBy',
});
};
return medical_events;
};

View File

@ -0,0 +1,169 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const mock_trial_roles = sequelize.define(
'mock_trial_roles',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
role_name: {
type: DataTypes.ENUM,
values: [
"judge",
"plaintiff",
"defendant",
"petitioner",
"respondent",
"opposing_counsel",
"witness",
"clerk",
"bailiff"
],
},
actor_type: {
type: DataTypes.ENUM,
values: [
"user",
"ai"
],
},
display_name: {
type: DataTypes.TEXT,
},
instructions: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
mock_trial_roles.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.mock_trial_roles.hasMany(db.mock_trial_turns, {
as: 'mock_trial_turns_role',
foreignKey: {
name: 'roleId',
},
constraints: false,
});
//end loop
db.mock_trial_roles.belongsTo(db.mock_trials, {
as: 'mock_trial',
foreignKey: {
name: 'mock_trialId',
},
constraints: false,
});
db.mock_trial_roles.belongsTo(db.users, {
as: 'createdBy',
});
db.mock_trial_roles.belongsTo(db.users, {
as: 'updatedBy',
});
};
return mock_trial_roles;
};

View File

@ -0,0 +1,161 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const mock_trial_turns = sequelize.define(
'mock_trial_turns',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
turn_type: {
type: DataTypes.ENUM,
values: [
"opening",
"direct_exam",
"cross_exam",
"argument",
"ruling",
"objection",
"sidebar",
"closing",
"general"
],
},
content: {
type: DataTypes.TEXT,
},
spoken_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
mock_trial_turns.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.mock_trial_turns.belongsTo(db.mock_trials, {
as: 'mock_trial',
foreignKey: {
name: 'mock_trialId',
},
constraints: false,
});
db.mock_trial_turns.belongsTo(db.mock_trial_roles, {
as: 'role',
foreignKey: {
name: 'roleId',
},
constraints: false,
});
db.mock_trial_turns.belongsTo(db.files, {
as: 'audio_file',
foreignKey: {
name: 'audio_fileId',
},
constraints: false,
});
db.mock_trial_turns.belongsTo(db.users, {
as: 'createdBy',
});
db.mock_trial_turns.belongsTo(db.users, {
as: 'updatedBy',
});
};
return mock_trial_turns;
};

View File

@ -0,0 +1,210 @@
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 mock_trials = sequelize.define(
'mock_trials',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
session_title: {
type: DataTypes.TEXT,
},
mode: {
type: DataTypes.ENUM,
values: [
"scripted",
"realtime"
],
},
input_type: {
type: DataTypes.ENUM,
values: [
"text",
"voice",
"mixed"
],
},
status: {
type: DataTypes.ENUM,
values: [
"scheduled",
"in_progress",
"completed",
"archived"
],
},
scheduled_at: {
type: DataTypes.DATE,
},
started_at: {
type: DataTypes.DATE,
},
ended_at: {
type: DataTypes.DATE,
},
scenario_brief: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
mock_trials.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.mock_trials.hasMany(db.mock_trial_roles, {
as: 'mock_trial_roles_mock_trial',
foreignKey: {
name: 'mock_trialId',
},
constraints: false,
});
db.mock_trials.hasMany(db.mock_trial_turns, {
as: 'mock_trial_turns_mock_trial',
foreignKey: {
name: 'mock_trialId',
},
constraints: false,
});
//end loop
db.mock_trials.belongsTo(db.users, {
as: 'owner',
foreignKey: {
name: 'ownerId',
},
constraints: false,
});
db.mock_trials.belongsTo(db.matters, {
as: 'matter',
foreignKey: {
name: 'matterId',
},
constraints: false,
});
db.mock_trials.belongsTo(db.users, {
as: 'createdBy',
});
db.mock_trials.belongsTo(db.users, {
as: 'updatedBy',
});
};
return mock_trials;
};

View File

@ -0,0 +1,93 @@
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,157 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const research_queries = sequelize.define(
'research_queries',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
query_text: {
type: DataTypes.TEXT,
},
jurisdiction: {
type: DataTypes.TEXT,
},
source_scope: {
type: DataTypes.ENUM,
values: [
"federal",
"state",
"both"
],
},
searched_at: {
type: DataTypes.DATE,
},
filters_json: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
research_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.research_queries.hasMany(db.research_results, {
as: 'research_results_research_query',
foreignKey: {
name: 'research_queryId',
},
constraints: false,
});
//end loop
db.research_queries.belongsTo(db.users, {
as: 'requested_by',
foreignKey: {
name: 'requested_byId',
},
constraints: false,
});
db.research_queries.belongsTo(db.matters, {
as: 'matter',
foreignKey: {
name: 'matterId',
},
constraints: false,
});
db.research_queries.belongsTo(db.users, {
as: 'createdBy',
});
db.research_queries.belongsTo(db.users, {
as: 'updatedBy',
});
};
return research_queries;
};

View File

@ -0,0 +1,123 @@
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 research_results = sequelize.define(
'research_results',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
relevance_score: {
type: DataTypes.DECIMAL,
},
snippet: {
type: DataTypes.TEXT,
},
rule_statement: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
research_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.research_results.belongsTo(db.research_queries, {
as: 'research_query',
foreignKey: {
name: 'research_queryId',
},
constraints: false,
});
db.research_results.belongsTo(db.legal_sources, {
as: 'legal_source',
foreignKey: {
name: 'legal_sourceId',
},
constraints: false,
});
db.research_results.belongsTo(db.users, {
as: 'createdBy',
});
db.research_results.belongsTo(db.users, {
as: 'updatedBy',
});
};
return research_results;
};

View File

@ -0,0 +1,126 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const 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,188 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const subscriptions = sequelize.define(
'subscriptions',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
status: {
type: DataTypes.ENUM,
values: [
"trialing",
"active",
"past_due",
"canceled",
"expired"
],
},
billing_period: {
type: DataTypes.ENUM,
values: [
"yearly"
],
},
price_amount: {
type: DataTypes.DECIMAL,
},
currency: {
type: DataTypes.TEXT,
},
current_period_start: {
type: DataTypes.DATE,
},
current_period_end: {
type: DataTypes.DATE,
},
canceled_at: {
type: DataTypes.DATE,
},
payment_provider: {
type: DataTypes.TEXT,
},
provider_customer_ref: {
type: DataTypes.TEXT,
},
provider_subscription_ref: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
subscriptions.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.subscriptions.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.subscriptions.belongsTo(db.users, {
as: 'createdBy',
});
db.subscriptions.belongsTo(db.users, {
as: 'updatedBy',
});
};
return subscriptions;
};

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 template_fields = sequelize.define(
'template_fields',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
field_key: {
type: DataTypes.TEXT,
},
label: {
type: DataTypes.TEXT,
},
value_type: {
type: DataTypes.ENUM,
values: [
"text",
"number",
"date",
"boolean",
"party",
"citation",
"custom"
],
},
is_required: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
default_value: {
type: DataTypes.TEXT,
},
sort_order: {
type: DataTypes.INTEGER,
},
help_text: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
template_fields.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.template_fields.belongsTo(db.legal_templates, {
as: 'template',
foreignKey: {
name: 'templateId',
},
constraints: false,
});
db.template_fields.belongsTo(db.users, {
as: 'createdBy',
});
db.template_fields.belongsTo(db.users, {
as: 'updatedBy',
});
};
return template_fields;
};

View File

@ -0,0 +1,206 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const transcription_jobs = sequelize.define(
'transcription_jobs',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
status: {
type: DataTypes.ENUM,
values: [
"queued",
"running",
"completed",
"failed"
],
},
source_language: {
type: DataTypes.TEXT,
},
target_language: {
type: DataTypes.TEXT,
},
speaker_diarization: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
confidence_avg: {
type: DataTypes.DECIMAL,
},
transcript_text: {
type: DataTypes.TEXT,
},
summary_text: {
type: DataTypes.TEXT,
},
started_at: {
type: DataTypes.DATE,
},
finished_at: {
type: DataTypes.DATE,
},
error_message: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
transcription_jobs.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.transcription_jobs.belongsTo(db.users, {
as: 'requested_by',
foreignKey: {
name: 'requested_byId',
},
constraints: false,
});
db.transcription_jobs.belongsTo(db.matters, {
as: 'matter',
foreignKey: {
name: 'matterId',
},
constraints: false,
});
db.transcription_jobs.belongsTo(db.files, {
as: 'media_file',
foreignKey: {
name: 'media_fileId',
},
constraints: false,
});
db.transcription_jobs.belongsTo(db.files, {
as: 'export_file',
foreignKey: {
name: 'export_fileId',
},
constraints: false,
});
db.transcription_jobs.belongsTo(db.users, {
as: 'createdBy',
});
db.transcription_jobs.belongsTo(db.users, {
as: 'updatedBy',
});
};
return transcription_jobs;
};

View File

@ -0,0 +1,363 @@
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.subscriptions, {
as: 'subscriptions_user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.users.hasMany(db.matters, {
as: 'matters_owner',
foreignKey: {
name: 'ownerId',
},
constraints: false,
});
db.users.hasMany(db.files, {
as: 'files_owner',
foreignKey: {
name: 'ownerId',
},
constraints: false,
});
db.users.hasMany(db.assistant_threads, {
as: 'assistant_threads_owner',
foreignKey: {
name: 'ownerId',
},
constraints: false,
});
db.users.hasMany(db.ai_jobs, {
as: 'ai_jobs_requested_by',
foreignKey: {
name: 'requested_byId',
},
constraints: false,
});
db.users.hasMany(db.legal_templates, {
as: 'legal_templates_owner',
foreignKey: {
name: 'ownerId',
},
constraints: false,
});
db.users.hasMany(db.generated_documents, {
as: 'generated_documents_owner',
foreignKey: {
name: 'ownerId',
},
constraints: false,
});
db.users.hasMany(db.research_queries, {
as: 'research_queries_requested_by',
foreignKey: {
name: 'requested_byId',
},
constraints: false,
});
db.users.hasMany(db.citator_checks, {
as: 'citator_checks_requested_by',
foreignKey: {
name: 'requested_byId',
},
constraints: false,
});
db.users.hasMany(db.mock_trials, {
as: 'mock_trials_owner',
foreignKey: {
name: 'ownerId',
},
constraints: false,
});
db.users.hasMany(db.transcription_jobs, {
as: 'transcription_jobs_requested_by',
foreignKey: {
name: 'requested_byId',
},
constraints: false,
});
db.users.hasMany(db.medical_chronology_reports, {
as: 'medical_chronology_reports_requested_by',
foreignKey: {
name: 'requested_byId',
},
constraints: false,
});
db.users.hasMany(db.causation_analyses, {
as: 'causation_analyses_requested_by',
foreignKey: {
name: 'requested_byId',
},
constraints: false,
});
db.users.hasMany(db.audit_events, {
as: 'audit_events_actor',
foreignKey: {
name: 'actorId',
},
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;
}

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

View File

@ -0,0 +1,555 @@
const { v4: uuid } = require("uuid");
module.exports = {
/**
* @param{import("sequelize").QueryInterface} queryInterface
* @return {Promise<void>}
*/
async up(queryInterface) {
const createdAt = new Date();
const updatedAt = new Date();
/** @type {Map<string, string>} */
const idMap = new Map();
/**
* @param {string} key
* @return {string}
*/
function getId(key) {
if (idMap.has(key)) {
return idMap.get(key);
}
const id = uuid();
idMap.set(key, id);
return id;
}
await queryInterface.bulkInsert("roles", [
{ id: getId("Administrator"), name: "Administrator", createdAt, updatedAt },
{ id: getId("User"), name: "User", createdAt, updatedAt },
{ id: getId("Public"), name: "Public", createdAt, updatedAt },
]);
/**
* @param {string} name
*/
function createPermissions(name) {
return [
{ id: getId(`CREATE_${name.toUpperCase()}`), createdAt, updatedAt, name: `CREATE_${name.toUpperCase()}` },
{ id: getId(`READ_${name.toUpperCase()}`), createdAt, updatedAt, name: `READ_${name.toUpperCase()}` },
{ id: getId(`UPDATE_${name.toUpperCase()}`), createdAt, updatedAt, name: `UPDATE_${name.toUpperCase()}` },
{ id: getId(`DELETE_${name.toUpperCase()}`), createdAt, updatedAt, name: `DELETE_${name.toUpperCase()}` }
];
}
const entities = [
"users","roles","permissions","subscriptions","feature_flags","matters","matter_parties","files","file_extractions","assistant_threads","assistant_messages","ai_jobs","legal_templates","template_fields","generated_documents","document_versions","research_queries","legal_sources","research_results","citator_checks","mock_trials","mock_trial_roles","mock_trial_turns","transcription_jobs","medical_chronology_reports","medical_events","causation_analyses","audit_events",,
];
await queryInterface.bulkInsert("permissions", entities.flatMap(createPermissions));
await queryInterface.bulkInsert("permissions", [{ id: getId(`READ_API_DOCS`), createdAt, updatedAt, name: `READ_API_DOCS` }]);
await queryInterface.bulkInsert("permissions", [{ id: getId(`CREATE_SEARCH`), createdAt, updatedAt, name: `CREATE_SEARCH`}]);
await queryInterface.sequelize.query(`create table "rolesPermissionsPermissions"
(
"createdAt" timestamp with time zone not null,
"updatedAt" timestamp with time zone not null,
"roles_permissionsId" uuid not null,
"permissionId" uuid not null,
primary key ("roles_permissionsId", "permissionId")
);`);
await queryInterface.bulkInsert("rolesPermissionsPermissions", [
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('CREATE_USERS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('READ_USERS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('UPDATE_USERS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('DELETE_USERS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('CREATE_SUBSCRIPTIONS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('READ_SUBSCRIPTIONS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('UPDATE_SUBSCRIPTIONS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('DELETE_SUBSCRIPTIONS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('CREATE_FEATURE_FLAGS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('READ_FEATURE_FLAGS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('UPDATE_FEATURE_FLAGS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('DELETE_FEATURE_FLAGS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('CREATE_MATTERS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('READ_MATTERS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('UPDATE_MATTERS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('DELETE_MATTERS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('CREATE_MATTER_PARTIES') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('READ_MATTER_PARTIES') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('UPDATE_MATTER_PARTIES') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('DELETE_MATTER_PARTIES') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('CREATE_FILES') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('READ_FILES') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('UPDATE_FILES') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('DELETE_FILES') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('CREATE_FILE_EXTRACTIONS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('READ_FILE_EXTRACTIONS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('UPDATE_FILE_EXTRACTIONS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('DELETE_FILE_EXTRACTIONS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('CREATE_ASSISTANT_THREADS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('READ_ASSISTANT_THREADS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('UPDATE_ASSISTANT_THREADS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('DELETE_ASSISTANT_THREADS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('CREATE_ASSISTANT_MESSAGES') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('READ_ASSISTANT_MESSAGES') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('UPDATE_ASSISTANT_MESSAGES') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('DELETE_ASSISTANT_MESSAGES') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('CREATE_AI_JOBS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('READ_AI_JOBS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('UPDATE_AI_JOBS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('DELETE_AI_JOBS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('CREATE_LEGAL_TEMPLATES') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('READ_LEGAL_TEMPLATES') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('UPDATE_LEGAL_TEMPLATES') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('DELETE_LEGAL_TEMPLATES') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('CREATE_TEMPLATE_FIELDS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('READ_TEMPLATE_FIELDS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('UPDATE_TEMPLATE_FIELDS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('DELETE_TEMPLATE_FIELDS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('CREATE_GENERATED_DOCUMENTS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('READ_GENERATED_DOCUMENTS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('UPDATE_GENERATED_DOCUMENTS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('DELETE_GENERATED_DOCUMENTS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('CREATE_DOCUMENT_VERSIONS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('READ_DOCUMENT_VERSIONS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('UPDATE_DOCUMENT_VERSIONS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('DELETE_DOCUMENT_VERSIONS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('CREATE_RESEARCH_QUERIES') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('READ_RESEARCH_QUERIES') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('UPDATE_RESEARCH_QUERIES') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('DELETE_RESEARCH_QUERIES') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('CREATE_LEGAL_SOURCES') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('READ_LEGAL_SOURCES') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('UPDATE_LEGAL_SOURCES') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('DELETE_LEGAL_SOURCES') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('CREATE_RESEARCH_RESULTS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('READ_RESEARCH_RESULTS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('UPDATE_RESEARCH_RESULTS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('DELETE_RESEARCH_RESULTS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('CREATE_CITATOR_CHECKS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('READ_CITATOR_CHECKS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('UPDATE_CITATOR_CHECKS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('DELETE_CITATOR_CHECKS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('CREATE_MOCK_TRIALS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('READ_MOCK_TRIALS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('UPDATE_MOCK_TRIALS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('DELETE_MOCK_TRIALS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('CREATE_MOCK_TRIAL_ROLES') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('READ_MOCK_TRIAL_ROLES') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('UPDATE_MOCK_TRIAL_ROLES') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('DELETE_MOCK_TRIAL_ROLES') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('CREATE_MOCK_TRIAL_TURNS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('READ_MOCK_TRIAL_TURNS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('UPDATE_MOCK_TRIAL_TURNS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('DELETE_MOCK_TRIAL_TURNS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('CREATE_TRANSCRIPTION_JOBS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('READ_TRANSCRIPTION_JOBS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('UPDATE_TRANSCRIPTION_JOBS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('DELETE_TRANSCRIPTION_JOBS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('CREATE_MEDICAL_CHRONOLOGY_REPORTS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('READ_MEDICAL_CHRONOLOGY_REPORTS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('UPDATE_MEDICAL_CHRONOLOGY_REPORTS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('DELETE_MEDICAL_CHRONOLOGY_REPORTS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('CREATE_MEDICAL_EVENTS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('READ_MEDICAL_EVENTS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('UPDATE_MEDICAL_EVENTS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('DELETE_MEDICAL_EVENTS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('CREATE_CAUSATION_ANALYSES') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('READ_CAUSATION_ANALYSES') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('UPDATE_CAUSATION_ANALYSES') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('DELETE_CAUSATION_ANALYSES') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('CREATE_AUDIT_EVENTS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('READ_AUDIT_EVENTS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('UPDATE_AUDIT_EVENTS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('DELETE_AUDIT_EVENTS') },
{ createdAt, updatedAt, roles_permissionsId: getId("User"), permissionId: getId('CREATE_SEARCH') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('CREATE_USERS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('READ_USERS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('UPDATE_USERS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('DELETE_USERS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('CREATE_ROLES') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('READ_ROLES') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('UPDATE_ROLES') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('DELETE_ROLES') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('CREATE_PERMISSIONS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('READ_PERMISSIONS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('UPDATE_PERMISSIONS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('DELETE_PERMISSIONS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('CREATE_SUBSCRIPTIONS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('READ_SUBSCRIPTIONS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('UPDATE_SUBSCRIPTIONS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('DELETE_SUBSCRIPTIONS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('CREATE_FEATURE_FLAGS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('READ_FEATURE_FLAGS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('UPDATE_FEATURE_FLAGS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('DELETE_FEATURE_FLAGS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('CREATE_MATTERS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('READ_MATTERS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('UPDATE_MATTERS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('DELETE_MATTERS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('CREATE_MATTER_PARTIES') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('READ_MATTER_PARTIES') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('UPDATE_MATTER_PARTIES') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('DELETE_MATTER_PARTIES') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('CREATE_FILES') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('READ_FILES') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('UPDATE_FILES') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('DELETE_FILES') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('CREATE_FILE_EXTRACTIONS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('READ_FILE_EXTRACTIONS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('UPDATE_FILE_EXTRACTIONS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('DELETE_FILE_EXTRACTIONS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('CREATE_ASSISTANT_THREADS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('READ_ASSISTANT_THREADS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('UPDATE_ASSISTANT_THREADS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('DELETE_ASSISTANT_THREADS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('CREATE_ASSISTANT_MESSAGES') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('READ_ASSISTANT_MESSAGES') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('UPDATE_ASSISTANT_MESSAGES') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('DELETE_ASSISTANT_MESSAGES') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('CREATE_AI_JOBS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('READ_AI_JOBS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('UPDATE_AI_JOBS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('DELETE_AI_JOBS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('CREATE_LEGAL_TEMPLATES') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('READ_LEGAL_TEMPLATES') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('UPDATE_LEGAL_TEMPLATES') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('DELETE_LEGAL_TEMPLATES') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('CREATE_TEMPLATE_FIELDS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('READ_TEMPLATE_FIELDS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('UPDATE_TEMPLATE_FIELDS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('DELETE_TEMPLATE_FIELDS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('CREATE_GENERATED_DOCUMENTS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('READ_GENERATED_DOCUMENTS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('UPDATE_GENERATED_DOCUMENTS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('DELETE_GENERATED_DOCUMENTS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('CREATE_DOCUMENT_VERSIONS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('READ_DOCUMENT_VERSIONS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('UPDATE_DOCUMENT_VERSIONS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('DELETE_DOCUMENT_VERSIONS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('CREATE_RESEARCH_QUERIES') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('READ_RESEARCH_QUERIES') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('UPDATE_RESEARCH_QUERIES') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('DELETE_RESEARCH_QUERIES') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('CREATE_LEGAL_SOURCES') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('READ_LEGAL_SOURCES') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('UPDATE_LEGAL_SOURCES') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('DELETE_LEGAL_SOURCES') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('CREATE_RESEARCH_RESULTS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('READ_RESEARCH_RESULTS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('UPDATE_RESEARCH_RESULTS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('DELETE_RESEARCH_RESULTS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('CREATE_CITATOR_CHECKS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('READ_CITATOR_CHECKS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('UPDATE_CITATOR_CHECKS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('DELETE_CITATOR_CHECKS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('CREATE_MOCK_TRIALS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('READ_MOCK_TRIALS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('UPDATE_MOCK_TRIALS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('DELETE_MOCK_TRIALS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('CREATE_MOCK_TRIAL_ROLES') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('READ_MOCK_TRIAL_ROLES') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('UPDATE_MOCK_TRIAL_ROLES') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('DELETE_MOCK_TRIAL_ROLES') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('CREATE_MOCK_TRIAL_TURNS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('READ_MOCK_TRIAL_TURNS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('UPDATE_MOCK_TRIAL_TURNS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('DELETE_MOCK_TRIAL_TURNS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('CREATE_TRANSCRIPTION_JOBS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('READ_TRANSCRIPTION_JOBS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('UPDATE_TRANSCRIPTION_JOBS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('DELETE_TRANSCRIPTION_JOBS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('CREATE_MEDICAL_CHRONOLOGY_REPORTS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('READ_MEDICAL_CHRONOLOGY_REPORTS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('UPDATE_MEDICAL_CHRONOLOGY_REPORTS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('DELETE_MEDICAL_CHRONOLOGY_REPORTS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('CREATE_MEDICAL_EVENTS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('READ_MEDICAL_EVENTS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('UPDATE_MEDICAL_EVENTS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('DELETE_MEDICAL_EVENTS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('CREATE_CAUSATION_ANALYSES') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('READ_CAUSATION_ANALYSES') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('UPDATE_CAUSATION_ANALYSES') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('DELETE_CAUSATION_ANALYSES') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('CREATE_AUDIT_EVENTS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('READ_AUDIT_EVENTS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('UPDATE_AUDIT_EVENTS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('DELETE_AUDIT_EVENTS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('READ_API_DOCS') },
{ createdAt, updatedAt, roles_permissionsId: getId("Administrator"), permissionId: getId('CREATE_SEARCH') },
]);
await queryInterface.sequelize.query(`UPDATE "users" SET "app_roleId"='${getId("SuperAdmin")}' WHERE "email"='super_admin@flatlogic.com'`);
await queryInterface.sequelize.query(`UPDATE "users" SET "app_roleId"='${getId("Administrator")}' WHERE "email"='admin@flatlogic.com'`);
await queryInterface.sequelize.query(`UPDATE "users" SET "app_roleId"='${getId("User")}' WHERE "email"='client@hello.com'`);
await queryInterface.sequelize.query(`UPDATE "users" SET "app_roleId"='${getId("User")}' WHERE "email"='john@doe.com'`);
}
};

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

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

@ -0,0 +1,238 @@
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 subscriptionsRoutes = require('./routes/subscriptions');
const feature_flagsRoutes = require('./routes/feature_flags');
const mattersRoutes = require('./routes/matters');
const matter_partiesRoutes = require('./routes/matter_parties');
const filesRoutes = require('./routes/files');
const file_extractionsRoutes = require('./routes/file_extractions');
const assistant_threadsRoutes = require('./routes/assistant_threads');
const assistant_messagesRoutes = require('./routes/assistant_messages');
const ai_jobsRoutes = require('./routes/ai_jobs');
const legal_templatesRoutes = require('./routes/legal_templates');
const template_fieldsRoutes = require('./routes/template_fields');
const generated_documentsRoutes = require('./routes/generated_documents');
const document_versionsRoutes = require('./routes/document_versions');
const research_queriesRoutes = require('./routes/research_queries');
const legal_sourcesRoutes = require('./routes/legal_sources');
const research_resultsRoutes = require('./routes/research_results');
const citator_checksRoutes = require('./routes/citator_checks');
const mock_trialsRoutes = require('./routes/mock_trials');
const mock_trial_rolesRoutes = require('./routes/mock_trial_roles');
const mock_trial_turnsRoutes = require('./routes/mock_trial_turns');
const transcription_jobsRoutes = require('./routes/transcription_jobs');
const medical_chronology_reportsRoutes = require('./routes/medical_chronology_reports');
const medical_eventsRoutes = require('./routes/medical_events');
const causation_analysesRoutes = require('./routes/causation_analyses');
const audit_eventsRoutes = require('./routes/audit_events');
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: "Pro Se Litigant AI",
description: "Pro Se Litigant AI 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/subscriptions', passport.authenticate('jwt', {session: false}), subscriptionsRoutes);
app.use('/api/feature_flags', passport.authenticate('jwt', {session: false}), feature_flagsRoutes);
app.use('/api/matters', passport.authenticate('jwt', {session: false}), mattersRoutes);
app.use('/api/matter_parties', passport.authenticate('jwt', {session: false}), matter_partiesRoutes);
app.use('/api/files', passport.authenticate('jwt', {session: false}), filesRoutes);
app.use('/api/file_extractions', passport.authenticate('jwt', {session: false}), file_extractionsRoutes);
app.use('/api/assistant_threads', passport.authenticate('jwt', {session: false}), assistant_threadsRoutes);
app.use('/api/assistant_messages', passport.authenticate('jwt', {session: false}), assistant_messagesRoutes);
app.use('/api/ai_jobs', passport.authenticate('jwt', {session: false}), ai_jobsRoutes);
app.use('/api/legal_templates', passport.authenticate('jwt', {session: false}), legal_templatesRoutes);
app.use('/api/template_fields', passport.authenticate('jwt', {session: false}), template_fieldsRoutes);
app.use('/api/generated_documents', passport.authenticate('jwt', {session: false}), generated_documentsRoutes);
app.use('/api/document_versions', passport.authenticate('jwt', {session: false}), document_versionsRoutes);
app.use('/api/research_queries', passport.authenticate('jwt', {session: false}), research_queriesRoutes);
app.use('/api/legal_sources', passport.authenticate('jwt', {session: false}), legal_sourcesRoutes);
app.use('/api/research_results', passport.authenticate('jwt', {session: false}), research_resultsRoutes);
app.use('/api/citator_checks', passport.authenticate('jwt', {session: false}), citator_checksRoutes);
app.use('/api/mock_trials', passport.authenticate('jwt', {session: false}), mock_trialsRoutes);
app.use('/api/mock_trial_roles', passport.authenticate('jwt', {session: false}), mock_trial_rolesRoutes);
app.use('/api/mock_trial_turns', passport.authenticate('jwt', {session: false}), mock_trial_turnsRoutes);
app.use('/api/transcription_jobs', passport.authenticate('jwt', {session: false}), transcription_jobsRoutes);
app.use('/api/medical_chronology_reports', passport.authenticate('jwt', {session: false}), medical_chronology_reportsRoutes);
app.use('/api/medical_events', passport.authenticate('jwt', {session: false}), medical_eventsRoutes);
app.use('/api/causation_analyses', passport.authenticate('jwt', {session: false}), causation_analysesRoutes);
app.use('/api/audit_events', passport.authenticate('jwt', {session: false}), audit_eventsRoutes);
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,440 @@
const express = require('express');
const Ai_jobsService = require('../services/ai_jobs');
const Ai_jobsDBApi = require('../db/api/ai_jobs');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('ai_jobs'));
/**
* @swagger
* components:
* schemas:
* Ai_jobs:
* type: object
* properties:
* input_summary:
* type: string
* default: input_summary
* output_summary:
* type: string
* default: output_summary
* error_message:
* type: string
* default: error_message
* cost_usd:
* type: integer
* format: int64
*
*
*/
/**
* @swagger
* tags:
* name: Ai_jobs
* description: The Ai_jobs managing API
*/
/**
* @swagger
* /api/ai_jobs:
* post:
* security:
* - bearerAuth: []
* tags: [Ai_jobs]
* 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_jobs"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Ai_jobs"
* 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_jobsService.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_jobs]
* 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_jobs"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Ai_jobs"
* 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_jobsService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/ai_jobs/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Ai_jobs]
* 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_jobs"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Ai_jobs"
* 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_jobsService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/ai_jobs/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Ai_jobs]
* 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_jobs"
* 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_jobsService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/ai_jobs/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Ai_jobs]
* 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_jobs"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await Ai_jobsService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/ai_jobs:
* get:
* security:
* - bearerAuth: []
* tags: [Ai_jobs]
* summary: Get all ai_jobs
* description: Get all ai_jobs
* responses:
* 200:
* description: Ai_jobs list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Ai_jobs"
* 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_jobsDBApi.findAll(
req.query, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','input_summary','output_summary','error_message',
'cost_usd',
'queued_at','started_at','completed_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_jobs/count:
* get:
* security:
* - bearerAuth: []
* tags: [Ai_jobs]
* summary: Count all ai_jobs
* description: Count all ai_jobs
* responses:
* 200:
* description: Ai_jobs count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Ai_jobs"
* 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_jobsDBApi.findAll(
req.query,
null,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/ai_jobs/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Ai_jobs]
* summary: Find all ai_jobs that match search criteria
* description: Find all ai_jobs that match search criteria
* responses:
* 200:
* description: Ai_jobs list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Ai_jobs"
* 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_jobsDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/ai_jobs/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Ai_jobs]
* 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_jobs"
* 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_jobsDBApi.findBy(
{ id: req.params.id },
);
res.status(200).send(payload);
}));
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

View File

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

View File

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

View File

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

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

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

View File

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

View File

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

View File

View File

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

View File

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

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