Initial version

This commit is contained in:
Flatlogic Bot 2026-03-06 04:22:38 +00:00
commit 1efd00be71
734 changed files with 230001 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>App Preview</h2>
<p>All-in-one investing platform with live data, research, AI insights, and paper trading.</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 @@
# App Preview
## 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_39023
DB_USER=app_39023
DB_PASS=9449f547-9488-46d6-b8ec-5e79c32b885a
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 @@
#App Preview - 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_app_preview;`
- Then give that new user privileges to the new database then quit the `psql`.
- `postgres=> GRANT ALL PRIVILEGES ON DATABASE db_app_preview 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": "apppreview",
"description": "App Preview - template backend",
"scripts": {
"start": "npm run db:migrate && npm run db:seed && npm run watch",
"lint": "eslint . --ext .js",
"db:migrate": "sequelize-cli db:migrate",
"db:seed": "sequelize-cli db:seed:all",
"db:drop": "sequelize-cli db:drop",
"db:create": "sequelize-cli db:create",
"watch": "node watcher.js"
},
"dependencies": {
"@google-cloud/storage": "^5.18.2",
"axios": "^1.6.7",
"bcrypt": "5.1.1",
"chokidar": "^4.0.3",
"cors": "2.8.5",
"csv-parser": "^3.0.0",
"express": "4.18.2",
"formidable": "1.2.2",
"helmet": "4.1.1",
"json2csv": "^5.0.7",
"jsonwebtoken": "8.5.1",
"lodash": "4.17.21",
"moment": "2.30.1",
"multer": "^1.4.4",
"mysql2": "2.2.5",
"nodemailer": "6.9.9",
"passport": "^0.7.0",
"passport-google-oauth2": "^0.2.0",
"passport-jwt": "^4.0.1",
"passport-microsoft": "^0.1.0",
"pg": "8.4.1",
"pg-hstore": "2.3.4",
"sequelize": "6.35.2",
"sequelize-json-schema": "^2.1.1",
"sqlite": "4.0.15",
"swagger-jsdoc": "^6.2.8",
"swagger-ui-express": "^5.0.0",
"tedious": "^18.2.4"
},
"engines": {
"node": ">=18"
},
"private": true,
"devDependencies": {
"cross-env": "7.0.3",
"eslint": "^8.23.1",
"eslint-plugin-import": "^2.29.1",
"mocha": "8.1.3",
"node-mocks-http": "1.9.0",
"nodemon": "2.0.5",
"sequelize-cli": "6.6.2"
}
}

View File

@ -0,0 +1,484 @@
"use strict";
const fs = require("fs");
const path = require("path");
const http = require("http");
const https = require("https");
const { URL } = require("url");
let CONFIG_CACHE = null;
class LocalAIApi {
static createResponse(params, options) {
return createResponse(params, options);
}
static request(pathValue, payload, options) {
return request(pathValue, payload, options);
}
static fetchStatus(aiRequestId, options) {
return fetchStatus(aiRequestId, options);
}
static awaitResponse(aiRequestId, options) {
return awaitResponse(aiRequestId, options);
}
static extractText(response) {
return extractText(response);
}
static decodeJsonFromResponse(response) {
return decodeJsonFromResponse(response);
}
}
async function createResponse(params, options = {}) {
const payload = { ...(params || {}) };
if (!Array.isArray(payload.input) || payload.input.length === 0) {
return {
success: false,
error: "input_missing",
message: 'Parameter "input" is required and must be a non-empty array.',
};
}
const cfg = config();
if (!payload.model) {
payload.model = cfg.defaultModel;
}
const initial = await request(options.path, payload, options);
if (!initial.success) {
return initial;
}
const data = initial.data;
if (data && typeof data === "object" && data.ai_request_id) {
const pollTimeout = Number(options.poll_timeout ?? 300);
const pollInterval = Number(options.poll_interval ?? 5);
return await awaitResponse(data.ai_request_id, {
interval: pollInterval,
timeout: pollTimeout,
headers: options.headers,
timeout_per_call: options.timeout,
verify_tls: options.verify_tls,
});
}
return initial;
}
async function request(pathValue, payload = {}, options = {}) {
const cfg = config();
const resolvedPath = pathValue || options.path || cfg.responsesPath;
if (!resolvedPath) {
return {
success: false,
error: "project_id_missing",
message: "PROJECT_ID is not defined; cannot resolve AI proxy endpoint.",
};
}
if (!cfg.projectUuid) {
return {
success: false,
error: "project_uuid_missing",
message: "PROJECT_UUID is not defined; aborting AI request.",
};
}
const bodyPayload = { ...(payload || {}) };
if (!bodyPayload.project_uuid) {
bodyPayload.project_uuid = cfg.projectUuid;
}
const url = buildUrl(resolvedPath, cfg.baseUrl);
const timeout = resolveTimeout(options.timeout, cfg.timeout);
const verifyTls = resolveVerifyTls(options.verify_tls, cfg.verifyTls);
const headers = {
Accept: "application/json",
"Content-Type": "application/json",
[cfg.projectHeader]: cfg.projectUuid,
};
if (Array.isArray(options.headers)) {
for (const header of options.headers) {
if (typeof header === "string" && header.includes(":")) {
const [name, value] = header.split(":", 2);
headers[name.trim()] = value.trim();
}
}
}
const body = JSON.stringify(bodyPayload);
return sendRequest(url, "POST", body, headers, timeout, verifyTls);
}
async function fetchStatus(aiRequestId, options = {}) {
const cfg = config();
if (!cfg.projectUuid) {
return {
success: false,
error: "project_uuid_missing",
message: "PROJECT_UUID is not defined; aborting status check.",
};
}
const statusPath = resolveStatusPath(aiRequestId, cfg);
const url = buildUrl(statusPath, cfg.baseUrl);
const timeout = resolveTimeout(options.timeout, cfg.timeout);
const verifyTls = resolveVerifyTls(options.verify_tls, cfg.verifyTls);
const headers = {
Accept: "application/json",
[cfg.projectHeader]: cfg.projectUuid,
};
if (Array.isArray(options.headers)) {
for (const header of options.headers) {
if (typeof header === "string" && header.includes(":")) {
const [name, value] = header.split(":", 2);
headers[name.trim()] = value.trim();
}
}
}
return sendRequest(url, "GET", null, headers, timeout, verifyTls);
}
async function awaitResponse(aiRequestId, options = {}) {
const timeout = Number(options.timeout ?? 300);
const interval = Math.max(Number(options.interval ?? 5), 1);
const deadline = Date.now() + Math.max(timeout, interval) * 1000;
while (true) {
const statusResp = await fetchStatus(aiRequestId, {
headers: options.headers,
timeout: options.timeout_per_call,
verify_tls: options.verify_tls,
});
if (statusResp.success) {
const data = statusResp.data || {};
if (data && typeof data === "object") {
if (data.status === "success") {
return {
success: true,
status: 200,
data: data.response || data,
};
}
if (data.status === "failed") {
return {
success: false,
status: 500,
error: String(data.error || "AI request failed"),
data,
};
}
}
} else {
return statusResp;
}
if (Date.now() >= deadline) {
return {
success: false,
error: "timeout",
message: "Timed out waiting for AI response.",
};
}
await sleep(interval * 1000);
}
}
function extractText(response) {
const payload = response && typeof response === "object" ? response.data || response : null;
if (!payload || typeof payload !== "object") {
return "";
}
if (Array.isArray(payload.output)) {
let combined = "";
for (const item of payload.output) {
if (!item || !Array.isArray(item.content)) {
continue;
}
for (const block of item.content) {
if (
block &&
typeof block === "object" &&
block.type === "output_text" &&
typeof block.text === "string" &&
block.text.length > 0
) {
combined += block.text;
}
}
}
if (combined) {
return combined;
}
}
if (
payload.choices &&
payload.choices[0] &&
payload.choices[0].message &&
typeof payload.choices[0].message.content === "string"
) {
return payload.choices[0].message.content;
}
return "";
}
function decodeJsonFromResponse(response) {
const text = extractText(response);
if (!text) {
throw new Error("No text found in AI response.");
}
const parsed = parseJson(text);
if (parsed.ok && parsed.value && typeof parsed.value === "object") {
return parsed.value;
}
const stripped = stripJsonFence(text);
if (stripped !== text) {
const parsedStripped = parseJson(stripped);
if (parsedStripped.ok && parsedStripped.value && typeof parsedStripped.value === "object") {
return parsedStripped.value;
}
throw new Error(`JSON parse failed after stripping fences: ${parsedStripped.error}`);
}
throw new Error(`JSON parse failed: ${parsed.error}`);
}
function config() {
if (CONFIG_CACHE) {
return CONFIG_CACHE;
}
ensureEnvLoaded();
const baseUrl = process.env.AI_PROXY_BASE_URL || "https://flatlogic.com";
const projectId = process.env.PROJECT_ID || null;
let responsesPath = process.env.AI_RESPONSES_PATH || null;
if (!responsesPath && projectId) {
responsesPath = `/projects/${projectId}/ai-request`;
}
const timeout = resolveTimeout(process.env.AI_TIMEOUT, 30);
const verifyTls = resolveVerifyTls(process.env.AI_VERIFY_TLS, true);
CONFIG_CACHE = {
baseUrl,
responsesPath,
projectId,
projectUuid: process.env.PROJECT_UUID || null,
projectHeader: process.env.AI_PROJECT_HEADER || "project-uuid",
defaultModel: process.env.AI_DEFAULT_MODEL || "gpt-5-mini",
timeout,
verifyTls,
};
return CONFIG_CACHE;
}
function buildUrl(pathValue, baseUrl) {
const trimmed = String(pathValue || "").trim();
if (trimmed === "") {
return baseUrl;
}
if (trimmed.startsWith("http://") || trimmed.startsWith("https://")) {
return trimmed;
}
if (trimmed.startsWith("/")) {
return `${baseUrl}${trimmed}`;
}
return `${baseUrl}/${trimmed}`;
}
function resolveStatusPath(aiRequestId, cfg) {
const basePath = (cfg.responsesPath || "").replace(/\/+$/, "");
if (!basePath) {
return `/ai-request/${encodeURIComponent(String(aiRequestId))}/status`;
}
const normalized = basePath.endsWith("/ai-request") ? basePath : `${basePath}/ai-request`;
return `${normalized}/${encodeURIComponent(String(aiRequestId))}/status`;
}
function sendRequest(urlString, method, body, headers, timeoutSeconds, verifyTls) {
return new Promise((resolve) => {
let targetUrl;
try {
targetUrl = new URL(urlString);
} catch (err) {
resolve({
success: false,
error: "invalid_url",
message: err.message,
});
return;
}
const isHttps = targetUrl.protocol === "https:";
const requestFn = isHttps ? https.request : http.request;
const options = {
protocol: targetUrl.protocol,
hostname: targetUrl.hostname,
port: targetUrl.port || (isHttps ? 443 : 80),
path: `${targetUrl.pathname}${targetUrl.search}`,
method: method.toUpperCase(),
headers,
timeout: Math.max(Number(timeoutSeconds || 30), 1) * 1000,
};
if (isHttps) {
options.rejectUnauthorized = Boolean(verifyTls);
}
const req = requestFn(options, (res) => {
let responseBody = "";
res.setEncoding("utf8");
res.on("data", (chunk) => {
responseBody += chunk;
});
res.on("end", () => {
const status = res.statusCode || 0;
const parsed = parseJson(responseBody);
const payload = parsed.ok ? parsed.value : responseBody;
if (status >= 200 && status < 300) {
const result = {
success: true,
status,
data: payload,
};
if (!parsed.ok) {
result.json_error = parsed.error;
}
resolve(result);
return;
}
const errorMessage =
parsed.ok && payload && typeof payload === "object"
? String(payload.error || payload.message || "AI proxy request failed")
: String(responseBody || "AI proxy request failed");
resolve({
success: false,
status,
error: errorMessage,
response: payload,
json_error: parsed.ok ? undefined : parsed.error,
});
});
});
req.on("timeout", () => {
req.destroy(new Error("request_timeout"));
});
req.on("error", (err) => {
resolve({
success: false,
error: "request_failed",
message: err.message,
});
});
if (body) {
req.write(body);
}
req.end();
});
}
function parseJson(value) {
if (typeof value !== "string" || value.trim() === "") {
return { ok: false, error: "empty_response" };
}
try {
return { ok: true, value: JSON.parse(value) };
} catch (err) {
return { ok: false, error: err.message };
}
}
function stripJsonFence(text) {
const trimmed = text.trim();
if (trimmed.startsWith("```json")) {
return trimmed.replace(/^```json/, "").replace(/```$/, "").trim();
}
if (trimmed.startsWith("```")) {
return trimmed.replace(/^```/, "").replace(/```$/, "").trim();
}
return text;
}
function resolveTimeout(value, fallback) {
const parsed = Number.parseInt(String(value ?? fallback), 10);
return Number.isNaN(parsed) ? Number(fallback) : parsed;
}
function resolveVerifyTls(value, fallback) {
if (value === undefined || value === null) {
return Boolean(fallback);
}
return String(value).toLowerCase() !== "false" && String(value) !== "0";
}
function ensureEnvLoaded() {
if (process.env.PROJECT_UUID && process.env.PROJECT_ID) {
return;
}
const envPath = path.resolve(__dirname, "../../../../.env");
if (!fs.existsSync(envPath)) {
return;
}
let content;
try {
content = fs.readFileSync(envPath, "utf8");
} catch (err) {
throw new Error(`Failed to read executor .env: ${err.message}`);
}
for (const line of content.split(/\r?\n/)) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith("#") || !trimmed.includes("=")) {
continue;
}
const [rawKey, ...rest] = trimmed.split("=");
const key = rawKey.trim();
if (!key) {
continue;
}
const value = rest.join("=").trim().replace(/^['"]|['"]$/g, "");
if (!process.env[key]) {
process.env[key] = value;
}
}
}
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
module.exports = {
LocalAIApi,
createResponse,
request,
fetchStatus,
awaitResponse,
extractText,
decodeJsonFromResponse,
};

68
backend/src/auth/auth.js Normal file
View File

@ -0,0 +1,68 @@
const config = require('../config');
const providers = config.providers;
const helpers = require('../helpers');
const db = require('../db/models');
const passport = require('passport');
const JWTstrategy = require('passport-jwt').Strategy;
const ExtractJWT = require('passport-jwt').ExtractJwt;
const GoogleStrategy = require('passport-google-oauth2').Strategy;
const MicrosoftStrategy = require('passport-microsoft').Strategy;
const UsersDBApi = require('../db/api/users');
passport.use(new JWTstrategy({
passReqToCallback: true,
secretOrKey: config.secret_key,
jwtFromRequest: ExtractJWT.fromAuthHeaderAsBearerToken()
}, async (req, token, done) => {
try {
const user = await UsersDBApi.findBy( {email: token.user.email});
if (user && user.disabled) {
return done (new Error(`User '${user.email}' is disabled`));
}
req.currentUser = user;
return done(null, user);
} catch (error) {
done(error);
}
}));
passport.use(new GoogleStrategy({
clientID: config.google.clientId,
clientSecret: config.google.clientSecret,
callbackURL: config.apiUrl + '/auth/signin/google/callback',
passReqToCallback: true
},
function (request, accessToken, refreshToken, profile, done) {
socialStrategy(profile.email, profile, providers.GOOGLE, done);
}
));
passport.use(new MicrosoftStrategy({
clientID: config.microsoft.clientId,
clientSecret: config.microsoft.clientSecret,
callbackURL: config.apiUrl + '/auth/signin/microsoft/callback',
passReqToCallback: true
},
function (request, accessToken, refreshToken, profile, done) {
const email = profile._json.mail || profile._json.userPrincipalName;
socialStrategy(email, profile, providers.MICROSOFT, done);
}
));
function socialStrategy(email, profile, provider, done) {
db.users.findOrCreate({where: {email, provider}}).then(([user, created]) => {
const body = {
id: user.id,
email: user.email,
name: profile.displayName,
};
const token = helpers.jwtSign({user: body});
return done(null, {token});
});
}

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

@ -0,0 +1,79 @@
const os = require('os');
const config = {
gcloud: {
bucket: "fldemo-files",
hash: "afeefb9d49f5b7977577876b99532ac7"
},
bcrypt: {
saltRounds: 12
},
admin_pass: "9449f547",
user_pass: "5e79c32b885a",
admin_email: "admin@flatlogic.com",
providers: {
LOCAL: 'local',
GOOGLE: 'google',
MICROSOFT: 'microsoft'
},
secret_key: process.env.SECRET_KEY || '9449f547-9488-46d6-b8ec-5e79c32b885a',
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: 'App Preview <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: 'Investor',
},
project_uuid: '9449f547-9488-46d6-b8ec-5e79c32b885a',
flHost: process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'dev_stage' ? 'https://flatlogic.com/projects' : 'http://localhost:3000/projects',
gpt_key: process.env.GPT_KEY || '',
};
config.pexelsKey = process.env.PEXELS_KEY || '';
config.pexelsQuery = 'Lighthouse in stormy sea';
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,515 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Ai_chat_sessionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const ai_chat_sessions = await db.ai_chat_sessions.create(
{
id: data.id || undefined,
title: data.title
||
null
,
mode: data.mode
||
null
,
status: data.status
||
null
,
started_at: data.started_at
||
null
,
last_message_at: data.last_message_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await ai_chat_sessions.setUser( data.user || null, {
transaction,
});
return ai_chat_sessions;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const ai_chat_sessionsData = data.map((item, index) => ({
id: item.id || undefined,
title: item.title
||
null
,
mode: item.mode
||
null
,
status: item.status
||
null
,
started_at: item.started_at
||
null
,
last_message_at: item.last_message_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const ai_chat_sessions = await db.ai_chat_sessions.bulkCreate(ai_chat_sessionsData, { transaction });
// For each item created, replace relation files
return ai_chat_sessions;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const ai_chat_sessions = await db.ai_chat_sessions.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.title !== undefined) updatePayload.title = data.title;
if (data.mode !== undefined) updatePayload.mode = data.mode;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
if (data.last_message_at !== undefined) updatePayload.last_message_at = data.last_message_at;
updatePayload.updatedById = currentUser.id;
await ai_chat_sessions.update(updatePayload, {transaction});
if (data.user !== undefined) {
await ai_chat_sessions.setUser(
data.user,
{ transaction }
);
}
return ai_chat_sessions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const ai_chat_sessions = await db.ai_chat_sessions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of ai_chat_sessions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of ai_chat_sessions) {
await record.destroy({transaction});
}
});
return ai_chat_sessions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const ai_chat_sessions = await db.ai_chat_sessions.findByPk(id, options);
await ai_chat_sessions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await ai_chat_sessions.destroy({
transaction
});
return ai_chat_sessions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const ai_chat_sessions = await db.ai_chat_sessions.findOne(
{ where },
{ transaction },
);
if (!ai_chat_sessions) {
return ai_chat_sessions;
}
const output = ai_chat_sessions.get({plain: true});
output.ai_messages_ai_chat_session = await ai_chat_sessions.getAi_messages_ai_chat_session({
transaction
});
output.user = await ai_chat_sessions.getUser({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.users,
as: 'user',
where: filter.user ? {
[Op.or]: [
{ id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.title) {
where = {
...where,
[Op.and]: Utils.ilike(
'ai_chat_sessions',
'title',
filter.title,
),
};
}
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.last_message_atRange) {
const [start, end] = filter.last_message_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
last_message_at: {
...where.last_message_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
last_message_at: {
...where.last_message_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.mode) {
where = {
...where,
mode: filter.mode,
};
}
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_chat_sessions.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'ai_chat_sessions',
'title',
query,
),
],
};
}
const records = await db.ai_chat_sessions.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,593 @@
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_messagesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const ai_messages = await db.ai_messages.create(
{
id: data.id || undefined,
sent_at: data.sent_at
||
null
,
sender: data.sender
||
null
,
content: data.content
||
null
,
intent: data.intent
||
null
,
risk_level: data.risk_level
||
null
,
recommendation: data.recommendation
||
null
,
confidence: data.confidence
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await ai_messages.setAi_chat_session( data.ai_chat_session || null, {
transaction,
});
await ai_messages.setCited_symbols(data.cited_symbols || [], {
transaction,
});
return ai_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 ai_messagesData = data.map((item, index) => ({
id: item.id || undefined,
sent_at: item.sent_at
||
null
,
sender: item.sender
||
null
,
content: item.content
||
null
,
intent: item.intent
||
null
,
risk_level: item.risk_level
||
null
,
recommendation: item.recommendation
||
null
,
confidence: item.confidence
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const ai_messages = await db.ai_messages.bulkCreate(ai_messagesData, { transaction });
// For each item created, replace relation files
return ai_messages;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const ai_messages = await db.ai_messages.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.sent_at !== undefined) updatePayload.sent_at = data.sent_at;
if (data.sender !== undefined) updatePayload.sender = data.sender;
if (data.content !== undefined) updatePayload.content = data.content;
if (data.intent !== undefined) updatePayload.intent = data.intent;
if (data.risk_level !== undefined) updatePayload.risk_level = data.risk_level;
if (data.recommendation !== undefined) updatePayload.recommendation = data.recommendation;
if (data.confidence !== undefined) updatePayload.confidence = data.confidence;
updatePayload.updatedById = currentUser.id;
await ai_messages.update(updatePayload, {transaction});
if (data.ai_chat_session !== undefined) {
await ai_messages.setAi_chat_session(
data.ai_chat_session,
{ transaction }
);
}
if (data.cited_symbols !== undefined) {
await ai_messages.setCited_symbols(data.cited_symbols, { transaction });
}
return ai_messages;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const ai_messages = await db.ai_messages.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of ai_messages) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of ai_messages) {
await record.destroy({transaction});
}
});
return ai_messages;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const ai_messages = await db.ai_messages.findByPk(id, options);
await ai_messages.update({
deletedBy: currentUser.id
}, {
transaction,
});
await ai_messages.destroy({
transaction
});
return ai_messages;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const ai_messages = await db.ai_messages.findOne(
{ where },
{ transaction },
);
if (!ai_messages) {
return ai_messages;
}
const output = ai_messages.get({plain: true});
output.ai_chat_session = await ai_messages.getAi_chat_session({
transaction
});
output.cited_symbols = await ai_messages.getCited_symbols({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.ai_chat_sessions,
as: 'ai_chat_session',
where: filter.ai_chat_session ? {
[Op.or]: [
{ id: { [Op.in]: filter.ai_chat_session.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.ai_chat_session.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.market_symbols,
as: 'cited_symbols',
required: false,
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.content) {
where = {
...where,
[Op.and]: Utils.ilike(
'ai_messages',
'content',
filter.content,
),
};
}
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.confidenceRange) {
const [start, end] = filter.confidenceRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
confidence: {
...where.confidence,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
confidence: {
...where.confidence,
[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.intent) {
where = {
...where,
intent: filter.intent,
};
}
if (filter.risk_level) {
where = {
...where,
risk_level: filter.risk_level,
};
}
if (filter.recommendation) {
where = {
...where,
recommendation: filter.recommendation,
};
}
if (filter.cited_symbols) {
const searchTerms = filter.cited_symbols.split('|');
include = [
{
model: db.market_symbols,
as: 'cited_symbols_filter',
required: searchTerms.length > 0,
where: searchTerms.length > 0 ? {
[Op.or]: [
{ id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
{
symbol: {
[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.ai_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(
'ai_messages',
'content',
query,
),
],
};
}
const records = await db.ai_messages.findAll({
attributes: [ 'id', 'content' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['content', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.content,
}));
}
};

View File

@ -0,0 +1,539 @@
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 Analyst_ratingsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const analyst_ratings = await db.analyst_ratings.create(
{
id: data.id || undefined,
firm_name: data.firm_name
||
null
,
rating: data.rating
||
null
,
price_target: data.price_target
||
null
,
rating_at: data.rating_at
||
null
,
summary: data.summary
||
null
,
source_url: data.source_url
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await analyst_ratings.setMarket_symbol( data.market_symbol || null, {
transaction,
});
return analyst_ratings;
}
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 analyst_ratingsData = data.map((item, index) => ({
id: item.id || undefined,
firm_name: item.firm_name
||
null
,
rating: item.rating
||
null
,
price_target: item.price_target
||
null
,
rating_at: item.rating_at
||
null
,
summary: item.summary
||
null
,
source_url: item.source_url
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const analyst_ratings = await db.analyst_ratings.bulkCreate(analyst_ratingsData, { transaction });
// For each item created, replace relation files
return analyst_ratings;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const analyst_ratings = await db.analyst_ratings.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.firm_name !== undefined) updatePayload.firm_name = data.firm_name;
if (data.rating !== undefined) updatePayload.rating = data.rating;
if (data.price_target !== undefined) updatePayload.price_target = data.price_target;
if (data.rating_at !== undefined) updatePayload.rating_at = data.rating_at;
if (data.summary !== undefined) updatePayload.summary = data.summary;
if (data.source_url !== undefined) updatePayload.source_url = data.source_url;
updatePayload.updatedById = currentUser.id;
await analyst_ratings.update(updatePayload, {transaction});
if (data.market_symbol !== undefined) {
await analyst_ratings.setMarket_symbol(
data.market_symbol,
{ transaction }
);
}
return analyst_ratings;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const analyst_ratings = await db.analyst_ratings.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of analyst_ratings) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of analyst_ratings) {
await record.destroy({transaction});
}
});
return analyst_ratings;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const analyst_ratings = await db.analyst_ratings.findByPk(id, options);
await analyst_ratings.update({
deletedBy: currentUser.id
}, {
transaction,
});
await analyst_ratings.destroy({
transaction
});
return analyst_ratings;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const analyst_ratings = await db.analyst_ratings.findOne(
{ where },
{ transaction },
);
if (!analyst_ratings) {
return analyst_ratings;
}
const output = analyst_ratings.get({plain: true});
output.market_symbol = await analyst_ratings.getMarket_symbol({
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.market_symbols,
as: 'market_symbol',
where: filter.market_symbol ? {
[Op.or]: [
{ id: { [Op.in]: filter.market_symbol.split('|').map(term => Utils.uuid(term)) } },
{
symbol: {
[Op.or]: filter.market_symbol.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.firm_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'analyst_ratings',
'firm_name',
filter.firm_name,
),
};
}
if (filter.summary) {
where = {
...where,
[Op.and]: Utils.ilike(
'analyst_ratings',
'summary',
filter.summary,
),
};
}
if (filter.source_url) {
where = {
...where,
[Op.and]: Utils.ilike(
'analyst_ratings',
'source_url',
filter.source_url,
),
};
}
if (filter.price_targetRange) {
const [start, end] = filter.price_targetRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
price_target: {
...where.price_target,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
price_target: {
...where.price_target,
[Op.lte]: end,
},
};
}
}
if (filter.rating_atRange) {
const [start, end] = filter.rating_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
rating_at: {
...where.rating_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
rating_at: {
...where.rating_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.rating) {
where = {
...where,
rating: filter.rating,
};
}
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.analyst_ratings.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(
'analyst_ratings',
'firm_name',
query,
),
],
};
}
const records = await db.analyst_ratings.findAll({
attributes: [ 'id', 'firm_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['firm_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.firm_name,
}));
}
};

View File

@ -0,0 +1,507 @@
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 Api_providersDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const api_providers = await db.api_providers.create(
{
id: data.id || undefined,
name: data.name
||
null
,
base_url: data.base_url
||
null
,
provider_type: data.provider_type
||
null
,
enabled: data.enabled
||
false
,
last_health_check_at: data.last_health_check_at
||
null
,
health_status: data.health_status
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return api_providers;
}
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 api_providersData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
base_url: item.base_url
||
null
,
provider_type: item.provider_type
||
null
,
enabled: item.enabled
||
false
,
last_health_check_at: item.last_health_check_at
||
null
,
health_status: item.health_status
||
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 api_providers = await db.api_providers.bulkCreate(api_providersData, { transaction });
// For each item created, replace relation files
return api_providers;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const api_providers = await db.api_providers.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.base_url !== undefined) updatePayload.base_url = data.base_url;
if (data.provider_type !== undefined) updatePayload.provider_type = data.provider_type;
if (data.enabled !== undefined) updatePayload.enabled = data.enabled;
if (data.last_health_check_at !== undefined) updatePayload.last_health_check_at = data.last_health_check_at;
if (data.health_status !== undefined) updatePayload.health_status = data.health_status;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await api_providers.update(updatePayload, {transaction});
return api_providers;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const api_providers = await db.api_providers.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of api_providers) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of api_providers) {
await record.destroy({transaction});
}
});
return api_providers;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const api_providers = await db.api_providers.findByPk(id, options);
await api_providers.update({
deletedBy: currentUser.id
}, {
transaction,
});
await api_providers.destroy({
transaction
});
return api_providers;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const api_providers = await db.api_providers.findOne(
{ where },
{ transaction },
);
if (!api_providers) {
return api_providers;
}
const output = api_providers.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(
'api_providers',
'name',
filter.name,
),
};
}
if (filter.base_url) {
where = {
...where,
[Op.and]: Utils.ilike(
'api_providers',
'base_url',
filter.base_url,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'api_providers',
'notes',
filter.notes,
),
};
}
if (filter.last_health_check_atRange) {
const [start, end] = filter.last_health_check_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
last_health_check_at: {
...where.last_health_check_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
last_health_check_at: {
...where.last_health_check_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.provider_type) {
where = {
...where,
provider_type: filter.provider_type,
};
}
if (filter.enabled) {
where = {
...where,
enabled: filter.enabled,
};
}
if (filter.health_status) {
where = {
...where,
health_status: filter.health_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.api_providers.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(
'api_providers',
'name',
query,
),
],
};
}
const records = await db.api_providers.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,471 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Article_bookmarksDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const article_bookmarks = await db.article_bookmarks.create(
{
id: data.id || undefined,
bookmarked_at: data.bookmarked_at
||
null
,
note: data.note
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await article_bookmarks.setUser( data.user || null, {
transaction,
});
await article_bookmarks.setNews_article( data.news_article || null, {
transaction,
});
return article_bookmarks;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const article_bookmarksData = data.map((item, index) => ({
id: item.id || undefined,
bookmarked_at: item.bookmarked_at
||
null
,
note: item.note
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const article_bookmarks = await db.article_bookmarks.bulkCreate(article_bookmarksData, { transaction });
// For each item created, replace relation files
return article_bookmarks;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const article_bookmarks = await db.article_bookmarks.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.bookmarked_at !== undefined) updatePayload.bookmarked_at = data.bookmarked_at;
if (data.note !== undefined) updatePayload.note = data.note;
updatePayload.updatedById = currentUser.id;
await article_bookmarks.update(updatePayload, {transaction});
if (data.user !== undefined) {
await article_bookmarks.setUser(
data.user,
{ transaction }
);
}
if (data.news_article !== undefined) {
await article_bookmarks.setNews_article(
data.news_article,
{ transaction }
);
}
return article_bookmarks;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const article_bookmarks = await db.article_bookmarks.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of article_bookmarks) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of article_bookmarks) {
await record.destroy({transaction});
}
});
return article_bookmarks;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const article_bookmarks = await db.article_bookmarks.findByPk(id, options);
await article_bookmarks.update({
deletedBy: currentUser.id
}, {
transaction,
});
await article_bookmarks.destroy({
transaction
});
return article_bookmarks;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const article_bookmarks = await db.article_bookmarks.findOne(
{ where },
{ transaction },
);
if (!article_bookmarks) {
return article_bookmarks;
}
const output = article_bookmarks.get({plain: true});
output.user = await article_bookmarks.getUser({
transaction
});
output.news_article = await article_bookmarks.getNews_article({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.users,
as: 'user',
where: filter.user ? {
[Op.or]: [
{ id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.news_articles,
as: 'news_article',
where: filter.news_article ? {
[Op.or]: [
{ id: { [Op.in]: filter.news_article.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.news_article.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.note) {
where = {
...where,
[Op.and]: Utils.ilike(
'article_bookmarks',
'note',
filter.note,
),
};
}
if (filter.bookmarked_atRange) {
const [start, end] = filter.bookmarked_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
bookmarked_at: {
...where.bookmarked_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
bookmarked_at: {
...where.bookmarked_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.article_bookmarks.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'article_bookmarks',
'note',
query,
),
],
};
}
const records = await db.article_bookmarks.findAll({
attributes: [ 'id', 'note' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['note', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.note,
}));
}
};

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 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,
occurred_at: data.occurred_at
||
null
,
event_type: data.event_type
||
null
,
entity_name: data.entity_name
||
null
,
entity_reference: data.entity_reference
||
null
,
metadata_json: data.metadata_json
||
null
,
severity: data.severity
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await audit_events.setUser( data.user || 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,
occurred_at: item.occurred_at
||
null
,
event_type: item.event_type
||
null
,
entity_name: item.entity_name
||
null
,
entity_reference: item.entity_reference
||
null
,
metadata_json: item.metadata_json
||
null
,
severity: item.severity
||
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.occurred_at !== undefined) updatePayload.occurred_at = data.occurred_at;
if (data.event_type !== undefined) updatePayload.event_type = data.event_type;
if (data.entity_name !== undefined) updatePayload.entity_name = data.entity_name;
if (data.entity_reference !== undefined) updatePayload.entity_reference = data.entity_reference;
if (data.metadata_json !== undefined) updatePayload.metadata_json = data.metadata_json;
if (data.severity !== undefined) updatePayload.severity = data.severity;
updatePayload.updatedById = currentUser.id;
await audit_events.update(updatePayload, {transaction});
if (data.user !== undefined) {
await audit_events.setUser(
data.user,
{ 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.user = await audit_events.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.entity_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'audit_events',
'entity_name',
filter.entity_name,
),
};
}
if (filter.entity_reference) {
where = {
...where,
[Op.and]: Utils.ilike(
'audit_events',
'entity_reference',
filter.entity_reference,
),
};
}
if (filter.metadata_json) {
where = {
...where,
[Op.and]: Utils.ilike(
'audit_events',
'metadata_json',
filter.metadata_json,
),
};
}
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_type) {
where = {
...where,
event_type: filter.event_type,
};
}
if (filter.severity) {
where = {
...where,
severity: filter.severity,
};
}
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_type',
query,
),
],
};
}
const records = await db.audit_events.findAll({
attributes: [ 'id', 'event_type' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['event_type', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.event_type,
}));
}
};

View File

@ -0,0 +1,711 @@
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 Earnings_reportsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const earnings_reports = await db.earnings_reports.create(
{
id: data.id || undefined,
period_end_at: data.period_end_at
||
null
,
reported_at: data.reported_at
||
null
,
reported_eps: data.reported_eps
||
null
,
estimated_eps: data.estimated_eps
||
null
,
surprise: data.surprise
||
null
,
surprise_percent: data.surprise_percent
||
null
,
reported_revenue: data.reported_revenue
||
null
,
estimated_revenue: data.estimated_revenue
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await earnings_reports.setMarket_symbol( data.market_symbol || null, {
transaction,
});
return earnings_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 earnings_reportsData = data.map((item, index) => ({
id: item.id || undefined,
period_end_at: item.period_end_at
||
null
,
reported_at: item.reported_at
||
null
,
reported_eps: item.reported_eps
||
null
,
estimated_eps: item.estimated_eps
||
null
,
surprise: item.surprise
||
null
,
surprise_percent: item.surprise_percent
||
null
,
reported_revenue: item.reported_revenue
||
null
,
estimated_revenue: item.estimated_revenue
||
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 earnings_reports = await db.earnings_reports.bulkCreate(earnings_reportsData, { transaction });
// For each item created, replace relation files
return earnings_reports;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const earnings_reports = await db.earnings_reports.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.period_end_at !== undefined) updatePayload.period_end_at = data.period_end_at;
if (data.reported_at !== undefined) updatePayload.reported_at = data.reported_at;
if (data.reported_eps !== undefined) updatePayload.reported_eps = data.reported_eps;
if (data.estimated_eps !== undefined) updatePayload.estimated_eps = data.estimated_eps;
if (data.surprise !== undefined) updatePayload.surprise = data.surprise;
if (data.surprise_percent !== undefined) updatePayload.surprise_percent = data.surprise_percent;
if (data.reported_revenue !== undefined) updatePayload.reported_revenue = data.reported_revenue;
if (data.estimated_revenue !== undefined) updatePayload.estimated_revenue = data.estimated_revenue;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await earnings_reports.update(updatePayload, {transaction});
if (data.market_symbol !== undefined) {
await earnings_reports.setMarket_symbol(
data.market_symbol,
{ transaction }
);
}
return earnings_reports;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const earnings_reports = await db.earnings_reports.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of earnings_reports) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of earnings_reports) {
await record.destroy({transaction});
}
});
return earnings_reports;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const earnings_reports = await db.earnings_reports.findByPk(id, options);
await earnings_reports.update({
deletedBy: currentUser.id
}, {
transaction,
});
await earnings_reports.destroy({
transaction
});
return earnings_reports;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const earnings_reports = await db.earnings_reports.findOne(
{ where },
{ transaction },
);
if (!earnings_reports) {
return earnings_reports;
}
const output = earnings_reports.get({plain: true});
output.market_symbol = await earnings_reports.getMarket_symbol({
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.market_symbols,
as: 'market_symbol',
where: filter.market_symbol ? {
[Op.or]: [
{ id: { [Op.in]: filter.market_symbol.split('|').map(term => Utils.uuid(term)) } },
{
symbol: {
[Op.or]: filter.market_symbol.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'earnings_reports',
'notes',
filter.notes,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
reported_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
period_end_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.period_end_atRange) {
const [start, end] = filter.period_end_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
period_end_at: {
...where.period_end_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
period_end_at: {
...where.period_end_at,
[Op.lte]: end,
},
};
}
}
if (filter.reported_atRange) {
const [start, end] = filter.reported_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
reported_at: {
...where.reported_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
reported_at: {
...where.reported_at,
[Op.lte]: end,
},
};
}
}
if (filter.reported_epsRange) {
const [start, end] = filter.reported_epsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
reported_eps: {
...where.reported_eps,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
reported_eps: {
...where.reported_eps,
[Op.lte]: end,
},
};
}
}
if (filter.estimated_epsRange) {
const [start, end] = filter.estimated_epsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
estimated_eps: {
...where.estimated_eps,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
estimated_eps: {
...where.estimated_eps,
[Op.lte]: end,
},
};
}
}
if (filter.surpriseRange) {
const [start, end] = filter.surpriseRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
surprise: {
...where.surprise,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
surprise: {
...where.surprise,
[Op.lte]: end,
},
};
}
}
if (filter.surprise_percentRange) {
const [start, end] = filter.surprise_percentRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
surprise_percent: {
...where.surprise_percent,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
surprise_percent: {
...where.surprise_percent,
[Op.lte]: end,
},
};
}
}
if (filter.reported_revenueRange) {
const [start, end] = filter.reported_revenueRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
reported_revenue: {
...where.reported_revenue,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
reported_revenue: {
...where.reported_revenue,
[Op.lte]: end,
},
};
}
}
if (filter.estimated_revenueRange) {
const [start, end] = filter.estimated_revenueRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
estimated_revenue: {
...where.estimated_revenue,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
estimated_revenue: {
...where.estimated_revenue,
[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.earnings_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(
'earnings_reports',
'notes',
query,
),
],
};
}
const records = await db.earnings_reports.findAll({
attributes: [ 'id', 'notes' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['notes', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.notes,
}));
}
};

View File

@ -0,0 +1,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,524 @@
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 Ir_announcementsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const ir_announcements = await db.ir_announcements.create(
{
id: data.id || undefined,
title: data.title
||
null
,
announced_at: data.announced_at
||
null
,
body: data.body
||
null
,
source_url: data.source_url
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await ir_announcements.setIr_company( data.ir_company || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.ir_announcements.getTableName(),
belongsToColumn: 'attachments',
belongsToId: ir_announcements.id,
},
data.attachments,
options,
);
return ir_announcements;
}
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 ir_announcementsData = data.map((item, index) => ({
id: item.id || undefined,
title: item.title
||
null
,
announced_at: item.announced_at
||
null
,
body: item.body
||
null
,
source_url: item.source_url
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const ir_announcements = await db.ir_announcements.bulkCreate(ir_announcementsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < ir_announcements.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.ir_announcements.getTableName(),
belongsToColumn: 'attachments',
belongsToId: ir_announcements[i].id,
},
data[i].attachments,
options,
);
}
return ir_announcements;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const ir_announcements = await db.ir_announcements.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.title !== undefined) updatePayload.title = data.title;
if (data.announced_at !== undefined) updatePayload.announced_at = data.announced_at;
if (data.body !== undefined) updatePayload.body = data.body;
if (data.source_url !== undefined) updatePayload.source_url = data.source_url;
updatePayload.updatedById = currentUser.id;
await ir_announcements.update(updatePayload, {transaction});
if (data.ir_company !== undefined) {
await ir_announcements.setIr_company(
data.ir_company,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.ir_announcements.getTableName(),
belongsToColumn: 'attachments',
belongsToId: ir_announcements.id,
},
data.attachments,
options,
);
return ir_announcements;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const ir_announcements = await db.ir_announcements.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of ir_announcements) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of ir_announcements) {
await record.destroy({transaction});
}
});
return ir_announcements;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const ir_announcements = await db.ir_announcements.findByPk(id, options);
await ir_announcements.update({
deletedBy: currentUser.id
}, {
transaction,
});
await ir_announcements.destroy({
transaction
});
return ir_announcements;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const ir_announcements = await db.ir_announcements.findOne(
{ where },
{ transaction },
);
if (!ir_announcements) {
return ir_announcements;
}
const output = ir_announcements.get({plain: true});
output.ir_company = await ir_announcements.getIr_company({
transaction
});
output.attachments = await ir_announcements.getAttachments({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.ir_companies,
as: 'ir_company',
where: filter.ir_company ? {
[Op.or]: [
{ id: { [Op.in]: filter.ir_company.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.ir_company.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.file,
as: 'attachments',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.title) {
where = {
...where,
[Op.and]: Utils.ilike(
'ir_announcements',
'title',
filter.title,
),
};
}
if (filter.body) {
where = {
...where,
[Op.and]: Utils.ilike(
'ir_announcements',
'body',
filter.body,
),
};
}
if (filter.source_url) {
where = {
...where,
[Op.and]: Utils.ilike(
'ir_announcements',
'source_url',
filter.source_url,
),
};
}
if (filter.announced_atRange) {
const [start, end] = filter.announced_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
announced_at: {
...where.announced_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
announced_at: {
...where.announced_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.ir_announcements.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(
'ir_announcements',
'title',
query,
),
],
};
}
const records = await db.ir_announcements.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,526 @@
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 Ir_companiesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const ir_companies = await db.ir_companies.create(
{
id: data.id || undefined,
name: data.name
||
null
,
website: data.website
||
null
,
description: data.description
||
null
,
hq_location: data.hq_location
||
null
,
last_updated_at: data.last_updated_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await ir_companies.setMarket_symbol( data.market_symbol || null, {
transaction,
});
return ir_companies;
}
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 ir_companiesData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
website: item.website
||
null
,
description: item.description
||
null
,
hq_location: item.hq_location
||
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 ir_companies = await db.ir_companies.bulkCreate(ir_companiesData, { transaction });
// For each item created, replace relation files
return ir_companies;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const ir_companies = await db.ir_companies.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.website !== undefined) updatePayload.website = data.website;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.hq_location !== undefined) updatePayload.hq_location = data.hq_location;
if (data.last_updated_at !== undefined) updatePayload.last_updated_at = data.last_updated_at;
updatePayload.updatedById = currentUser.id;
await ir_companies.update(updatePayload, {transaction});
if (data.market_symbol !== undefined) {
await ir_companies.setMarket_symbol(
data.market_symbol,
{ transaction }
);
}
return ir_companies;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const ir_companies = await db.ir_companies.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of ir_companies) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of ir_companies) {
await record.destroy({transaction});
}
});
return ir_companies;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const ir_companies = await db.ir_companies.findByPk(id, options);
await ir_companies.update({
deletedBy: currentUser.id
}, {
transaction,
});
await ir_companies.destroy({
transaction
});
return ir_companies;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const ir_companies = await db.ir_companies.findOne(
{ where },
{ transaction },
);
if (!ir_companies) {
return ir_companies;
}
const output = ir_companies.get({plain: true});
output.ir_management_members_ir_company = await ir_companies.getIr_management_members_ir_company({
transaction
});
output.ir_filings_ir_company = await ir_companies.getIr_filings_ir_company({
transaction
});
output.ir_dividends_ir_company = await ir_companies.getIr_dividends_ir_company({
transaction
});
output.ir_announcements_ir_company = await ir_companies.getIr_announcements_ir_company({
transaction
});
output.ir_financial_statement_summaries_ir_company = await ir_companies.getIr_financial_statement_summaries_ir_company({
transaction
});
output.market_symbol = await ir_companies.getMarket_symbol({
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.market_symbols,
as: 'market_symbol',
where: filter.market_symbol ? {
[Op.or]: [
{ id: { [Op.in]: filter.market_symbol.split('|').map(term => Utils.uuid(term)) } },
{
symbol: {
[Op.or]: filter.market_symbol.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'ir_companies',
'name',
filter.name,
),
};
}
if (filter.website) {
where = {
...where,
[Op.and]: Utils.ilike(
'ir_companies',
'website',
filter.website,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'ir_companies',
'description',
filter.description,
),
};
}
if (filter.hq_location) {
where = {
...where,
[Op.and]: Utils.ilike(
'ir_companies',
'hq_location',
filter.hq_location,
),
};
}
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.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.ir_companies.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(
'ir_companies',
'name',
query,
),
],
};
}
const records = await db.ir_companies.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,616 @@
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 Ir_dividendsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const ir_dividends = await db.ir_dividends.create(
{
id: data.id || undefined,
declaration_at: data.declaration_at
||
null
,
ex_dividend_at: data.ex_dividend_at
||
null
,
record_at: data.record_at
||
null
,
payable_at: data.payable_at
||
null
,
amount: data.amount
||
null
,
currency: data.currency
||
null
,
frequency: data.frequency
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await ir_dividends.setIr_company( data.ir_company || null, {
transaction,
});
return ir_dividends;
}
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 ir_dividendsData = data.map((item, index) => ({
id: item.id || undefined,
declaration_at: item.declaration_at
||
null
,
ex_dividend_at: item.ex_dividend_at
||
null
,
record_at: item.record_at
||
null
,
payable_at: item.payable_at
||
null
,
amount: item.amount
||
null
,
currency: item.currency
||
null
,
frequency: item.frequency
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const ir_dividends = await db.ir_dividends.bulkCreate(ir_dividendsData, { transaction });
// For each item created, replace relation files
return ir_dividends;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const ir_dividends = await db.ir_dividends.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.declaration_at !== undefined) updatePayload.declaration_at = data.declaration_at;
if (data.ex_dividend_at !== undefined) updatePayload.ex_dividend_at = data.ex_dividend_at;
if (data.record_at !== undefined) updatePayload.record_at = data.record_at;
if (data.payable_at !== undefined) updatePayload.payable_at = data.payable_at;
if (data.amount !== undefined) updatePayload.amount = data.amount;
if (data.currency !== undefined) updatePayload.currency = data.currency;
if (data.frequency !== undefined) updatePayload.frequency = data.frequency;
updatePayload.updatedById = currentUser.id;
await ir_dividends.update(updatePayload, {transaction});
if (data.ir_company !== undefined) {
await ir_dividends.setIr_company(
data.ir_company,
{ transaction }
);
}
return ir_dividends;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const ir_dividends = await db.ir_dividends.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of ir_dividends) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of ir_dividends) {
await record.destroy({transaction});
}
});
return ir_dividends;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const ir_dividends = await db.ir_dividends.findByPk(id, options);
await ir_dividends.update({
deletedBy: currentUser.id
}, {
transaction,
});
await ir_dividends.destroy({
transaction
});
return ir_dividends;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const ir_dividends = await db.ir_dividends.findOne(
{ where },
{ transaction },
);
if (!ir_dividends) {
return ir_dividends;
}
const output = ir_dividends.get({plain: true});
output.ir_company = await ir_dividends.getIr_company({
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.ir_companies,
as: 'ir_company',
where: filter.ir_company ? {
[Op.or]: [
{ id: { [Op.in]: filter.ir_company.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.ir_company.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
ex_dividend_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
payable_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.declaration_atRange) {
const [start, end] = filter.declaration_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
declaration_at: {
...where.declaration_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
declaration_at: {
...where.declaration_at,
[Op.lte]: end,
},
};
}
}
if (filter.ex_dividend_atRange) {
const [start, end] = filter.ex_dividend_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
ex_dividend_at: {
...where.ex_dividend_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
ex_dividend_at: {
...where.ex_dividend_at,
[Op.lte]: end,
},
};
}
}
if (filter.record_atRange) {
const [start, end] = filter.record_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
record_at: {
...where.record_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
record_at: {
...where.record_at,
[Op.lte]: end,
},
};
}
}
if (filter.payable_atRange) {
const [start, end] = filter.payable_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
payable_at: {
...where.payable_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
payable_at: {
...where.payable_at,
[Op.lte]: end,
},
};
}
}
if (filter.amountRange) {
const [start, end] = filter.amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
amount: {
...where.amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
amount: {
...where.amount,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.currency) {
where = {
...where,
currency: filter.currency,
};
}
if (filter.frequency) {
where = {
...where,
frequency: filter.frequency,
};
}
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.ir_dividends.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(
'ir_dividends',
'currency',
query,
),
],
};
}
const records = await db.ir_dividends.findAll({
attributes: [ 'id', 'currency' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['currency', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.currency,
}));
}
};

View File

@ -0,0 +1,544 @@
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 Ir_filingsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const ir_filings = await db.ir_filings.create(
{
id: data.id || undefined,
filing_type: data.filing_type
||
null
,
title: data.title
||
null
,
filed_at: data.filed_at
||
null
,
sec_url: data.sec_url
||
null
,
summary: data.summary
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await ir_filings.setIr_company( data.ir_company || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.ir_filings.getTableName(),
belongsToColumn: 'attachments',
belongsToId: ir_filings.id,
},
data.attachments,
options,
);
return ir_filings;
}
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 ir_filingsData = data.map((item, index) => ({
id: item.id || undefined,
filing_type: item.filing_type
||
null
,
title: item.title
||
null
,
filed_at: item.filed_at
||
null
,
sec_url: item.sec_url
||
null
,
summary: item.summary
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const ir_filings = await db.ir_filings.bulkCreate(ir_filingsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < ir_filings.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.ir_filings.getTableName(),
belongsToColumn: 'attachments',
belongsToId: ir_filings[i].id,
},
data[i].attachments,
options,
);
}
return ir_filings;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const ir_filings = await db.ir_filings.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.filing_type !== undefined) updatePayload.filing_type = data.filing_type;
if (data.title !== undefined) updatePayload.title = data.title;
if (data.filed_at !== undefined) updatePayload.filed_at = data.filed_at;
if (data.sec_url !== undefined) updatePayload.sec_url = data.sec_url;
if (data.summary !== undefined) updatePayload.summary = data.summary;
updatePayload.updatedById = currentUser.id;
await ir_filings.update(updatePayload, {transaction});
if (data.ir_company !== undefined) {
await ir_filings.setIr_company(
data.ir_company,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.ir_filings.getTableName(),
belongsToColumn: 'attachments',
belongsToId: ir_filings.id,
},
data.attachments,
options,
);
return ir_filings;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const ir_filings = await db.ir_filings.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of ir_filings) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of ir_filings) {
await record.destroy({transaction});
}
});
return ir_filings;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const ir_filings = await db.ir_filings.findByPk(id, options);
await ir_filings.update({
deletedBy: currentUser.id
}, {
transaction,
});
await ir_filings.destroy({
transaction
});
return ir_filings;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const ir_filings = await db.ir_filings.findOne(
{ where },
{ transaction },
);
if (!ir_filings) {
return ir_filings;
}
const output = ir_filings.get({plain: true});
output.ir_company = await ir_filings.getIr_company({
transaction
});
output.attachments = await ir_filings.getAttachments({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.ir_companies,
as: 'ir_company',
where: filter.ir_company ? {
[Op.or]: [
{ id: { [Op.in]: filter.ir_company.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.ir_company.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.file,
as: 'attachments',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.title) {
where = {
...where,
[Op.and]: Utils.ilike(
'ir_filings',
'title',
filter.title,
),
};
}
if (filter.sec_url) {
where = {
...where,
[Op.and]: Utils.ilike(
'ir_filings',
'sec_url',
filter.sec_url,
),
};
}
if (filter.summary) {
where = {
...where,
[Op.and]: Utils.ilike(
'ir_filings',
'summary',
filter.summary,
),
};
}
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.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.filing_type) {
where = {
...where,
filing_type: filter.filing_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.ir_filings.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(
'ir_filings',
'title',
query,
),
],
};
}
const records = await db.ir_filings.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,659 @@
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 Ir_financial_statement_summariesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const ir_financial_statement_summaries = await db.ir_financial_statement_summaries.create(
{
id: data.id || undefined,
statement_type: data.statement_type
||
null
,
period_type: data.period_type
||
null
,
period_end_at: data.period_end_at
||
null
,
total_revenue: data.total_revenue
||
null
,
net_income: data.net_income
||
null
,
total_assets: data.total_assets
||
null
,
total_liabilities: data.total_liabilities
||
null
,
free_cash_flow: data.free_cash_flow
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await ir_financial_statement_summaries.setIr_company( data.ir_company || null, {
transaction,
});
return ir_financial_statement_summaries;
}
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 ir_financial_statement_summariesData = data.map((item, index) => ({
id: item.id || undefined,
statement_type: item.statement_type
||
null
,
period_type: item.period_type
||
null
,
period_end_at: item.period_end_at
||
null
,
total_revenue: item.total_revenue
||
null
,
net_income: item.net_income
||
null
,
total_assets: item.total_assets
||
null
,
total_liabilities: item.total_liabilities
||
null
,
free_cash_flow: item.free_cash_flow
||
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 ir_financial_statement_summaries = await db.ir_financial_statement_summaries.bulkCreate(ir_financial_statement_summariesData, { transaction });
// For each item created, replace relation files
return ir_financial_statement_summaries;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const ir_financial_statement_summaries = await db.ir_financial_statement_summaries.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.statement_type !== undefined) updatePayload.statement_type = data.statement_type;
if (data.period_type !== undefined) updatePayload.period_type = data.period_type;
if (data.period_end_at !== undefined) updatePayload.period_end_at = data.period_end_at;
if (data.total_revenue !== undefined) updatePayload.total_revenue = data.total_revenue;
if (data.net_income !== undefined) updatePayload.net_income = data.net_income;
if (data.total_assets !== undefined) updatePayload.total_assets = data.total_assets;
if (data.total_liabilities !== undefined) updatePayload.total_liabilities = data.total_liabilities;
if (data.free_cash_flow !== undefined) updatePayload.free_cash_flow = data.free_cash_flow;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await ir_financial_statement_summaries.update(updatePayload, {transaction});
if (data.ir_company !== undefined) {
await ir_financial_statement_summaries.setIr_company(
data.ir_company,
{ transaction }
);
}
return ir_financial_statement_summaries;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const ir_financial_statement_summaries = await db.ir_financial_statement_summaries.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of ir_financial_statement_summaries) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of ir_financial_statement_summaries) {
await record.destroy({transaction});
}
});
return ir_financial_statement_summaries;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const ir_financial_statement_summaries = await db.ir_financial_statement_summaries.findByPk(id, options);
await ir_financial_statement_summaries.update({
deletedBy: currentUser.id
}, {
transaction,
});
await ir_financial_statement_summaries.destroy({
transaction
});
return ir_financial_statement_summaries;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const ir_financial_statement_summaries = await db.ir_financial_statement_summaries.findOne(
{ where },
{ transaction },
);
if (!ir_financial_statement_summaries) {
return ir_financial_statement_summaries;
}
const output = ir_financial_statement_summaries.get({plain: true});
output.ir_company = await ir_financial_statement_summaries.getIr_company({
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.ir_companies,
as: 'ir_company',
where: filter.ir_company ? {
[Op.or]: [
{ id: { [Op.in]: filter.ir_company.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.ir_company.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'ir_financial_statement_summaries',
'notes',
filter.notes,
),
};
}
if (filter.period_end_atRange) {
const [start, end] = filter.period_end_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
period_end_at: {
...where.period_end_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
period_end_at: {
...where.period_end_at,
[Op.lte]: end,
},
};
}
}
if (filter.total_revenueRange) {
const [start, end] = filter.total_revenueRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
total_revenue: {
...where.total_revenue,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
total_revenue: {
...where.total_revenue,
[Op.lte]: end,
},
};
}
}
if (filter.net_incomeRange) {
const [start, end] = filter.net_incomeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
net_income: {
...where.net_income,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
net_income: {
...where.net_income,
[Op.lte]: end,
},
};
}
}
if (filter.total_assetsRange) {
const [start, end] = filter.total_assetsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
total_assets: {
...where.total_assets,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
total_assets: {
...where.total_assets,
[Op.lte]: end,
},
};
}
}
if (filter.total_liabilitiesRange) {
const [start, end] = filter.total_liabilitiesRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
total_liabilities: {
...where.total_liabilities,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
total_liabilities: {
...where.total_liabilities,
[Op.lte]: end,
},
};
}
}
if (filter.free_cash_flowRange) {
const [start, end] = filter.free_cash_flowRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
free_cash_flow: {
...where.free_cash_flow,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
free_cash_flow: {
...where.free_cash_flow,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.statement_type) {
where = {
...where,
statement_type: filter.statement_type,
};
}
if (filter.period_type) {
where = {
...where,
period_type: filter.period_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.ir_financial_statement_summaries.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(
'ir_financial_statement_summaries',
'statement_type',
query,
),
],
};
}
const records = await db.ir_financial_statement_summaries.findAll({
attributes: [ 'id', 'statement_type' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['statement_type', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.statement_type,
}));
}
};

View File

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

View File

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

View File

@ -0,0 +1,627 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Market_symbolsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const market_symbols = await db.market_symbols.create(
{
id: data.id || undefined,
symbol: data.symbol
||
null
,
name: data.name
||
null
,
asset_class: data.asset_class
||
null
,
exchange: data.exchange
||
null
,
currency: data.currency
||
null
,
country: data.country
||
null
,
sector: data.sector
||
null
,
industry: data.industry
||
null
,
active: data.active
||
false
,
last_refreshed_at: data.last_refreshed_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return market_symbols;
}
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 market_symbolsData = data.map((item, index) => ({
id: item.id || undefined,
symbol: item.symbol
||
null
,
name: item.name
||
null
,
asset_class: item.asset_class
||
null
,
exchange: item.exchange
||
null
,
currency: item.currency
||
null
,
country: item.country
||
null
,
sector: item.sector
||
null
,
industry: item.industry
||
null
,
active: item.active
||
false
,
last_refreshed_at: item.last_refreshed_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const market_symbols = await db.market_symbols.bulkCreate(market_symbolsData, { transaction });
// For each item created, replace relation files
return market_symbols;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const market_symbols = await db.market_symbols.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.symbol !== undefined) updatePayload.symbol = data.symbol;
if (data.name !== undefined) updatePayload.name = data.name;
if (data.asset_class !== undefined) updatePayload.asset_class = data.asset_class;
if (data.exchange !== undefined) updatePayload.exchange = data.exchange;
if (data.currency !== undefined) updatePayload.currency = data.currency;
if (data.country !== undefined) updatePayload.country = data.country;
if (data.sector !== undefined) updatePayload.sector = data.sector;
if (data.industry !== undefined) updatePayload.industry = data.industry;
if (data.active !== undefined) updatePayload.active = data.active;
if (data.last_refreshed_at !== undefined) updatePayload.last_refreshed_at = data.last_refreshed_at;
updatePayload.updatedById = currentUser.id;
await market_symbols.update(updatePayload, {transaction});
return market_symbols;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const market_symbols = await db.market_symbols.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of market_symbols) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of market_symbols) {
await record.destroy({transaction});
}
});
return market_symbols;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const market_symbols = await db.market_symbols.findByPk(id, options);
await market_symbols.update({
deletedBy: currentUser.id
}, {
transaction,
});
await market_symbols.destroy({
transaction
});
return market_symbols;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const market_symbols = await db.market_symbols.findOne(
{ where },
{ transaction },
);
if (!market_symbols) {
return market_symbols;
}
const output = market_symbols.get({plain: true});
output.symbol_fundamentals_market_symbol = await market_symbols.getSymbol_fundamentals_market_symbol({
transaction
});
output.price_quotes_market_symbol = await market_symbols.getPrice_quotes_market_symbol({
transaction
});
output.technical_indicators_market_symbol = await market_symbols.getTechnical_indicators_market_symbol({
transaction
});
output.analyst_ratings_market_symbol = await market_symbols.getAnalyst_ratings_market_symbol({
transaction
});
output.earnings_reports_market_symbol = await market_symbols.getEarnings_reports_market_symbol({
transaction
});
output.news_article_symbols_market_symbol = await market_symbols.getNews_article_symbols_market_symbol({
transaction
});
output.watchlist_items_market_symbol = await market_symbols.getWatchlist_items_market_symbol({
transaction
});
output.paper_orders_market_symbol = await market_symbols.getPaper_orders_market_symbol({
transaction
});
output.paper_positions_market_symbol = await market_symbols.getPaper_positions_market_symbol({
transaction
});
output.screener_results_market_symbol = await market_symbols.getScreener_results_market_symbol({
transaction
});
output.ir_companies_market_symbol = await market_symbols.getIr_companies_market_symbol({
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.symbol) {
where = {
...where,
[Op.and]: Utils.ilike(
'market_symbols',
'symbol',
filter.symbol,
),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'market_symbols',
'name',
filter.name,
),
};
}
if (filter.exchange) {
where = {
...where,
[Op.and]: Utils.ilike(
'market_symbols',
'exchange',
filter.exchange,
),
};
}
if (filter.currency) {
where = {
...where,
[Op.and]: Utils.ilike(
'market_symbols',
'currency',
filter.currency,
),
};
}
if (filter.country) {
where = {
...where,
[Op.and]: Utils.ilike(
'market_symbols',
'country',
filter.country,
),
};
}
if (filter.sector) {
where = {
...where,
[Op.and]: Utils.ilike(
'market_symbols',
'sector',
filter.sector,
),
};
}
if (filter.industry) {
where = {
...where,
[Op.and]: Utils.ilike(
'market_symbols',
'industry',
filter.industry,
),
};
}
if (filter.last_refreshed_atRange) {
const [start, end] = filter.last_refreshed_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
last_refreshed_at: {
...where.last_refreshed_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
last_refreshed_at: {
...where.last_refreshed_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.asset_class) {
where = {
...where,
asset_class: filter.asset_class,
};
}
if (filter.active) {
where = {
...where,
active: filter.active,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.market_symbols.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(
'market_symbols',
'symbol',
query,
),
],
};
}
const records = await db.market_symbols.findAll({
attributes: [ 'id', 'symbol' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['symbol', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.symbol,
}));
}
};

View File

@ -0,0 +1,467 @@
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 News_article_symbolsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const news_article_symbols = await db.news_article_symbols.create(
{
id: data.id || undefined,
relevance: data.relevance
||
null
,
sentiment_score: data.sentiment_score
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await news_article_symbols.setNews_article( data.news_article || null, {
transaction,
});
await news_article_symbols.setMarket_symbol( data.market_symbol || null, {
transaction,
});
return news_article_symbols;
}
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 news_article_symbolsData = data.map((item, index) => ({
id: item.id || undefined,
relevance: item.relevance
||
null
,
sentiment_score: item.sentiment_score
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const news_article_symbols = await db.news_article_symbols.bulkCreate(news_article_symbolsData, { transaction });
// For each item created, replace relation files
return news_article_symbols;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const news_article_symbols = await db.news_article_symbols.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.relevance !== undefined) updatePayload.relevance = data.relevance;
if (data.sentiment_score !== undefined) updatePayload.sentiment_score = data.sentiment_score;
updatePayload.updatedById = currentUser.id;
await news_article_symbols.update(updatePayload, {transaction});
if (data.news_article !== undefined) {
await news_article_symbols.setNews_article(
data.news_article,
{ transaction }
);
}
if (data.market_symbol !== undefined) {
await news_article_symbols.setMarket_symbol(
data.market_symbol,
{ transaction }
);
}
return news_article_symbols;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const news_article_symbols = await db.news_article_symbols.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of news_article_symbols) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of news_article_symbols) {
await record.destroy({transaction});
}
});
return news_article_symbols;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const news_article_symbols = await db.news_article_symbols.findByPk(id, options);
await news_article_symbols.update({
deletedBy: currentUser.id
}, {
transaction,
});
await news_article_symbols.destroy({
transaction
});
return news_article_symbols;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const news_article_symbols = await db.news_article_symbols.findOne(
{ where },
{ transaction },
);
if (!news_article_symbols) {
return news_article_symbols;
}
const output = news_article_symbols.get({plain: true});
output.news_article = await news_article_symbols.getNews_article({
transaction
});
output.market_symbol = await news_article_symbols.getMarket_symbol({
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.news_articles,
as: 'news_article',
where: filter.news_article ? {
[Op.or]: [
{ id: { [Op.in]: filter.news_article.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.news_article.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.market_symbols,
as: 'market_symbol',
where: filter.market_symbol ? {
[Op.or]: [
{ id: { [Op.in]: filter.market_symbol.split('|').map(term => Utils.uuid(term)) } },
{
symbol: {
[Op.or]: filter.market_symbol.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.sentiment_scoreRange) {
const [start, end] = filter.sentiment_scoreRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sentiment_score: {
...where.sentiment_score,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sentiment_score: {
...where.sentiment_score,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.relevance) {
where = {
...where,
relevance: filter.relevance,
};
}
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.news_article_symbols.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(
'news_article_symbols',
'relevance',
query,
),
],
};
}
const records = await db.news_article_symbols.findAll({
attributes: [ 'id', 'relevance' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['relevance', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.relevance,
}));
}
};

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 News_articlesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const news_articles = await db.news_articles.create(
{
id: data.id || undefined,
title: data.title
||
null
,
publisher: data.publisher
||
null
,
published_at: data.published_at
||
null
,
category: data.category
||
null
,
url: data.url
||
null
,
summary: data.summary
||
null
,
content: data.content
||
null
,
sentiment: data.sentiment
||
null
,
source: data.source
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.news_articles.getTableName(),
belongsToColumn: 'cover_images',
belongsToId: news_articles.id,
},
data.cover_images,
options,
);
return news_articles;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const news_articlesData = data.map((item, index) => ({
id: item.id || undefined,
title: item.title
||
null
,
publisher: item.publisher
||
null
,
published_at: item.published_at
||
null
,
category: item.category
||
null
,
url: item.url
||
null
,
summary: item.summary
||
null
,
content: item.content
||
null
,
sentiment: item.sentiment
||
null
,
source: item.source
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const news_articles = await db.news_articles.bulkCreate(news_articlesData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < news_articles.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.news_articles.getTableName(),
belongsToColumn: 'cover_images',
belongsToId: news_articles[i].id,
},
data[i].cover_images,
options,
);
}
return news_articles;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const news_articles = await db.news_articles.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.title !== undefined) updatePayload.title = data.title;
if (data.publisher !== undefined) updatePayload.publisher = data.publisher;
if (data.published_at !== undefined) updatePayload.published_at = data.published_at;
if (data.category !== undefined) updatePayload.category = data.category;
if (data.url !== undefined) updatePayload.url = data.url;
if (data.summary !== undefined) updatePayload.summary = data.summary;
if (data.content !== undefined) updatePayload.content = data.content;
if (data.sentiment !== undefined) updatePayload.sentiment = data.sentiment;
if (data.source !== undefined) updatePayload.source = data.source;
updatePayload.updatedById = currentUser.id;
await news_articles.update(updatePayload, {transaction});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.news_articles.getTableName(),
belongsToColumn: 'cover_images',
belongsToId: news_articles.id,
},
data.cover_images,
options,
);
return news_articles;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const news_articles = await db.news_articles.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of news_articles) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of news_articles) {
await record.destroy({transaction});
}
});
return news_articles;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const news_articles = await db.news_articles.findByPk(id, options);
await news_articles.update({
deletedBy: currentUser.id
}, {
transaction,
});
await news_articles.destroy({
transaction
});
return news_articles;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const news_articles = await db.news_articles.findOne(
{ where },
{ transaction },
);
if (!news_articles) {
return news_articles;
}
const output = news_articles.get({plain: true});
output.news_article_symbols_news_article = await news_articles.getNews_article_symbols_news_article({
transaction
});
output.article_bookmarks_news_article = await news_articles.getArticle_bookmarks_news_article({
transaction
});
output.cover_images = await news_articles.getCover_images({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.file,
as: 'cover_images',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.title) {
where = {
...where,
[Op.and]: Utils.ilike(
'news_articles',
'title',
filter.title,
),
};
}
if (filter.publisher) {
where = {
...where,
[Op.and]: Utils.ilike(
'news_articles',
'publisher',
filter.publisher,
),
};
}
if (filter.url) {
where = {
...where,
[Op.and]: Utils.ilike(
'news_articles',
'url',
filter.url,
),
};
}
if (filter.summary) {
where = {
...where,
[Op.and]: Utils.ilike(
'news_articles',
'summary',
filter.summary,
),
};
}
if (filter.content) {
where = {
...where,
[Op.and]: Utils.ilike(
'news_articles',
'content',
filter.content,
),
};
}
if (filter.source) {
where = {
...where,
[Op.and]: Utils.ilike(
'news_articles',
'source',
filter.source,
),
};
}
if (filter.published_atRange) {
const [start, end] = filter.published_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
published_at: {
...where.published_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
published_at: {
...where.published_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.category) {
where = {
...where,
category: filter.category,
};
}
if (filter.sentiment) {
where = {
...where,
sentiment: filter.sentiment,
};
}
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.news_articles.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'news_articles',
'title',
query,
),
],
};
}
const records = await db.news_articles.findAll({
attributes: [ 'id', 'title' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['title', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.title,
}));
}
};

View File

@ -0,0 +1,599 @@
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 Paper_accountsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const paper_accounts = await db.paper_accounts.create(
{
id: data.id || undefined,
name: data.name
||
null
,
base_currency: data.base_currency
||
null
,
starting_cash: data.starting_cash
||
null
,
cash_balance: data.cash_balance
||
null
,
buying_power: data.buying_power
||
null
,
is_active: data.is_active
||
false
,
opened_at: data.opened_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await paper_accounts.setUser( data.user || null, {
transaction,
});
return paper_accounts;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const paper_accountsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
base_currency: item.base_currency
||
null
,
starting_cash: item.starting_cash
||
null
,
cash_balance: item.cash_balance
||
null
,
buying_power: item.buying_power
||
null
,
is_active: item.is_active
||
false
,
opened_at: item.opened_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const paper_accounts = await db.paper_accounts.bulkCreate(paper_accountsData, { transaction });
// For each item created, replace relation files
return paper_accounts;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const paper_accounts = await db.paper_accounts.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.base_currency !== undefined) updatePayload.base_currency = data.base_currency;
if (data.starting_cash !== undefined) updatePayload.starting_cash = data.starting_cash;
if (data.cash_balance !== undefined) updatePayload.cash_balance = data.cash_balance;
if (data.buying_power !== undefined) updatePayload.buying_power = data.buying_power;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
if (data.opened_at !== undefined) updatePayload.opened_at = data.opened_at;
updatePayload.updatedById = currentUser.id;
await paper_accounts.update(updatePayload, {transaction});
if (data.user !== undefined) {
await paper_accounts.setUser(
data.user,
{ transaction }
);
}
return paper_accounts;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const paper_accounts = await db.paper_accounts.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of paper_accounts) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of paper_accounts) {
await record.destroy({transaction});
}
});
return paper_accounts;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const paper_accounts = await db.paper_accounts.findByPk(id, options);
await paper_accounts.update({
deletedBy: currentUser.id
}, {
transaction,
});
await paper_accounts.destroy({
transaction
});
return paper_accounts;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const paper_accounts = await db.paper_accounts.findOne(
{ where },
{ transaction },
);
if (!paper_accounts) {
return paper_accounts;
}
const output = paper_accounts.get({plain: true});
output.paper_orders_paper_account = await paper_accounts.getPaper_orders_paper_account({
transaction
});
output.paper_positions_paper_account = await paper_accounts.getPaper_positions_paper_account({
transaction
});
output.portfolio_snapshots_paper_account = await paper_accounts.getPortfolio_snapshots_paper_account({
transaction
});
output.user = await paper_accounts.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.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'paper_accounts',
'name',
filter.name,
),
};
}
if (filter.starting_cashRange) {
const [start, end] = filter.starting_cashRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
starting_cash: {
...where.starting_cash,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
starting_cash: {
...where.starting_cash,
[Op.lte]: end,
},
};
}
}
if (filter.cash_balanceRange) {
const [start, end] = filter.cash_balanceRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
cash_balance: {
...where.cash_balance,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
cash_balance: {
...where.cash_balance,
[Op.lte]: end,
},
};
}
}
if (filter.buying_powerRange) {
const [start, end] = filter.buying_powerRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
buying_power: {
...where.buying_power,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
buying_power: {
...where.buying_power,
[Op.lte]: end,
},
};
}
}
if (filter.opened_atRange) {
const [start, end] = filter.opened_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
opened_at: {
...where.opened_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
opened_at: {
...where.opened_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.base_currency) {
where = {
...where,
base_currency: filter.base_currency,
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.paper_accounts.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'paper_accounts',
'name',
query,
),
],
};
}
const records = await db.paper_accounts.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,757 @@
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 Paper_ordersDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const paper_orders = await db.paper_orders.create(
{
id: data.id || undefined,
placed_at: data.placed_at
||
null
,
filled_at: data.filled_at
||
null
,
side: data.side
||
null
,
order_type: data.order_type
||
null
,
quantity: data.quantity
||
null
,
limit_price: data.limit_price
||
null
,
stop_price: data.stop_price
||
null
,
filled_quantity: data.filled_quantity
||
null
,
average_fill_price: data.average_fill_price
||
null
,
status: data.status
||
null
,
rejection_reason: data.rejection_reason
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await paper_orders.setPaper_account( data.paper_account || null, {
transaction,
});
await paper_orders.setMarket_symbol( data.market_symbol || null, {
transaction,
});
return paper_orders;
}
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 paper_ordersData = data.map((item, index) => ({
id: item.id || undefined,
placed_at: item.placed_at
||
null
,
filled_at: item.filled_at
||
null
,
side: item.side
||
null
,
order_type: item.order_type
||
null
,
quantity: item.quantity
||
null
,
limit_price: item.limit_price
||
null
,
stop_price: item.stop_price
||
null
,
filled_quantity: item.filled_quantity
||
null
,
average_fill_price: item.average_fill_price
||
null
,
status: item.status
||
null
,
rejection_reason: item.rejection_reason
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const paper_orders = await db.paper_orders.bulkCreate(paper_ordersData, { transaction });
// For each item created, replace relation files
return paper_orders;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const paper_orders = await db.paper_orders.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.placed_at !== undefined) updatePayload.placed_at = data.placed_at;
if (data.filled_at !== undefined) updatePayload.filled_at = data.filled_at;
if (data.side !== undefined) updatePayload.side = data.side;
if (data.order_type !== undefined) updatePayload.order_type = data.order_type;
if (data.quantity !== undefined) updatePayload.quantity = data.quantity;
if (data.limit_price !== undefined) updatePayload.limit_price = data.limit_price;
if (data.stop_price !== undefined) updatePayload.stop_price = data.stop_price;
if (data.filled_quantity !== undefined) updatePayload.filled_quantity = data.filled_quantity;
if (data.average_fill_price !== undefined) updatePayload.average_fill_price = data.average_fill_price;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.rejection_reason !== undefined) updatePayload.rejection_reason = data.rejection_reason;
updatePayload.updatedById = currentUser.id;
await paper_orders.update(updatePayload, {transaction});
if (data.paper_account !== undefined) {
await paper_orders.setPaper_account(
data.paper_account,
{ transaction }
);
}
if (data.market_symbol !== undefined) {
await paper_orders.setMarket_symbol(
data.market_symbol,
{ transaction }
);
}
return paper_orders;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const paper_orders = await db.paper_orders.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of paper_orders) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of paper_orders) {
await record.destroy({transaction});
}
});
return paper_orders;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const paper_orders = await db.paper_orders.findByPk(id, options);
await paper_orders.update({
deletedBy: currentUser.id
}, {
transaction,
});
await paper_orders.destroy({
transaction
});
return paper_orders;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const paper_orders = await db.paper_orders.findOne(
{ where },
{ transaction },
);
if (!paper_orders) {
return paper_orders;
}
const output = paper_orders.get({plain: true});
output.paper_trades_paper_order = await paper_orders.getPaper_trades_paper_order({
transaction
});
output.paper_account = await paper_orders.getPaper_account({
transaction
});
output.market_symbol = await paper_orders.getMarket_symbol({
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.paper_accounts,
as: 'paper_account',
where: filter.paper_account ? {
[Op.or]: [
{ id: { [Op.in]: filter.paper_account.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.paper_account.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.market_symbols,
as: 'market_symbol',
where: filter.market_symbol ? {
[Op.or]: [
{ id: { [Op.in]: filter.market_symbol.split('|').map(term => Utils.uuid(term)) } },
{
symbol: {
[Op.or]: filter.market_symbol.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.rejection_reason) {
where = {
...where,
[Op.and]: Utils.ilike(
'paper_orders',
'rejection_reason',
filter.rejection_reason,
),
};
}
if (filter.placed_atRange) {
const [start, end] = filter.placed_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
placed_at: {
...where.placed_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
placed_at: {
...where.placed_at,
[Op.lte]: end,
},
};
}
}
if (filter.filled_atRange) {
const [start, end] = filter.filled_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
filled_at: {
...where.filled_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
filled_at: {
...where.filled_at,
[Op.lte]: end,
},
};
}
}
if (filter.quantityRange) {
const [start, end] = filter.quantityRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
quantity: {
...where.quantity,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
quantity: {
...where.quantity,
[Op.lte]: end,
},
};
}
}
if (filter.limit_priceRange) {
const [start, end] = filter.limit_priceRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
limit_price: {
...where.limit_price,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
limit_price: {
...where.limit_price,
[Op.lte]: end,
},
};
}
}
if (filter.stop_priceRange) {
const [start, end] = filter.stop_priceRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
stop_price: {
...where.stop_price,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
stop_price: {
...where.stop_price,
[Op.lte]: end,
},
};
}
}
if (filter.filled_quantityRange) {
const [start, end] = filter.filled_quantityRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
filled_quantity: {
...where.filled_quantity,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
filled_quantity: {
...where.filled_quantity,
[Op.lte]: end,
},
};
}
}
if (filter.average_fill_priceRange) {
const [start, end] = filter.average_fill_priceRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
average_fill_price: {
...where.average_fill_price,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
average_fill_price: {
...where.average_fill_price,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.side) {
where = {
...where,
side: filter.side,
};
}
if (filter.order_type) {
where = {
...where,
order_type: filter.order_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.paper_orders.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(
'paper_orders',
'status',
query,
),
],
};
}
const records = await db.paper_orders.findAll({
attributes: [ 'id', 'status' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['status', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.status,
}));
}
};

View File

@ -0,0 +1,669 @@
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 Paper_positionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const paper_positions = await db.paper_positions.create(
{
id: data.id || undefined,
quantity: data.quantity
||
null
,
average_cost: data.average_cost
||
null
,
market_value: data.market_value
||
null
,
unrealized_pl: data.unrealized_pl
||
null
,
realized_pl: data.realized_pl
||
null
,
day_pl: data.day_pl
||
null
,
last_priced_at: data.last_priced_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await paper_positions.setPaper_account( data.paper_account || null, {
transaction,
});
await paper_positions.setMarket_symbol( data.market_symbol || null, {
transaction,
});
return paper_positions;
}
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 paper_positionsData = data.map((item, index) => ({
id: item.id || undefined,
quantity: item.quantity
||
null
,
average_cost: item.average_cost
||
null
,
market_value: item.market_value
||
null
,
unrealized_pl: item.unrealized_pl
||
null
,
realized_pl: item.realized_pl
||
null
,
day_pl: item.day_pl
||
null
,
last_priced_at: item.last_priced_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const paper_positions = await db.paper_positions.bulkCreate(paper_positionsData, { transaction });
// For each item created, replace relation files
return paper_positions;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const paper_positions = await db.paper_positions.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.quantity !== undefined) updatePayload.quantity = data.quantity;
if (data.average_cost !== undefined) updatePayload.average_cost = data.average_cost;
if (data.market_value !== undefined) updatePayload.market_value = data.market_value;
if (data.unrealized_pl !== undefined) updatePayload.unrealized_pl = data.unrealized_pl;
if (data.realized_pl !== undefined) updatePayload.realized_pl = data.realized_pl;
if (data.day_pl !== undefined) updatePayload.day_pl = data.day_pl;
if (data.last_priced_at !== undefined) updatePayload.last_priced_at = data.last_priced_at;
updatePayload.updatedById = currentUser.id;
await paper_positions.update(updatePayload, {transaction});
if (data.paper_account !== undefined) {
await paper_positions.setPaper_account(
data.paper_account,
{ transaction }
);
}
if (data.market_symbol !== undefined) {
await paper_positions.setMarket_symbol(
data.market_symbol,
{ transaction }
);
}
return paper_positions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const paper_positions = await db.paper_positions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of paper_positions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of paper_positions) {
await record.destroy({transaction});
}
});
return paper_positions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const paper_positions = await db.paper_positions.findByPk(id, options);
await paper_positions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await paper_positions.destroy({
transaction
});
return paper_positions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const paper_positions = await db.paper_positions.findOne(
{ where },
{ transaction },
);
if (!paper_positions) {
return paper_positions;
}
const output = paper_positions.get({plain: true});
output.paper_account = await paper_positions.getPaper_account({
transaction
});
output.market_symbol = await paper_positions.getMarket_symbol({
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.paper_accounts,
as: 'paper_account',
where: filter.paper_account ? {
[Op.or]: [
{ id: { [Op.in]: filter.paper_account.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.paper_account.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.market_symbols,
as: 'market_symbol',
where: filter.market_symbol ? {
[Op.or]: [
{ id: { [Op.in]: filter.market_symbol.split('|').map(term => Utils.uuid(term)) } },
{
symbol: {
[Op.or]: filter.market_symbol.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.quantityRange) {
const [start, end] = filter.quantityRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
quantity: {
...where.quantity,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
quantity: {
...where.quantity,
[Op.lte]: end,
},
};
}
}
if (filter.average_costRange) {
const [start, end] = filter.average_costRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
average_cost: {
...where.average_cost,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
average_cost: {
...where.average_cost,
[Op.lte]: end,
},
};
}
}
if (filter.market_valueRange) {
const [start, end] = filter.market_valueRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
market_value: {
...where.market_value,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
market_value: {
...where.market_value,
[Op.lte]: end,
},
};
}
}
if (filter.unrealized_plRange) {
const [start, end] = filter.unrealized_plRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
unrealized_pl: {
...where.unrealized_pl,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
unrealized_pl: {
...where.unrealized_pl,
[Op.lte]: end,
},
};
}
}
if (filter.realized_plRange) {
const [start, end] = filter.realized_plRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
realized_pl: {
...where.realized_pl,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
realized_pl: {
...where.realized_pl,
[Op.lte]: end,
},
};
}
}
if (filter.day_plRange) {
const [start, end] = filter.day_plRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
day_pl: {
...where.day_pl,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
day_pl: {
...where.day_pl,
[Op.lte]: end,
},
};
}
}
if (filter.last_priced_atRange) {
const [start, end] = filter.last_priced_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
last_priced_at: {
...where.last_priced_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
last_priced_at: {
...where.last_priced_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.paper_positions.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(
'paper_positions',
'last_priced_at',
query,
),
],
};
}
const records = await db.paper_positions.findAll({
attributes: [ 'id', 'last_priced_at' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['last_priced_at', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.last_priced_at,
}));
}
};

View File

@ -0,0 +1,545 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Paper_tradesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const paper_trades = await db.paper_trades.create(
{
id: data.id || undefined,
executed_at: data.executed_at
||
null
,
quantity: data.quantity
||
null
,
price: data.price
||
null
,
fees: data.fees
||
null
,
venue: data.venue
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await paper_trades.setPaper_order( data.paper_order || null, {
transaction,
});
return paper_trades;
}
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 paper_tradesData = data.map((item, index) => ({
id: item.id || undefined,
executed_at: item.executed_at
||
null
,
quantity: item.quantity
||
null
,
price: item.price
||
null
,
fees: item.fees
||
null
,
venue: item.venue
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const paper_trades = await db.paper_trades.bulkCreate(paper_tradesData, { transaction });
// For each item created, replace relation files
return paper_trades;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const paper_trades = await db.paper_trades.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.executed_at !== undefined) updatePayload.executed_at = data.executed_at;
if (data.quantity !== undefined) updatePayload.quantity = data.quantity;
if (data.price !== undefined) updatePayload.price = data.price;
if (data.fees !== undefined) updatePayload.fees = data.fees;
if (data.venue !== undefined) updatePayload.venue = data.venue;
updatePayload.updatedById = currentUser.id;
await paper_trades.update(updatePayload, {transaction});
if (data.paper_order !== undefined) {
await paper_trades.setPaper_order(
data.paper_order,
{ transaction }
);
}
return paper_trades;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const paper_trades = await db.paper_trades.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of paper_trades) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of paper_trades) {
await record.destroy({transaction});
}
});
return paper_trades;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const paper_trades = await db.paper_trades.findByPk(id, options);
await paper_trades.update({
deletedBy: currentUser.id
}, {
transaction,
});
await paper_trades.destroy({
transaction
});
return paper_trades;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const paper_trades = await db.paper_trades.findOne(
{ where },
{ transaction },
);
if (!paper_trades) {
return paper_trades;
}
const output = paper_trades.get({plain: true});
output.paper_order = await paper_trades.getPaper_order({
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.paper_orders,
as: 'paper_order',
where: filter.paper_order ? {
[Op.or]: [
{ id: { [Op.in]: filter.paper_order.split('|').map(term => Utils.uuid(term)) } },
{
status: {
[Op.or]: filter.paper_order.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.venue) {
where = {
...where,
[Op.and]: Utils.ilike(
'paper_trades',
'venue',
filter.venue,
),
};
}
if (filter.executed_atRange) {
const [start, end] = filter.executed_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
executed_at: {
...where.executed_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
executed_at: {
...where.executed_at,
[Op.lte]: end,
},
};
}
}
if (filter.quantityRange) {
const [start, end] = filter.quantityRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
quantity: {
...where.quantity,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
quantity: {
...where.quantity,
[Op.lte]: end,
},
};
}
}
if (filter.priceRange) {
const [start, end] = filter.priceRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
price: {
...where.price,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
price: {
...where.price,
[Op.lte]: end,
},
};
}
}
if (filter.feesRange) {
const [start, end] = filter.feesRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
fees: {
...where.fees,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
fees: {
...where.fees,
[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.paper_trades.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(
'paper_trades',
'venue',
query,
),
],
};
}
const records = await db.paper_trades.findAll({
attributes: [ 'id', 'venue' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['venue', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.venue,
}));
}
};

View File

@ -0,0 +1,360 @@
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,632 @@
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 Portfolio_snapshotsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const portfolio_snapshots = await db.portfolio_snapshots.create(
{
id: data.id || undefined,
snapshotted_at: data.snapshotted_at
||
null
,
total_value: data.total_value
||
null
,
cash_value: data.cash_value
||
null
,
positions_value: data.positions_value
||
null
,
day_pl: data.day_pl
||
null
,
all_time_pl: data.all_time_pl
||
null
,
day_pl_percent: data.day_pl_percent
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await portfolio_snapshots.setPaper_account( data.paper_account || null, {
transaction,
});
return portfolio_snapshots;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const portfolio_snapshotsData = data.map((item, index) => ({
id: item.id || undefined,
snapshotted_at: item.snapshotted_at
||
null
,
total_value: item.total_value
||
null
,
cash_value: item.cash_value
||
null
,
positions_value: item.positions_value
||
null
,
day_pl: item.day_pl
||
null
,
all_time_pl: item.all_time_pl
||
null
,
day_pl_percent: item.day_pl_percent
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const portfolio_snapshots = await db.portfolio_snapshots.bulkCreate(portfolio_snapshotsData, { transaction });
// For each item created, replace relation files
return portfolio_snapshots;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const portfolio_snapshots = await db.portfolio_snapshots.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.snapshotted_at !== undefined) updatePayload.snapshotted_at = data.snapshotted_at;
if (data.total_value !== undefined) updatePayload.total_value = data.total_value;
if (data.cash_value !== undefined) updatePayload.cash_value = data.cash_value;
if (data.positions_value !== undefined) updatePayload.positions_value = data.positions_value;
if (data.day_pl !== undefined) updatePayload.day_pl = data.day_pl;
if (data.all_time_pl !== undefined) updatePayload.all_time_pl = data.all_time_pl;
if (data.day_pl_percent !== undefined) updatePayload.day_pl_percent = data.day_pl_percent;
updatePayload.updatedById = currentUser.id;
await portfolio_snapshots.update(updatePayload, {transaction});
if (data.paper_account !== undefined) {
await portfolio_snapshots.setPaper_account(
data.paper_account,
{ transaction }
);
}
return portfolio_snapshots;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const portfolio_snapshots = await db.portfolio_snapshots.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of portfolio_snapshots) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of portfolio_snapshots) {
await record.destroy({transaction});
}
});
return portfolio_snapshots;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const portfolio_snapshots = await db.portfolio_snapshots.findByPk(id, options);
await portfolio_snapshots.update({
deletedBy: currentUser.id
}, {
transaction,
});
await portfolio_snapshots.destroy({
transaction
});
return portfolio_snapshots;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const portfolio_snapshots = await db.portfolio_snapshots.findOne(
{ where },
{ transaction },
);
if (!portfolio_snapshots) {
return portfolio_snapshots;
}
const output = portfolio_snapshots.get({plain: true});
output.paper_account = await portfolio_snapshots.getPaper_account({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.paper_accounts,
as: 'paper_account',
where: filter.paper_account ? {
[Op.or]: [
{ id: { [Op.in]: filter.paper_account.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.paper_account.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.snapshotted_atRange) {
const [start, end] = filter.snapshotted_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
snapshotted_at: {
...where.snapshotted_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
snapshotted_at: {
...where.snapshotted_at,
[Op.lte]: end,
},
};
}
}
if (filter.total_valueRange) {
const [start, end] = filter.total_valueRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
total_value: {
...where.total_value,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
total_value: {
...where.total_value,
[Op.lte]: end,
},
};
}
}
if (filter.cash_valueRange) {
const [start, end] = filter.cash_valueRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
cash_value: {
...where.cash_value,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
cash_value: {
...where.cash_value,
[Op.lte]: end,
},
};
}
}
if (filter.positions_valueRange) {
const [start, end] = filter.positions_valueRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
positions_value: {
...where.positions_value,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
positions_value: {
...where.positions_value,
[Op.lte]: end,
},
};
}
}
if (filter.day_plRange) {
const [start, end] = filter.day_plRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
day_pl: {
...where.day_pl,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
day_pl: {
...where.day_pl,
[Op.lte]: end,
},
};
}
}
if (filter.all_time_plRange) {
const [start, end] = filter.all_time_plRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
all_time_pl: {
...where.all_time_pl,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
all_time_pl: {
...where.all_time_pl,
[Op.lte]: end,
},
};
}
}
if (filter.day_pl_percentRange) {
const [start, end] = filter.day_pl_percentRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
day_pl_percent: {
...where.day_pl_percent,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
day_pl_percent: {
...where.day_pl_percent,
[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.portfolio_snapshots.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'portfolio_snapshots',
'snapshotted_at',
query,
),
],
};
}
const records = await db.portfolio_snapshots.findAll({
attributes: [ 'id', 'snapshotted_at' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['snapshotted_at', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.snapshotted_at,
}));
}
};

View File

@ -0,0 +1,750 @@
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 Price_quotesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const price_quotes = await db.price_quotes.create(
{
id: data.id || undefined,
quoted_at: data.quoted_at
||
null
,
price: data.price
||
null
,
open: data.open
||
null
,
high: data.high
||
null
,
low: data.low
||
null
,
previous_close: data.previous_close
||
null
,
change_amount: data.change_amount
||
null
,
change_percent: data.change_percent
||
null
,
volume: data.volume
||
null
,
timeframe: data.timeframe
||
null
,
source: data.source
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await price_quotes.setMarket_symbol( data.market_symbol || null, {
transaction,
});
return price_quotes;
}
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 price_quotesData = data.map((item, index) => ({
id: item.id || undefined,
quoted_at: item.quoted_at
||
null
,
price: item.price
||
null
,
open: item.open
||
null
,
high: item.high
||
null
,
low: item.low
||
null
,
previous_close: item.previous_close
||
null
,
change_amount: item.change_amount
||
null
,
change_percent: item.change_percent
||
null
,
volume: item.volume
||
null
,
timeframe: item.timeframe
||
null
,
source: item.source
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const price_quotes = await db.price_quotes.bulkCreate(price_quotesData, { transaction });
// For each item created, replace relation files
return price_quotes;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const price_quotes = await db.price_quotes.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.quoted_at !== undefined) updatePayload.quoted_at = data.quoted_at;
if (data.price !== undefined) updatePayload.price = data.price;
if (data.open !== undefined) updatePayload.open = data.open;
if (data.high !== undefined) updatePayload.high = data.high;
if (data.low !== undefined) updatePayload.low = data.low;
if (data.previous_close !== undefined) updatePayload.previous_close = data.previous_close;
if (data.change_amount !== undefined) updatePayload.change_amount = data.change_amount;
if (data.change_percent !== undefined) updatePayload.change_percent = data.change_percent;
if (data.volume !== undefined) updatePayload.volume = data.volume;
if (data.timeframe !== undefined) updatePayload.timeframe = data.timeframe;
if (data.source !== undefined) updatePayload.source = data.source;
updatePayload.updatedById = currentUser.id;
await price_quotes.update(updatePayload, {transaction});
if (data.market_symbol !== undefined) {
await price_quotes.setMarket_symbol(
data.market_symbol,
{ transaction }
);
}
return price_quotes;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const price_quotes = await db.price_quotes.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of price_quotes) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of price_quotes) {
await record.destroy({transaction});
}
});
return price_quotes;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const price_quotes = await db.price_quotes.findByPk(id, options);
await price_quotes.update({
deletedBy: currentUser.id
}, {
transaction,
});
await price_quotes.destroy({
transaction
});
return price_quotes;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const price_quotes = await db.price_quotes.findOne(
{ where },
{ transaction },
);
if (!price_quotes) {
return price_quotes;
}
const output = price_quotes.get({plain: true});
output.market_symbol = await price_quotes.getMarket_symbol({
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.market_symbols,
as: 'market_symbol',
where: filter.market_symbol ? {
[Op.or]: [
{ id: { [Op.in]: filter.market_symbol.split('|').map(term => Utils.uuid(term)) } },
{
symbol: {
[Op.or]: filter.market_symbol.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.source) {
where = {
...where,
[Op.and]: Utils.ilike(
'price_quotes',
'source',
filter.source,
),
};
}
if (filter.quoted_atRange) {
const [start, end] = filter.quoted_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
quoted_at: {
...where.quoted_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
quoted_at: {
...where.quoted_at,
[Op.lte]: end,
},
};
}
}
if (filter.priceRange) {
const [start, end] = filter.priceRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
price: {
...where.price,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
price: {
...where.price,
[Op.lte]: end,
},
};
}
}
if (filter.openRange) {
const [start, end] = filter.openRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
open: {
...where.open,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
open: {
...where.open,
[Op.lte]: end,
},
};
}
}
if (filter.highRange) {
const [start, end] = filter.highRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
high: {
...where.high,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
high: {
...where.high,
[Op.lte]: end,
},
};
}
}
if (filter.lowRange) {
const [start, end] = filter.lowRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
low: {
...where.low,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
low: {
...where.low,
[Op.lte]: end,
},
};
}
}
if (filter.previous_closeRange) {
const [start, end] = filter.previous_closeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
previous_close: {
...where.previous_close,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
previous_close: {
...where.previous_close,
[Op.lte]: end,
},
};
}
}
if (filter.change_amountRange) {
const [start, end] = filter.change_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
change_amount: {
...where.change_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
change_amount: {
...where.change_amount,
[Op.lte]: end,
},
};
}
}
if (filter.change_percentRange) {
const [start, end] = filter.change_percentRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
change_percent: {
...where.change_percent,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
change_percent: {
...where.change_percent,
[Op.lte]: end,
},
};
}
}
if (filter.volumeRange) {
const [start, end] = filter.volumeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
volume: {
...where.volume,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
volume: {
...where.volume,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.timeframe) {
where = {
...where,
timeframe: filter.timeframe,
};
}
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.price_quotes.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(
'price_quotes',
'source',
query,
),
],
};
}
const records = await db.price_quotes.findAll({
attributes: [ 'id', 'source' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['source', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.source,
}));
}
};

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

@ -0,0 +1,430 @@
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,800 @@
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 Screener_filtersDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const screener_filters = await db.screener_filters.create(
{
id: data.id || undefined,
name: data.name
||
null
,
asset_class: data.asset_class
||
null
,
sector: data.sector
||
null
,
market_cap_min: data.market_cap_min
||
null
,
market_cap_max: data.market_cap_max
||
null
,
pe_min: data.pe_min
||
null
,
pe_max: data.pe_max
||
null
,
price_min: data.price_min
||
null
,
price_max: data.price_max
||
null
,
volume_min: data.volume_min
||
null
,
performance_52w_min: data.performance_52w_min
||
null
,
performance_52w_max: data.performance_52w_max
||
null
,
is_pinned: data.is_pinned
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await screener_filters.setUser( data.user || null, {
transaction,
});
return screener_filters;
}
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 screener_filtersData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
asset_class: item.asset_class
||
null
,
sector: item.sector
||
null
,
market_cap_min: item.market_cap_min
||
null
,
market_cap_max: item.market_cap_max
||
null
,
pe_min: item.pe_min
||
null
,
pe_max: item.pe_max
||
null
,
price_min: item.price_min
||
null
,
price_max: item.price_max
||
null
,
volume_min: item.volume_min
||
null
,
performance_52w_min: item.performance_52w_min
||
null
,
performance_52w_max: item.performance_52w_max
||
null
,
is_pinned: item.is_pinned
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const screener_filters = await db.screener_filters.bulkCreate(screener_filtersData, { transaction });
// For each item created, replace relation files
return screener_filters;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const screener_filters = await db.screener_filters.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.asset_class !== undefined) updatePayload.asset_class = data.asset_class;
if (data.sector !== undefined) updatePayload.sector = data.sector;
if (data.market_cap_min !== undefined) updatePayload.market_cap_min = data.market_cap_min;
if (data.market_cap_max !== undefined) updatePayload.market_cap_max = data.market_cap_max;
if (data.pe_min !== undefined) updatePayload.pe_min = data.pe_min;
if (data.pe_max !== undefined) updatePayload.pe_max = data.pe_max;
if (data.price_min !== undefined) updatePayload.price_min = data.price_min;
if (data.price_max !== undefined) updatePayload.price_max = data.price_max;
if (data.volume_min !== undefined) updatePayload.volume_min = data.volume_min;
if (data.performance_52w_min !== undefined) updatePayload.performance_52w_min = data.performance_52w_min;
if (data.performance_52w_max !== undefined) updatePayload.performance_52w_max = data.performance_52w_max;
if (data.is_pinned !== undefined) updatePayload.is_pinned = data.is_pinned;
updatePayload.updatedById = currentUser.id;
await screener_filters.update(updatePayload, {transaction});
if (data.user !== undefined) {
await screener_filters.setUser(
data.user,
{ transaction }
);
}
return screener_filters;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const screener_filters = await db.screener_filters.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of screener_filters) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of screener_filters) {
await record.destroy({transaction});
}
});
return screener_filters;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const screener_filters = await db.screener_filters.findByPk(id, options);
await screener_filters.update({
deletedBy: currentUser.id
}, {
transaction,
});
await screener_filters.destroy({
transaction
});
return screener_filters;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const screener_filters = await db.screener_filters.findOne(
{ where },
{ transaction },
);
if (!screener_filters) {
return screener_filters;
}
const output = screener_filters.get({plain: true});
output.screener_runs_screener_filter = await screener_filters.getScreener_runs_screener_filter({
transaction
});
output.user = await screener_filters.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.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'screener_filters',
'name',
filter.name,
),
};
}
if (filter.sector) {
where = {
...where,
[Op.and]: Utils.ilike(
'screener_filters',
'sector',
filter.sector,
),
};
}
if (filter.market_cap_minRange) {
const [start, end] = filter.market_cap_minRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
market_cap_min: {
...where.market_cap_min,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
market_cap_min: {
...where.market_cap_min,
[Op.lte]: end,
},
};
}
}
if (filter.market_cap_maxRange) {
const [start, end] = filter.market_cap_maxRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
market_cap_max: {
...where.market_cap_max,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
market_cap_max: {
...where.market_cap_max,
[Op.lte]: end,
},
};
}
}
if (filter.pe_minRange) {
const [start, end] = filter.pe_minRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
pe_min: {
...where.pe_min,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
pe_min: {
...where.pe_min,
[Op.lte]: end,
},
};
}
}
if (filter.pe_maxRange) {
const [start, end] = filter.pe_maxRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
pe_max: {
...where.pe_max,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
pe_max: {
...where.pe_max,
[Op.lte]: end,
},
};
}
}
if (filter.price_minRange) {
const [start, end] = filter.price_minRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
price_min: {
...where.price_min,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
price_min: {
...where.price_min,
[Op.lte]: end,
},
};
}
}
if (filter.price_maxRange) {
const [start, end] = filter.price_maxRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
price_max: {
...where.price_max,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
price_max: {
...where.price_max,
[Op.lte]: end,
},
};
}
}
if (filter.volume_minRange) {
const [start, end] = filter.volume_minRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
volume_min: {
...where.volume_min,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
volume_min: {
...where.volume_min,
[Op.lte]: end,
},
};
}
}
if (filter.performance_52w_minRange) {
const [start, end] = filter.performance_52w_minRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
performance_52w_min: {
...where.performance_52w_min,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
performance_52w_min: {
...where.performance_52w_min,
[Op.lte]: end,
},
};
}
}
if (filter.performance_52w_maxRange) {
const [start, end] = filter.performance_52w_maxRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
performance_52w_max: {
...where.performance_52w_max,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
performance_52w_max: {
...where.performance_52w_max,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.asset_class) {
where = {
...where,
asset_class: filter.asset_class,
};
}
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.screener_filters.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(
'screener_filters',
'name',
query,
),
],
};
}
const records = await db.screener_filters.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,619 @@
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 Screener_resultsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const screener_results = await db.screener_results.create(
{
id: data.id || undefined,
last_price: data.last_price
||
null
,
market_cap: data.market_cap
||
null
,
pe_ratio: data.pe_ratio
||
null
,
volume: data.volume
||
null
,
performance_52w: data.performance_52w
||
null
,
sector: data.sector
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await screener_results.setScreener_run( data.screener_run || null, {
transaction,
});
await screener_results.setMarket_symbol( data.market_symbol || null, {
transaction,
});
return screener_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 screener_resultsData = data.map((item, index) => ({
id: item.id || undefined,
last_price: item.last_price
||
null
,
market_cap: item.market_cap
||
null
,
pe_ratio: item.pe_ratio
||
null
,
volume: item.volume
||
null
,
performance_52w: item.performance_52w
||
null
,
sector: item.sector
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const screener_results = await db.screener_results.bulkCreate(screener_resultsData, { transaction });
// For each item created, replace relation files
return screener_results;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const screener_results = await db.screener_results.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.last_price !== undefined) updatePayload.last_price = data.last_price;
if (data.market_cap !== undefined) updatePayload.market_cap = data.market_cap;
if (data.pe_ratio !== undefined) updatePayload.pe_ratio = data.pe_ratio;
if (data.volume !== undefined) updatePayload.volume = data.volume;
if (data.performance_52w !== undefined) updatePayload.performance_52w = data.performance_52w;
if (data.sector !== undefined) updatePayload.sector = data.sector;
updatePayload.updatedById = currentUser.id;
await screener_results.update(updatePayload, {transaction});
if (data.screener_run !== undefined) {
await screener_results.setScreener_run(
data.screener_run,
{ transaction }
);
}
if (data.market_symbol !== undefined) {
await screener_results.setMarket_symbol(
data.market_symbol,
{ transaction }
);
}
return screener_results;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const screener_results = await db.screener_results.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of screener_results) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of screener_results) {
await record.destroy({transaction});
}
});
return screener_results;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const screener_results = await db.screener_results.findByPk(id, options);
await screener_results.update({
deletedBy: currentUser.id
}, {
transaction,
});
await screener_results.destroy({
transaction
});
return screener_results;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const screener_results = await db.screener_results.findOne(
{ where },
{ transaction },
);
if (!screener_results) {
return screener_results;
}
const output = screener_results.get({plain: true});
output.screener_run = await screener_results.getScreener_run({
transaction
});
output.market_symbol = await screener_results.getMarket_symbol({
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.screener_runs,
as: 'screener_run',
where: filter.screener_run ? {
[Op.or]: [
{ id: { [Op.in]: filter.screener_run.split('|').map(term => Utils.uuid(term)) } },
{
status: {
[Op.or]: filter.screener_run.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.market_symbols,
as: 'market_symbol',
where: filter.market_symbol ? {
[Op.or]: [
{ id: { [Op.in]: filter.market_symbol.split('|').map(term => Utils.uuid(term)) } },
{
symbol: {
[Op.or]: filter.market_symbol.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.sector) {
where = {
...where,
[Op.and]: Utils.ilike(
'screener_results',
'sector',
filter.sector,
),
};
}
if (filter.last_priceRange) {
const [start, end] = filter.last_priceRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
last_price: {
...where.last_price,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
last_price: {
...where.last_price,
[Op.lte]: end,
},
};
}
}
if (filter.market_capRange) {
const [start, end] = filter.market_capRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
market_cap: {
...where.market_cap,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
market_cap: {
...where.market_cap,
[Op.lte]: end,
},
};
}
}
if (filter.pe_ratioRange) {
const [start, end] = filter.pe_ratioRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
pe_ratio: {
...where.pe_ratio,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
pe_ratio: {
...where.pe_ratio,
[Op.lte]: end,
},
};
}
}
if (filter.volumeRange) {
const [start, end] = filter.volumeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
volume: {
...where.volume,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
volume: {
...where.volume,
[Op.lte]: end,
},
};
}
}
if (filter.performance_52wRange) {
const [start, end] = filter.performance_52wRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
performance_52w: {
...where.performance_52w,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
performance_52w: {
...where.performance_52w,
[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.screener_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(
'screener_results',
'sector',
query,
),
],
};
}
const records = await db.screener_results.findAll({
attributes: [ 'id', 'sector' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['sector', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.sector,
}));
}
};

View File

@ -0,0 +1,495 @@
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 Screener_runsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const screener_runs = await db.screener_runs.create(
{
id: data.id || undefined,
run_at: data.run_at
||
null
,
result_count: data.result_count
||
null
,
status: data.status
||
null
,
error_message: data.error_message
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await screener_runs.setScreener_filter( data.screener_filter || null, {
transaction,
});
return screener_runs;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const screener_runsData = data.map((item, index) => ({
id: item.id || undefined,
run_at: item.run_at
||
null
,
result_count: item.result_count
||
null
,
status: item.status
||
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 screener_runs = await db.screener_runs.bulkCreate(screener_runsData, { transaction });
// For each item created, replace relation files
return screener_runs;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const screener_runs = await db.screener_runs.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.run_at !== undefined) updatePayload.run_at = data.run_at;
if (data.result_count !== undefined) updatePayload.result_count = data.result_count;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.error_message !== undefined) updatePayload.error_message = data.error_message;
updatePayload.updatedById = currentUser.id;
await screener_runs.update(updatePayload, {transaction});
if (data.screener_filter !== undefined) {
await screener_runs.setScreener_filter(
data.screener_filter,
{ transaction }
);
}
return screener_runs;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const screener_runs = await db.screener_runs.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of screener_runs) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of screener_runs) {
await record.destroy({transaction});
}
});
return screener_runs;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const screener_runs = await db.screener_runs.findByPk(id, options);
await screener_runs.update({
deletedBy: currentUser.id
}, {
transaction,
});
await screener_runs.destroy({
transaction
});
return screener_runs;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const screener_runs = await db.screener_runs.findOne(
{ where },
{ transaction },
);
if (!screener_runs) {
return screener_runs;
}
const output = screener_runs.get({plain: true});
output.screener_results_screener_run = await screener_runs.getScreener_results_screener_run({
transaction
});
output.screener_filter = await screener_runs.getScreener_filter({
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.screener_filters,
as: 'screener_filter',
where: filter.screener_filter ? {
[Op.or]: [
{ id: { [Op.in]: filter.screener_filter.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.screener_filter.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.error_message) {
where = {
...where,
[Op.and]: Utils.ilike(
'screener_runs',
'error_message',
filter.error_message,
),
};
}
if (filter.run_atRange) {
const [start, end] = filter.run_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
run_at: {
...where.run_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
run_at: {
...where.run_at,
[Op.lte]: end,
},
};
}
}
if (filter.result_countRange) {
const [start, end] = filter.result_countRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
result_count: {
...where.result_count,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
result_count: {
...where.result_count,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.screener_runs.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'screener_runs',
'status',
query,
),
],
};
}
const records = await db.screener_runs.findAll({
attributes: [ 'id', 'status' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['status', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.status,
}));
}
};

View File

@ -0,0 +1,693 @@
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 Symbol_fundamentalsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const symbol_fundamentals = await db.symbol_fundamentals.create(
{
id: data.id || undefined,
pe_ratio: data.pe_ratio
||
null
,
eps: data.eps
||
null
,
market_cap: data.market_cap
||
null
,
revenue: data.revenue
||
null
,
dividend_yield: data.dividend_yield
||
null
,
beta: data.beta
||
null
,
shares_outstanding: data.shares_outstanding
||
null
,
as_of_at: data.as_of_at
||
null
,
source: data.source
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await symbol_fundamentals.setMarket_symbol( data.market_symbol || null, {
transaction,
});
return symbol_fundamentals;
}
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 symbol_fundamentalsData = data.map((item, index) => ({
id: item.id || undefined,
pe_ratio: item.pe_ratio
||
null
,
eps: item.eps
||
null
,
market_cap: item.market_cap
||
null
,
revenue: item.revenue
||
null
,
dividend_yield: item.dividend_yield
||
null
,
beta: item.beta
||
null
,
shares_outstanding: item.shares_outstanding
||
null
,
as_of_at: item.as_of_at
||
null
,
source: item.source
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const symbol_fundamentals = await db.symbol_fundamentals.bulkCreate(symbol_fundamentalsData, { transaction });
// For each item created, replace relation files
return symbol_fundamentals;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const symbol_fundamentals = await db.symbol_fundamentals.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.pe_ratio !== undefined) updatePayload.pe_ratio = data.pe_ratio;
if (data.eps !== undefined) updatePayload.eps = data.eps;
if (data.market_cap !== undefined) updatePayload.market_cap = data.market_cap;
if (data.revenue !== undefined) updatePayload.revenue = data.revenue;
if (data.dividend_yield !== undefined) updatePayload.dividend_yield = data.dividend_yield;
if (data.beta !== undefined) updatePayload.beta = data.beta;
if (data.shares_outstanding !== undefined) updatePayload.shares_outstanding = data.shares_outstanding;
if (data.as_of_at !== undefined) updatePayload.as_of_at = data.as_of_at;
if (data.source !== undefined) updatePayload.source = data.source;
updatePayload.updatedById = currentUser.id;
await symbol_fundamentals.update(updatePayload, {transaction});
if (data.market_symbol !== undefined) {
await symbol_fundamentals.setMarket_symbol(
data.market_symbol,
{ transaction }
);
}
return symbol_fundamentals;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const symbol_fundamentals = await db.symbol_fundamentals.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of symbol_fundamentals) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of symbol_fundamentals) {
await record.destroy({transaction});
}
});
return symbol_fundamentals;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const symbol_fundamentals = await db.symbol_fundamentals.findByPk(id, options);
await symbol_fundamentals.update({
deletedBy: currentUser.id
}, {
transaction,
});
await symbol_fundamentals.destroy({
transaction
});
return symbol_fundamentals;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const symbol_fundamentals = await db.symbol_fundamentals.findOne(
{ where },
{ transaction },
);
if (!symbol_fundamentals) {
return symbol_fundamentals;
}
const output = symbol_fundamentals.get({plain: true});
output.market_symbol = await symbol_fundamentals.getMarket_symbol({
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.market_symbols,
as: 'market_symbol',
where: filter.market_symbol ? {
[Op.or]: [
{ id: { [Op.in]: filter.market_symbol.split('|').map(term => Utils.uuid(term)) } },
{
symbol: {
[Op.or]: filter.market_symbol.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.source) {
where = {
...where,
[Op.and]: Utils.ilike(
'symbol_fundamentals',
'source',
filter.source,
),
};
}
if (filter.pe_ratioRange) {
const [start, end] = filter.pe_ratioRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
pe_ratio: {
...where.pe_ratio,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
pe_ratio: {
...where.pe_ratio,
[Op.lte]: end,
},
};
}
}
if (filter.epsRange) {
const [start, end] = filter.epsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
eps: {
...where.eps,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
eps: {
...where.eps,
[Op.lte]: end,
},
};
}
}
if (filter.market_capRange) {
const [start, end] = filter.market_capRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
market_cap: {
...where.market_cap,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
market_cap: {
...where.market_cap,
[Op.lte]: end,
},
};
}
}
if (filter.revenueRange) {
const [start, end] = filter.revenueRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
revenue: {
...where.revenue,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
revenue: {
...where.revenue,
[Op.lte]: end,
},
};
}
}
if (filter.dividend_yieldRange) {
const [start, end] = filter.dividend_yieldRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
dividend_yield: {
...where.dividend_yield,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
dividend_yield: {
...where.dividend_yield,
[Op.lte]: end,
},
};
}
}
if (filter.betaRange) {
const [start, end] = filter.betaRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
beta: {
...where.beta,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
beta: {
...where.beta,
[Op.lte]: end,
},
};
}
}
if (filter.shares_outstandingRange) {
const [start, end] = filter.shares_outstandingRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
shares_outstanding: {
...where.shares_outstanding,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
shares_outstanding: {
...where.shares_outstanding,
[Op.lte]: end,
},
};
}
}
if (filter.as_of_atRange) {
const [start, end] = filter.as_of_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
as_of_at: {
...where.as_of_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
as_of_at: {
...where.as_of_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.symbol_fundamentals.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(
'symbol_fundamentals',
'source',
query,
),
],
};
}
const records = await db.symbol_fundamentals.findAll({
attributes: [ 'id', 'source' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['source', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.source,
}));
}
};

View File

@ -0,0 +1,733 @@
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 Technical_indicatorsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const technical_indicators = await db.technical_indicators.create(
{
id: data.id || undefined,
calculated_at: data.calculated_at
||
null
,
indicator_type: data.indicator_type
||
null
,
timeframe: data.timeframe
||
null
,
period: data.period
||
null
,
value: data.value
||
null
,
signal: data.signal
||
null
,
histogram: data.histogram
||
null
,
upper_band: data.upper_band
||
null
,
middle_band: data.middle_band
||
null
,
lower_band: data.lower_band
||
null
,
source: data.source
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await technical_indicators.setMarket_symbol( data.market_symbol || null, {
transaction,
});
return technical_indicators;
}
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 technical_indicatorsData = data.map((item, index) => ({
id: item.id || undefined,
calculated_at: item.calculated_at
||
null
,
indicator_type: item.indicator_type
||
null
,
timeframe: item.timeframe
||
null
,
period: item.period
||
null
,
value: item.value
||
null
,
signal: item.signal
||
null
,
histogram: item.histogram
||
null
,
upper_band: item.upper_band
||
null
,
middle_band: item.middle_band
||
null
,
lower_band: item.lower_band
||
null
,
source: item.source
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const technical_indicators = await db.technical_indicators.bulkCreate(technical_indicatorsData, { transaction });
// For each item created, replace relation files
return technical_indicators;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const technical_indicators = await db.technical_indicators.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.calculated_at !== undefined) updatePayload.calculated_at = data.calculated_at;
if (data.indicator_type !== undefined) updatePayload.indicator_type = data.indicator_type;
if (data.timeframe !== undefined) updatePayload.timeframe = data.timeframe;
if (data.period !== undefined) updatePayload.period = data.period;
if (data.value !== undefined) updatePayload.value = data.value;
if (data.signal !== undefined) updatePayload.signal = data.signal;
if (data.histogram !== undefined) updatePayload.histogram = data.histogram;
if (data.upper_band !== undefined) updatePayload.upper_band = data.upper_band;
if (data.middle_band !== undefined) updatePayload.middle_band = data.middle_band;
if (data.lower_band !== undefined) updatePayload.lower_band = data.lower_band;
if (data.source !== undefined) updatePayload.source = data.source;
updatePayload.updatedById = currentUser.id;
await technical_indicators.update(updatePayload, {transaction});
if (data.market_symbol !== undefined) {
await technical_indicators.setMarket_symbol(
data.market_symbol,
{ transaction }
);
}
return technical_indicators;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const technical_indicators = await db.technical_indicators.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of technical_indicators) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of technical_indicators) {
await record.destroy({transaction});
}
});
return technical_indicators;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const technical_indicators = await db.technical_indicators.findByPk(id, options);
await technical_indicators.update({
deletedBy: currentUser.id
}, {
transaction,
});
await technical_indicators.destroy({
transaction
});
return technical_indicators;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const technical_indicators = await db.technical_indicators.findOne(
{ where },
{ transaction },
);
if (!technical_indicators) {
return technical_indicators;
}
const output = technical_indicators.get({plain: true});
output.market_symbol = await technical_indicators.getMarket_symbol({
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.market_symbols,
as: 'market_symbol',
where: filter.market_symbol ? {
[Op.or]: [
{ id: { [Op.in]: filter.market_symbol.split('|').map(term => Utils.uuid(term)) } },
{
symbol: {
[Op.or]: filter.market_symbol.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.source) {
where = {
...where,
[Op.and]: Utils.ilike(
'technical_indicators',
'source',
filter.source,
),
};
}
if (filter.calculated_atRange) {
const [start, end] = filter.calculated_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
calculated_at: {
...where.calculated_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
calculated_at: {
...where.calculated_at,
[Op.lte]: end,
},
};
}
}
if (filter.periodRange) {
const [start, end] = filter.periodRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
period: {
...where.period,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
period: {
...where.period,
[Op.lte]: end,
},
};
}
}
if (filter.valueRange) {
const [start, end] = filter.valueRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
value: {
...where.value,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
value: {
...where.value,
[Op.lte]: end,
},
};
}
}
if (filter.signalRange) {
const [start, end] = filter.signalRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
signal: {
...where.signal,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
signal: {
...where.signal,
[Op.lte]: end,
},
};
}
}
if (filter.histogramRange) {
const [start, end] = filter.histogramRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
histogram: {
...where.histogram,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
histogram: {
...where.histogram,
[Op.lte]: end,
},
};
}
}
if (filter.upper_bandRange) {
const [start, end] = filter.upper_bandRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
upper_band: {
...where.upper_band,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
upper_band: {
...where.upper_band,
[Op.lte]: end,
},
};
}
}
if (filter.middle_bandRange) {
const [start, end] = filter.middle_bandRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
middle_band: {
...where.middle_band,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
middle_band: {
...where.middle_band,
[Op.lte]: end,
},
};
}
}
if (filter.lower_bandRange) {
const [start, end] = filter.lower_bandRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
lower_band: {
...where.lower_band,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
lower_band: {
...where.lower_band,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.indicator_type) {
where = {
...where,
indicator_type: filter.indicator_type,
};
}
if (filter.timeframe) {
where = {
...where,
timeframe: filter.timeframe,
};
}
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.technical_indicators.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(
'technical_indicators',
'source',
query,
),
],
};
}
const records = await db.technical_indicators.findAll({
attributes: [ 'id', 'source' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['source', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.source,
}));
}
};

View File

@ -0,0 +1,476 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class User_tooltipsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const user_tooltips = await db.user_tooltips.create(
{
id: data.id || undefined,
tooltip_key: data.tooltip_key
||
null
,
dismissed: data.dismissed
||
false
,
dismissed_at: data.dismissed_at
||
null
,
experience_mode: data.experience_mode
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await user_tooltips.setUser( data.user || null, {
transaction,
});
return user_tooltips;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const user_tooltipsData = data.map((item, index) => ({
id: item.id || undefined,
tooltip_key: item.tooltip_key
||
null
,
dismissed: item.dismissed
||
false
,
dismissed_at: item.dismissed_at
||
null
,
experience_mode: item.experience_mode
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const user_tooltips = await db.user_tooltips.bulkCreate(user_tooltipsData, { transaction });
// For each item created, replace relation files
return user_tooltips;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const user_tooltips = await db.user_tooltips.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.tooltip_key !== undefined) updatePayload.tooltip_key = data.tooltip_key;
if (data.dismissed !== undefined) updatePayload.dismissed = data.dismissed;
if (data.dismissed_at !== undefined) updatePayload.dismissed_at = data.dismissed_at;
if (data.experience_mode !== undefined) updatePayload.experience_mode = data.experience_mode;
updatePayload.updatedById = currentUser.id;
await user_tooltips.update(updatePayload, {transaction});
if (data.user !== undefined) {
await user_tooltips.setUser(
data.user,
{ transaction }
);
}
return user_tooltips;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const user_tooltips = await db.user_tooltips.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of user_tooltips) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of user_tooltips) {
await record.destroy({transaction});
}
});
return user_tooltips;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const user_tooltips = await db.user_tooltips.findByPk(id, options);
await user_tooltips.update({
deletedBy: currentUser.id
}, {
transaction,
});
await user_tooltips.destroy({
transaction
});
return user_tooltips;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const user_tooltips = await db.user_tooltips.findOne(
{ where },
{ transaction },
);
if (!user_tooltips) {
return user_tooltips;
}
const output = user_tooltips.get({plain: true});
output.user = await user_tooltips.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.tooltip_key) {
where = {
...where,
[Op.and]: Utils.ilike(
'user_tooltips',
'tooltip_key',
filter.tooltip_key,
),
};
}
if (filter.dismissed_atRange) {
const [start, end] = filter.dismissed_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
dismissed_at: {
...where.dismissed_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
dismissed_at: {
...where.dismissed_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.dismissed) {
where = {
...where,
dismissed: filter.dismissed,
};
}
if (filter.experience_mode) {
where = {
...where,
experience_mode: filter.experience_mode,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.user_tooltips.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'user_tooltips',
'tooltip_key',
query,
),
],
};
}
const records = await db.user_tooltips.findAll({
attributes: [ 'id', 'tooltip_key' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['tooltip_key', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.tooltip_key,
}));
}
};

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

@ -0,0 +1,986 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const bcrypt = require('bcrypt');
const config = require('../../config');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class UsersDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const users = await db.users.create(
{
id: data.data.id || undefined,
firstName: data.data.firstName
||
null
,
lastName: data.data.lastName
||
null
,
phoneNumber: data.data.phoneNumber
||
null
,
email: data.data.email
||
null
,
disabled: data.data.disabled
||
false
,
password: data.data.password
||
null
,
emailVerified: data.data.emailVerified
||
true
,
emailVerificationToken: data.data.emailVerificationToken
||
null
,
emailVerificationTokenExpiresAt: data.data.emailVerificationTokenExpiresAt
||
null
,
passwordResetToken: data.data.passwordResetToken
||
null
,
passwordResetTokenExpiresAt: data.data.passwordResetTokenExpiresAt
||
null
,
provider: data.data.provider
||
null
,
importHash: data.data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
if (!data.data.app_role) {
const role = await db.roles.findOne({
where: { name: 'User' },
});
if (role) {
await users.setApp_role(role, {
transaction,
});
}
}else{
await users.setApp_role(data.data.app_role || null, {
transaction,
});
}
await users.setCustom_permissions(data.data.custom_permissions || [], {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.users.getTableName(),
belongsToColumn: 'avatar',
belongsToId: users.id,
},
data.data.avatar,
options,
);
return users;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const usersData = data.map((item, index) => ({
id: item.id || undefined,
firstName: item.firstName
||
null
,
lastName: item.lastName
||
null
,
phoneNumber: item.phoneNumber
||
null
,
email: item.email
||
null
,
disabled: item.disabled
||
false
,
password: item.password
||
null
,
emailVerified: item.emailVerified
||
false
,
emailVerificationToken: item.emailVerificationToken
||
null
,
emailVerificationTokenExpiresAt: item.emailVerificationTokenExpiresAt
||
null
,
passwordResetToken: item.passwordResetToken
||
null
,
passwordResetTokenExpiresAt: item.passwordResetTokenExpiresAt
||
null
,
provider: item.provider
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const users = await db.users.bulkCreate(usersData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < users.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.users.getTableName(),
belongsToColumn: 'avatar',
belongsToId: users[i].id,
},
data[i].avatar,
options,
);
}
return users;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const users = await db.users.findByPk(id, {}, {transaction});
if (!data?.app_role) {
data.app_role = users?.app_role?.id;
}
if (!data?.custom_permissions) {
data.custom_permissions = users?.custom_permissions?.map(item => item.id);
}
if (data.password) {
data.password = bcrypt.hashSync(
data.password,
config.bcrypt.saltRounds,
);
} else {
data.password = users.password;
}
const updatePayload = {};
if (data.firstName !== undefined) updatePayload.firstName = data.firstName;
if (data.lastName !== undefined) updatePayload.lastName = data.lastName;
if (data.phoneNumber !== undefined) updatePayload.phoneNumber = data.phoneNumber;
if (data.email !== undefined) updatePayload.email = data.email;
if (data.disabled !== undefined) updatePayload.disabled = data.disabled;
if (data.password !== undefined) updatePayload.password = data.password;
if (data.emailVerified !== undefined) updatePayload.emailVerified = data.emailVerified;
else updatePayload.emailVerified = true;
if (data.emailVerificationToken !== undefined) updatePayload.emailVerificationToken = data.emailVerificationToken;
if (data.emailVerificationTokenExpiresAt !== undefined) updatePayload.emailVerificationTokenExpiresAt = data.emailVerificationTokenExpiresAt;
if (data.passwordResetToken !== undefined) updatePayload.passwordResetToken = data.passwordResetToken;
if (data.passwordResetTokenExpiresAt !== undefined) updatePayload.passwordResetTokenExpiresAt = data.passwordResetTokenExpiresAt;
if (data.provider !== undefined) updatePayload.provider = data.provider;
updatePayload.updatedById = currentUser.id;
await users.update(updatePayload, {transaction});
if (data.app_role !== undefined) {
await users.setApp_role(
data.app_role,
{ transaction }
);
}
if (data.custom_permissions !== undefined) {
await users.setCustom_permissions(data.custom_permissions, { transaction });
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.users.getTableName(),
belongsToColumn: 'avatar',
belongsToId: users.id,
},
data.avatar,
options,
);
return users;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const users = await db.users.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of users) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of users) {
await record.destroy({transaction});
}
});
return users;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const users = await db.users.findByPk(id, options);
await users.update({
deletedBy: currentUser.id
}, {
transaction,
});
await users.destroy({
transaction
});
return users;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const users = await db.users.findOne(
{ where },
{ transaction },
);
if (!users) {
return users;
}
const output = users.get({plain: true});
output.article_bookmarks_user = await users.getArticle_bookmarks_user({
transaction
});
output.watchlists_user = await users.getWatchlists_user({
transaction
});
output.paper_accounts_user = await users.getPaper_accounts_user({
transaction
});
output.screener_filters_user = await users.getScreener_filters_user({
transaction
});
output.ai_chat_sessions_user = await users.getAi_chat_sessions_user({
transaction
});
output.user_tooltips_user = await users.getUser_tooltips_user({
transaction
});
output.audit_events_user = await users.getAudit_events_user({
transaction
});
output.avatar = await users.getAvatar({
transaction
});
output.app_role = await users.getApp_role({
transaction
});
if (output.app_role) {
output.app_role_permissions = await output.app_role.getPermissions({
transaction,
});
}
output.custom_permissions = await users.getCustom_permissions({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.roles,
as: 'app_role',
where: filter.app_role ? {
[Op.or]: [
{ id: { [Op.in]: filter.app_role.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.app_role.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.permissions,
as: 'custom_permissions',
required: false,
},
{
model: db.file,
as: 'avatar',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.firstName) {
where = {
...where,
[Op.and]: Utils.ilike(
'users',
'firstName',
filter.firstName,
),
};
}
if (filter.lastName) {
where = {
...where,
[Op.and]: Utils.ilike(
'users',
'lastName',
filter.lastName,
),
};
}
if (filter.phoneNumber) {
where = {
...where,
[Op.and]: Utils.ilike(
'users',
'phoneNumber',
filter.phoneNumber,
),
};
}
if (filter.email) {
where = {
...where,
[Op.and]: Utils.ilike(
'users',
'email',
filter.email,
),
};
}
if (filter.password) {
where = {
...where,
[Op.and]: Utils.ilike(
'users',
'password',
filter.password,
),
};
}
if (filter.emailVerificationToken) {
where = {
...where,
[Op.and]: Utils.ilike(
'users',
'emailVerificationToken',
filter.emailVerificationToken,
),
};
}
if (filter.passwordResetToken) {
where = {
...where,
[Op.and]: Utils.ilike(
'users',
'passwordResetToken',
filter.passwordResetToken,
),
};
}
if (filter.provider) {
where = {
...where,
[Op.and]: Utils.ilike(
'users',
'provider',
filter.provider,
),
};
}
if (filter.emailVerificationTokenExpiresAtRange) {
const [start, end] = filter.emailVerificationTokenExpiresAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
emailVerificationTokenExpiresAt: {
...where.emailVerificationTokenExpiresAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
emailVerificationTokenExpiresAt: {
...where.emailVerificationTokenExpiresAt,
[Op.lte]: end,
},
};
}
}
if (filter.passwordResetTokenExpiresAtRange) {
const [start, end] = filter.passwordResetTokenExpiresAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
passwordResetTokenExpiresAt: {
...where.passwordResetTokenExpiresAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
passwordResetTokenExpiresAt: {
...where.passwordResetTokenExpiresAt,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.disabled) {
where = {
...where,
disabled: filter.disabled,
};
}
if (filter.emailVerified) {
where = {
...where,
emailVerified: filter.emailVerified,
};
}
if (filter.custom_permissions) {
const searchTerms = filter.custom_permissions.split('|');
include = [
{
model: db.permissions,
as: 'custom_permissions_filter',
required: searchTerms.length > 0,
where: searchTerms.length > 0 ? {
[Op.or]: [
{ id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
}
}
]
} : undefined
},
...include,
]
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.users.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'users',
'firstName',
query,
),
],
};
}
const records = await db.users.findAll({
attributes: [ 'id', 'firstName' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['firstName', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.firstName,
}));
}
static async createFromAuth(data, options) {
const transaction = (options && options.transaction) || undefined;
const users = await db.users.create(
{
email: data.email,
firstName: data.firstName,
authenticationUid: data.authenticationUid,
password: data.password,
},
{ transaction },
);
const app_role = await db.roles.findOne({
where: { name: config.roles?.user || "User" },
});
if (app_role?.id) {
await users.setApp_role(app_role?.id || null, {
transaction,
});
}
await users.update(
{
authenticationUid: users.id,
},
{ transaction },
);
delete users.password;
return users;
}
static async updatePassword(id, password, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const users = await db.users.findByPk(id, {
transaction,
});
await users.update(
{
password,
authenticationUid: id,
updatedById: currentUser.id,
},
{ transaction },
);
return users;
}
static async generateEmailVerificationToken(email, options) {
return this._generateToken(['emailVerificationToken', 'emailVerificationTokenExpiresAt'], email, options);
}
static async generatePasswordResetToken(email, options) {
return this._generateToken(['passwordResetToken', 'passwordResetTokenExpiresAt'], email, options);
}
static async findByPasswordResetToken(token, options) {
const transaction = (options && options.transaction) || undefined;
return db.users.findOne(
{
where: {
passwordResetToken: token,
passwordResetTokenExpiresAt: {
[db.Sequelize.Op.gt]: Date.now(),
},
},
},
{ transaction },
);
}
static async findByEmailVerificationToken(
token,
options,
) {
const transaction = (options && options.transaction) || undefined;
return db.users.findOne(
{
where: {
emailVerificationToken: token,
emailVerificationTokenExpiresAt: {
[db.Sequelize.Op.gt]: Date.now(),
},
},
},
{ transaction },
);
}
static async markEmailVerified(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const users = await db.users.findByPk(id, {
transaction,
});
await users.update(
{
emailVerified: true,
updatedById: currentUser.id,
},
{ transaction },
);
return true;
}
static async _generateToken(keyNames, email, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const users = await db.users.findOne(
{
where: { email: email.toLowerCase() },
},
{
transaction,
},
);
const token = crypto
.randomBytes(20)
.toString('hex');
const tokenExpiresAt = Date.now() + 360000;
if(users){
await users.update(
{
[keyNames[0]]: token,
[keyNames[1]]: tokenExpiresAt,
updatedById: currentUser.id,
},
{transaction},
);
}
return token;
}
};

View File

@ -0,0 +1,567 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Watchlist_itemsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const watchlist_items = await db.watchlist_items.create(
{
id: data.id || undefined,
added_at: data.added_at
||
null
,
alert_above_price: data.alert_above_price
||
null
,
alert_below_price: data.alert_below_price
||
null
,
alerts_enabled: data.alerts_enabled
||
false
,
note: data.note
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await watchlist_items.setWatchlist( data.watchlist || null, {
transaction,
});
await watchlist_items.setMarket_symbol( data.market_symbol || null, {
transaction,
});
return watchlist_items;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const watchlist_itemsData = data.map((item, index) => ({
id: item.id || undefined,
added_at: item.added_at
||
null
,
alert_above_price: item.alert_above_price
||
null
,
alert_below_price: item.alert_below_price
||
null
,
alerts_enabled: item.alerts_enabled
||
false
,
note: item.note
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const watchlist_items = await db.watchlist_items.bulkCreate(watchlist_itemsData, { transaction });
// For each item created, replace relation files
return watchlist_items;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const watchlist_items = await db.watchlist_items.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.added_at !== undefined) updatePayload.added_at = data.added_at;
if (data.alert_above_price !== undefined) updatePayload.alert_above_price = data.alert_above_price;
if (data.alert_below_price !== undefined) updatePayload.alert_below_price = data.alert_below_price;
if (data.alerts_enabled !== undefined) updatePayload.alerts_enabled = data.alerts_enabled;
if (data.note !== undefined) updatePayload.note = data.note;
updatePayload.updatedById = currentUser.id;
await watchlist_items.update(updatePayload, {transaction});
if (data.watchlist !== undefined) {
await watchlist_items.setWatchlist(
data.watchlist,
{ transaction }
);
}
if (data.market_symbol !== undefined) {
await watchlist_items.setMarket_symbol(
data.market_symbol,
{ transaction }
);
}
return watchlist_items;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const watchlist_items = await db.watchlist_items.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of watchlist_items) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of watchlist_items) {
await record.destroy({transaction});
}
});
return watchlist_items;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const watchlist_items = await db.watchlist_items.findByPk(id, options);
await watchlist_items.update({
deletedBy: currentUser.id
}, {
transaction,
});
await watchlist_items.destroy({
transaction
});
return watchlist_items;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const watchlist_items = await db.watchlist_items.findOne(
{ where },
{ transaction },
);
if (!watchlist_items) {
return watchlist_items;
}
const output = watchlist_items.get({plain: true});
output.watchlist = await watchlist_items.getWatchlist({
transaction
});
output.market_symbol = await watchlist_items.getMarket_symbol({
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.watchlists,
as: 'watchlist',
where: filter.watchlist ? {
[Op.or]: [
{ id: { [Op.in]: filter.watchlist.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.watchlist.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.market_symbols,
as: 'market_symbol',
where: filter.market_symbol ? {
[Op.or]: [
{ id: { [Op.in]: filter.market_symbol.split('|').map(term => Utils.uuid(term)) } },
{
symbol: {
[Op.or]: filter.market_symbol.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.note) {
where = {
...where,
[Op.and]: Utils.ilike(
'watchlist_items',
'note',
filter.note,
),
};
}
if (filter.added_atRange) {
const [start, end] = filter.added_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
added_at: {
...where.added_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
added_at: {
...where.added_at,
[Op.lte]: end,
},
};
}
}
if (filter.alert_above_priceRange) {
const [start, end] = filter.alert_above_priceRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
alert_above_price: {
...where.alert_above_price,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
alert_above_price: {
...where.alert_above_price,
[Op.lte]: end,
},
};
}
}
if (filter.alert_below_priceRange) {
const [start, end] = filter.alert_below_priceRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
alert_below_price: {
...where.alert_below_price,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
alert_below_price: {
...where.alert_below_price,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.alerts_enabled) {
where = {
...where,
alerts_enabled: filter.alerts_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.watchlist_items.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'watchlist_items',
'note',
query,
),
],
};
}
const records = await db.watchlist_items.findAll({
attributes: [ 'id', 'note' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['note', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.note,
}));
}
};

View File

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

View File

@ -0,0 +1,33 @@
module.exports = {
production: {
dialect: 'postgres',
username: process.env.DB_USER,
password: process.env.DB_PASS,
database: process.env.DB_NAME,
host: process.env.DB_HOST,
port: process.env.DB_PORT,
logging: console.log,
seederStorage: 'sequelize',
},
development: {
username: 'postgres',
dialect: 'postgres',
password: '',
database: 'db_app_preview',
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,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 ai_chat_sessions = sequelize.define(
'ai_chat_sessions',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
title: {
type: DataTypes.TEXT,
},
mode: {
type: DataTypes.ENUM,
values: [
"beginner",
"pro"
],
},
status: {
type: DataTypes.ENUM,
values: [
"active",
"archived"
],
},
started_at: {
type: DataTypes.DATE,
},
last_message_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
ai_chat_sessions.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.ai_chat_sessions.hasMany(db.ai_messages, {
as: 'ai_messages_ai_chat_session',
foreignKey: {
name: 'ai_chat_sessionId',
},
constraints: false,
});
//end loop
db.ai_chat_sessions.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.ai_chat_sessions.belongsTo(db.users, {
as: 'createdBy',
});
db.ai_chat_sessions.belongsTo(db.users, {
as: 'updatedBy',
});
};
return ai_chat_sessions;
};

View File

@ -0,0 +1,230 @@
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_messages = sequelize.define(
'ai_messages',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
sent_at: {
type: DataTypes.DATE,
},
sender: {
type: DataTypes.ENUM,
values: [
"user",
"assistant",
"system"
],
},
content: {
type: DataTypes.TEXT,
},
intent: {
type: DataTypes.ENUM,
values: [
"analyze_symbol",
"compare_symbols",
"news_summary",
"portfolio_question",
"education",
"other"
],
},
risk_level: {
type: DataTypes.ENUM,
values: [
"low",
"medium",
"high",
"unknown"
],
},
recommendation: {
type: DataTypes.ENUM,
values: [
"buy",
"hold",
"sell",
"unknown"
],
},
confidence: {
type: DataTypes.DECIMAL,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
ai_messages.associate = (db) => {
db.ai_messages.belongsToMany(db.market_symbols, {
as: 'cited_symbols',
foreignKey: {
name: 'ai_messages_cited_symbolsId',
},
constraints: false,
through: 'ai_messagesCited_symbolsMarket_symbols',
});
db.ai_messages.belongsToMany(db.market_symbols, {
as: 'cited_symbols_filter',
foreignKey: {
name: 'ai_messages_cited_symbolsId',
},
constraints: false,
through: 'ai_messagesCited_symbolsMarket_symbols',
});
/// 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_messages.belongsTo(db.ai_chat_sessions, {
as: 'ai_chat_session',
foreignKey: {
name: 'ai_chat_sessionId',
},
constraints: false,
});
db.ai_messages.belongsTo(db.users, {
as: 'createdBy',
});
db.ai_messages.belongsTo(db.users, {
as: 'updatedBy',
});
};
return ai_messages;
};

View File

@ -0,0 +1,160 @@
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 analyst_ratings = sequelize.define(
'analyst_ratings',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
firm_name: {
type: DataTypes.TEXT,
},
rating: {
type: DataTypes.ENUM,
values: [
"strong_buy",
"buy",
"hold",
"sell",
"strong_sell"
],
},
price_target: {
type: DataTypes.DECIMAL,
},
rating_at: {
type: DataTypes.DATE,
},
summary: {
type: DataTypes.TEXT,
},
source_url: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
analyst_ratings.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.analyst_ratings.belongsTo(db.market_symbols, {
as: 'market_symbol',
foreignKey: {
name: 'market_symbolId',
},
constraints: false,
});
db.analyst_ratings.belongsTo(db.users, {
as: 'createdBy',
});
db.analyst_ratings.belongsTo(db.users, {
as: 'updatedBy',
});
};
return analyst_ratings;
};

View File

@ -0,0 +1,171 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const api_providers = sequelize.define(
'api_providers',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
base_url: {
type: DataTypes.TEXT,
},
provider_type: {
type: DataTypes.ENUM,
values: [
"market_data",
"news",
"ai"
],
},
enabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
last_health_check_at: {
type: DataTypes.DATE,
},
health_status: {
type: DataTypes.ENUM,
values: [
"unknown",
"ok",
"degraded",
"down"
],
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
api_providers.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.api_providers.belongsTo(db.users, {
as: 'createdBy',
});
db.api_providers.belongsTo(db.users, {
as: 'updatedBy',
});
};
return api_providers;
};

View File

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

View File

@ -0,0 +1,199 @@
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,
},
occurred_at: {
type: DataTypes.DATE,
},
event_type: {
type: DataTypes.ENUM,
values: [
"login",
"logout",
"mode_switch",
"theme_switch",
"order_placed",
"order_filled",
"order_canceled",
"watchlist_created",
"watchlist_updated",
"bookmark_added",
"bookmark_removed",
"admin_change",
"api_error"
],
},
entity_name: {
type: DataTypes.TEXT,
},
entity_reference: {
type: DataTypes.TEXT,
},
metadata_json: {
type: DataTypes.TEXT,
},
severity: {
type: DataTypes.ENUM,
values: [
"info",
"warning",
"error",
"critical"
],
},
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: 'user',
foreignKey: {
name: 'userId',
},
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,163 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const earnings_reports = sequelize.define(
'earnings_reports',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
period_end_at: {
type: DataTypes.DATE,
},
reported_at: {
type: DataTypes.DATE,
},
reported_eps: {
type: DataTypes.DECIMAL,
},
estimated_eps: {
type: DataTypes.DECIMAL,
},
surprise: {
type: DataTypes.DECIMAL,
},
surprise_percent: {
type: DataTypes.DECIMAL,
},
reported_revenue: {
type: DataTypes.DECIMAL,
},
estimated_revenue: {
type: DataTypes.DECIMAL,
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
earnings_reports.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.earnings_reports.belongsTo(db.market_symbols, {
as: 'market_symbol',
foreignKey: {
name: 'market_symbolId',
},
constraints: false,
});
db.earnings_reports.belongsTo(db.users, {
as: 'createdBy',
});
db.earnings_reports.belongsTo(db.users, {
as: 'updatedBy',
});
};
return earnings_reports;
};

View File

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

View File

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

View File

@ -0,0 +1,138 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const ir_announcements = sequelize.define(
'ir_announcements',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
title: {
type: DataTypes.TEXT,
},
announced_at: {
type: DataTypes.DATE,
},
body: {
type: DataTypes.TEXT,
},
source_url: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
ir_announcements.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.ir_announcements.belongsTo(db.ir_companies, {
as: 'ir_company',
foreignKey: {
name: 'ir_companyId',
},
constraints: false,
});
db.ir_announcements.hasMany(db.file, {
as: 'attachments',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.ir_announcements.getTableName(),
belongsToColumn: 'attachments',
},
});
db.ir_announcements.belongsTo(db.users, {
as: 'createdBy',
});
db.ir_announcements.belongsTo(db.users, {
as: 'updatedBy',
});
};
return ir_announcements;
};

View File

@ -0,0 +1,175 @@
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 ir_companies = sequelize.define(
'ir_companies',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
website: {
type: DataTypes.TEXT,
},
description: {
type: DataTypes.TEXT,
},
hq_location: {
type: DataTypes.TEXT,
},
last_updated_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
ir_companies.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.ir_companies.hasMany(db.ir_management_members, {
as: 'ir_management_members_ir_company',
foreignKey: {
name: 'ir_companyId',
},
constraints: false,
});
db.ir_companies.hasMany(db.ir_filings, {
as: 'ir_filings_ir_company',
foreignKey: {
name: 'ir_companyId',
},
constraints: false,
});
db.ir_companies.hasMany(db.ir_dividends, {
as: 'ir_dividends_ir_company',
foreignKey: {
name: 'ir_companyId',
},
constraints: false,
});
db.ir_companies.hasMany(db.ir_announcements, {
as: 'ir_announcements_ir_company',
foreignKey: {
name: 'ir_companyId',
},
constraints: false,
});
db.ir_companies.hasMany(db.ir_financial_statement_summaries, {
as: 'ir_financial_statement_summaries_ir_company',
foreignKey: {
name: 'ir_companyId',
},
constraints: false,
});
//end loop
db.ir_companies.belongsTo(db.market_symbols, {
as: 'market_symbol',
foreignKey: {
name: 'market_symbolId',
},
constraints: false,
});
db.ir_companies.belongsTo(db.users, {
as: 'createdBy',
});
db.ir_companies.belongsTo(db.users, {
as: 'updatedBy',
});
};
return ir_companies;
};

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 ir_dividends = sequelize.define(
'ir_dividends',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
declaration_at: {
type: DataTypes.DATE,
},
ex_dividend_at: {
type: DataTypes.DATE,
},
record_at: {
type: DataTypes.DATE,
},
payable_at: {
type: DataTypes.DATE,
},
amount: {
type: DataTypes.DECIMAL,
},
currency: {
type: DataTypes.ENUM,
values: [
"USD",
"EUR",
"GBP",
"JPY"
],
},
frequency: {
type: DataTypes.ENUM,
values: [
"one_time",
"quarterly",
"semi_annual",
"annual",
"monthly"
],
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
ir_dividends.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.ir_dividends.belongsTo(db.ir_companies, {
as: 'ir_company',
foreignKey: {
name: 'ir_companyId',
},
constraints: false,
});
db.ir_dividends.belongsTo(db.users, {
as: 'createdBy',
});
db.ir_dividends.belongsTo(db.users, {
as: 'updatedBy',
});
};
return ir_dividends;
};

View File

@ -0,0 +1,166 @@
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 ir_filings = sequelize.define(
'ir_filings',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
filing_type: {
type: DataTypes.ENUM,
values: [
"10k",
"10q",
"8k",
"s1",
"def14a",
"other"
],
},
title: {
type: DataTypes.TEXT,
},
filed_at: {
type: DataTypes.DATE,
},
sec_url: {
type: DataTypes.TEXT,
},
summary: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
ir_filings.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.ir_filings.belongsTo(db.ir_companies, {
as: 'ir_company',
foreignKey: {
name: 'ir_companyId',
},
constraints: false,
});
db.ir_filings.hasMany(db.file, {
as: 'attachments',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.ir_filings.getTableName(),
belongsToColumn: 'attachments',
},
});
db.ir_filings.belongsTo(db.users, {
as: 'createdBy',
});
db.ir_filings.belongsTo(db.users, {
as: 'updatedBy',
});
};
return ir_filings;
};

View File

@ -0,0 +1,184 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const ir_financial_statement_summaries = sequelize.define(
'ir_financial_statement_summaries',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
statement_type: {
type: DataTypes.ENUM,
values: [
"income_statement",
"balance_sheet",
"cash_flow"
],
},
period_type: {
type: DataTypes.ENUM,
values: [
"annual",
"quarterly"
],
},
period_end_at: {
type: DataTypes.DATE,
},
total_revenue: {
type: DataTypes.DECIMAL,
},
net_income: {
type: DataTypes.DECIMAL,
},
total_assets: {
type: DataTypes.DECIMAL,
},
total_liabilities: {
type: DataTypes.DECIMAL,
},
free_cash_flow: {
type: DataTypes.DECIMAL,
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
ir_financial_statement_summaries.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.ir_financial_statement_summaries.belongsTo(db.ir_companies, {
as: 'ir_company',
foreignKey: {
name: 'ir_companyId',
},
constraints: false,
});
db.ir_financial_statement_summaries.belongsTo(db.users, {
as: 'createdBy',
});
db.ir_financial_statement_summaries.belongsTo(db.users, {
as: 'updatedBy',
});
};
return ir_financial_statement_summaries;
};

View File

@ -0,0 +1,138 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const ir_management_members = sequelize.define(
'ir_management_members',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
full_name: {
type: DataTypes.TEXT,
},
title: {
type: DataTypes.TEXT,
},
bio: {
type: DataTypes.TEXT,
},
display_order: {
type: DataTypes.INTEGER,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
ir_management_members.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.ir_management_members.belongsTo(db.ir_companies, {
as: 'ir_company',
foreignKey: {
name: 'ir_companyId',
},
constraints: false,
});
db.ir_management_members.hasMany(db.file, {
as: 'profile_images',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.ir_management_members.getTableName(),
belongsToColumn: 'profile_images',
},
});
db.ir_management_members.belongsTo(db.users, {
as: 'createdBy',
});
db.ir_management_members.belongsTo(db.users, {
as: 'updatedBy',
});
};
return ir_management_members;
};

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 learning_modules = sequelize.define(
'learning_modules',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
title: {
type: DataTypes.TEXT,
},
difficulty: {
type: DataTypes.ENUM,
values: [
"beginner",
"intermediate",
"advanced"
],
},
topic: {
type: DataTypes.ENUM,
values: [
"basics",
"risk_management",
"technical_analysis",
"fundamentals",
"options_awareness",
"macro",
"portfolio_building"
],
},
summary: {
type: DataTypes.TEXT,
},
content: {
type: DataTypes.TEXT,
},
estimated_minutes: {
type: DataTypes.INTEGER,
},
published: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
learning_modules.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.learning_modules.belongsTo(db.users, {
as: 'createdBy',
});
db.learning_modules.belongsTo(db.users, {
as: 'updatedBy',
});
};
return learning_modules;
};

View File

@ -0,0 +1,271 @@
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 market_symbols = sequelize.define(
'market_symbols',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
symbol: {
type: DataTypes.TEXT,
},
name: {
type: DataTypes.TEXT,
},
asset_class: {
type: DataTypes.ENUM,
values: [
"stock",
"crypto",
"forex",
"etf",
"index"
],
},
exchange: {
type: DataTypes.TEXT,
},
currency: {
type: DataTypes.TEXT,
},
country: {
type: DataTypes.TEXT,
},
sector: {
type: DataTypes.TEXT,
},
industry: {
type: DataTypes.TEXT,
},
active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
last_refreshed_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
market_symbols.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.market_symbols.hasMany(db.symbol_fundamentals, {
as: 'symbol_fundamentals_market_symbol',
foreignKey: {
name: 'market_symbolId',
},
constraints: false,
});
db.market_symbols.hasMany(db.price_quotes, {
as: 'price_quotes_market_symbol',
foreignKey: {
name: 'market_symbolId',
},
constraints: false,
});
db.market_symbols.hasMany(db.technical_indicators, {
as: 'technical_indicators_market_symbol',
foreignKey: {
name: 'market_symbolId',
},
constraints: false,
});
db.market_symbols.hasMany(db.analyst_ratings, {
as: 'analyst_ratings_market_symbol',
foreignKey: {
name: 'market_symbolId',
},
constraints: false,
});
db.market_symbols.hasMany(db.earnings_reports, {
as: 'earnings_reports_market_symbol',
foreignKey: {
name: 'market_symbolId',
},
constraints: false,
});
db.market_symbols.hasMany(db.news_article_symbols, {
as: 'news_article_symbols_market_symbol',
foreignKey: {
name: 'market_symbolId',
},
constraints: false,
});
db.market_symbols.hasMany(db.watchlist_items, {
as: 'watchlist_items_market_symbol',
foreignKey: {
name: 'market_symbolId',
},
constraints: false,
});
db.market_symbols.hasMany(db.paper_orders, {
as: 'paper_orders_market_symbol',
foreignKey: {
name: 'market_symbolId',
},
constraints: false,
});
db.market_symbols.hasMany(db.paper_positions, {
as: 'paper_positions_market_symbol',
foreignKey: {
name: 'market_symbolId',
},
constraints: false,
});
db.market_symbols.hasMany(db.screener_results, {
as: 'screener_results_market_symbol',
foreignKey: {
name: 'market_symbolId',
},
constraints: false,
});
db.market_symbols.hasMany(db.ir_companies, {
as: 'ir_companies_market_symbol',
foreignKey: {
name: 'market_symbolId',
},
constraints: false,
});
//end loop
db.market_symbols.belongsTo(db.users, {
as: 'createdBy',
});
db.market_symbols.belongsTo(db.users, {
as: 'updatedBy',
});
};
return market_symbols;
};

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 news_article_symbols = sequelize.define(
'news_article_symbols',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
relevance: {
type: DataTypes.ENUM,
values: [
"primary",
"secondary",
"mentioned"
],
},
sentiment_score: {
type: DataTypes.DECIMAL,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
news_article_symbols.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.news_article_symbols.belongsTo(db.news_articles, {
as: 'news_article',
foreignKey: {
name: 'news_articleId',
},
constraints: false,
});
db.news_article_symbols.belongsTo(db.market_symbols, {
as: 'market_symbol',
foreignKey: {
name: 'market_symbolId',
},
constraints: false,
});
db.news_article_symbols.belongsTo(db.users, {
as: 'createdBy',
});
db.news_article_symbols.belongsTo(db.users, {
as: 'updatedBy',
});
};
return news_article_symbols;
};

View File

@ -0,0 +1,223 @@
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 news_articles = sequelize.define(
'news_articles',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
title: {
type: DataTypes.TEXT,
},
publisher: {
type: DataTypes.TEXT,
},
published_at: {
type: DataTypes.DATE,
},
category: {
type: DataTypes.ENUM,
values: [
"stocks",
"crypto",
"earnings",
"macro",
"etfs",
"forex",
"general"
],
},
url: {
type: DataTypes.TEXT,
},
summary: {
type: DataTypes.TEXT,
},
content: {
type: DataTypes.TEXT,
},
sentiment: {
type: DataTypes.ENUM,
values: [
"positive",
"neutral",
"negative",
"mixed",
"unknown"
],
},
source: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
news_articles.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.news_articles.hasMany(db.news_article_symbols, {
as: 'news_article_symbols_news_article',
foreignKey: {
name: 'news_articleId',
},
constraints: false,
});
db.news_articles.hasMany(db.article_bookmarks, {
as: 'article_bookmarks_news_article',
foreignKey: {
name: 'news_articleId',
},
constraints: false,
});
//end loop
db.news_articles.hasMany(db.file, {
as: 'cover_images',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.news_articles.getTableName(),
belongsToColumn: 'cover_images',
},
});
db.news_articles.belongsTo(db.users, {
as: 'createdBy',
});
db.news_articles.belongsTo(db.users, {
as: 'updatedBy',
});
};
return news_articles;
};

View File

@ -0,0 +1,191 @@
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 paper_accounts = sequelize.define(
'paper_accounts',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
base_currency: {
type: DataTypes.ENUM,
values: [
"USD",
"EUR",
"GBP",
"JPY"
],
},
starting_cash: {
type: DataTypes.DECIMAL,
},
cash_balance: {
type: DataTypes.DECIMAL,
},
buying_power: {
type: DataTypes.DECIMAL,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
opened_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
paper_accounts.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.paper_accounts.hasMany(db.paper_orders, {
as: 'paper_orders_paper_account',
foreignKey: {
name: 'paper_accountId',
},
constraints: false,
});
db.paper_accounts.hasMany(db.paper_positions, {
as: 'paper_positions_paper_account',
foreignKey: {
name: 'paper_accountId',
},
constraints: false,
});
db.paper_accounts.hasMany(db.portfolio_snapshots, {
as: 'portfolio_snapshots_paper_account',
foreignKey: {
name: 'paper_accountId',
},
constraints: false,
});
//end loop
db.paper_accounts.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.paper_accounts.belongsTo(db.users, {
as: 'createdBy',
});
db.paper_accounts.belongsTo(db.users, {
as: 'updatedBy',
});
};
return paper_accounts;
};

View File

@ -0,0 +1,241 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const paper_orders = sequelize.define(
'paper_orders',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
placed_at: {
type: DataTypes.DATE,
},
filled_at: {
type: DataTypes.DATE,
},
side: {
type: DataTypes.ENUM,
values: [
"buy",
"sell"
],
},
order_type: {
type: DataTypes.ENUM,
values: [
"market",
"limit",
"stop",
"stop_limit"
],
},
quantity: {
type: DataTypes.DECIMAL,
},
limit_price: {
type: DataTypes.DECIMAL,
},
stop_price: {
type: DataTypes.DECIMAL,
},
filled_quantity: {
type: DataTypes.DECIMAL,
},
average_fill_price: {
type: DataTypes.DECIMAL,
},
status: {
type: DataTypes.ENUM,
values: [
"pending",
"placed",
"partially_filled",
"filled",
"canceled",
"rejected",
"expired"
],
},
rejection_reason: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
paper_orders.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.paper_orders.hasMany(db.paper_trades, {
as: 'paper_trades_paper_order',
foreignKey: {
name: 'paper_orderId',
},
constraints: false,
});
//end loop
db.paper_orders.belongsTo(db.paper_accounts, {
as: 'paper_account',
foreignKey: {
name: 'paper_accountId',
},
constraints: false,
});
db.paper_orders.belongsTo(db.market_symbols, {
as: 'market_symbol',
foreignKey: {
name: 'market_symbolId',
},
constraints: false,
});
db.paper_orders.belongsTo(db.users, {
as: 'createdBy',
});
db.paper_orders.belongsTo(db.users, {
as: 'updatedBy',
});
};
return paper_orders;
};

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 paper_positions = sequelize.define(
'paper_positions',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
quantity: {
type: DataTypes.DECIMAL,
},
average_cost: {
type: DataTypes.DECIMAL,
},
market_value: {
type: DataTypes.DECIMAL,
},
unrealized_pl: {
type: DataTypes.DECIMAL,
},
realized_pl: {
type: DataTypes.DECIMAL,
},
day_pl: {
type: DataTypes.DECIMAL,
},
last_priced_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
paper_positions.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.paper_positions.belongsTo(db.paper_accounts, {
as: 'paper_account',
foreignKey: {
name: 'paper_accountId',
},
constraints: false,
});
db.paper_positions.belongsTo(db.market_symbols, {
as: 'market_symbol',
foreignKey: {
name: 'market_symbolId',
},
constraints: false,
});
db.paper_positions.belongsTo(db.users, {
as: 'createdBy',
});
db.paper_positions.belongsTo(db.users, {
as: 'updatedBy',
});
};
return paper_positions;
};

View File

@ -0,0 +1,135 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const paper_trades = sequelize.define(
'paper_trades',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
executed_at: {
type: DataTypes.DATE,
},
quantity: {
type: DataTypes.DECIMAL,
},
price: {
type: DataTypes.DECIMAL,
},
fees: {
type: DataTypes.DECIMAL,
},
venue: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
paper_trades.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.paper_trades.belongsTo(db.paper_orders, {
as: 'paper_order',
foreignKey: {
name: 'paper_orderId',
},
constraints: false,
});
db.paper_trades.belongsTo(db.users, {
as: 'createdBy',
});
db.paper_trades.belongsTo(db.users, {
as: 'updatedBy',
});
};
return paper_trades;
};

View File

@ -0,0 +1,99 @@
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,149 @@
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 portfolio_snapshots = sequelize.define(
'portfolio_snapshots',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
snapshotted_at: {
type: DataTypes.DATE,
},
total_value: {
type: DataTypes.DECIMAL,
},
cash_value: {
type: DataTypes.DECIMAL,
},
positions_value: {
type: DataTypes.DECIMAL,
},
day_pl: {
type: DataTypes.DECIMAL,
},
all_time_pl: {
type: DataTypes.DECIMAL,
},
day_pl_percent: {
type: DataTypes.DECIMAL,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
portfolio_snapshots.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.portfolio_snapshots.belongsTo(db.paper_accounts, {
as: 'paper_account',
foreignKey: {
name: 'paper_accountId',
},
constraints: false,
});
db.portfolio_snapshots.belongsTo(db.users, {
as: 'createdBy',
});
db.portfolio_snapshots.belongsTo(db.users, {
as: 'updatedBy',
});
};
return portfolio_snapshots;
};

View File

@ -0,0 +1,204 @@
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 price_quotes = sequelize.define(
'price_quotes',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
quoted_at: {
type: DataTypes.DATE,
},
price: {
type: DataTypes.DECIMAL,
},
open: {
type: DataTypes.DECIMAL,
},
high: {
type: DataTypes.DECIMAL,
},
low: {
type: DataTypes.DECIMAL,
},
previous_close: {
type: DataTypes.DECIMAL,
},
change_amount: {
type: DataTypes.DECIMAL,
},
change_percent: {
type: DataTypes.DECIMAL,
},
volume: {
type: DataTypes.DECIMAL,
},
timeframe: {
type: DataTypes.ENUM,
values: [
"1min",
"5min",
"15min",
"30min",
"60min",
"daily",
"weekly",
"monthly"
],
},
source: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
price_quotes.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.price_quotes.belongsTo(db.market_symbols, {
as: 'market_symbol',
foreignKey: {
name: 'market_symbolId',
},
constraints: false,
});
db.price_quotes.belongsTo(db.users, {
as: 'createdBy',
});
db.price_quotes.belongsTo(db.users, {
as: 'updatedBy',
});
};
return price_quotes;
};

View File

@ -0,0 +1,132 @@
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,217 @@
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 screener_filters = sequelize.define(
'screener_filters',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
asset_class: {
type: DataTypes.ENUM,
values: [
"stock",
"etf",
"crypto",
"forex"
],
},
sector: {
type: DataTypes.TEXT,
},
market_cap_min: {
type: DataTypes.DECIMAL,
},
market_cap_max: {
type: DataTypes.DECIMAL,
},
pe_min: {
type: DataTypes.DECIMAL,
},
pe_max: {
type: DataTypes.DECIMAL,
},
price_min: {
type: DataTypes.DECIMAL,
},
price_max: {
type: DataTypes.DECIMAL,
},
volume_min: {
type: DataTypes.DECIMAL,
},
performance_52w_min: {
type: DataTypes.DECIMAL,
},
performance_52w_max: {
type: DataTypes.DECIMAL,
},
is_pinned: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
screener_filters.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.screener_filters.hasMany(db.screener_runs, {
as: 'screener_runs_screener_filter',
foreignKey: {
name: 'screener_filterId',
},
constraints: false,
});
//end loop
db.screener_filters.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.screener_filters.belongsTo(db.users, {
as: 'createdBy',
});
db.screener_filters.belongsTo(db.users, {
as: 'updatedBy',
});
};
return screener_filters;
};

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 screener_results = sequelize.define(
'screener_results',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
last_price: {
type: DataTypes.DECIMAL,
},
market_cap: {
type: DataTypes.DECIMAL,
},
pe_ratio: {
type: DataTypes.DECIMAL,
},
volume: {
type: DataTypes.DECIMAL,
},
performance_52w: {
type: DataTypes.DECIMAL,
},
sector: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
screener_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.screener_results.belongsTo(db.screener_runs, {
as: 'screener_run',
foreignKey: {
name: 'screener_runId',
},
constraints: false,
});
db.screener_results.belongsTo(db.market_symbols, {
as: 'market_symbol',
foreignKey: {
name: 'market_symbolId',
},
constraints: false,
});
db.screener_results.belongsTo(db.users, {
as: 'createdBy',
});
db.screener_results.belongsTo(db.users, {
as: 'updatedBy',
});
};
return screener_results;
};

View File

@ -0,0 +1,151 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const screener_runs = sequelize.define(
'screener_runs',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
run_at: {
type: DataTypes.DATE,
},
result_count: {
type: DataTypes.INTEGER,
},
status: {
type: DataTypes.ENUM,
values: [
"queued",
"running",
"completed",
"failed"
],
},
error_message: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
screener_runs.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.screener_runs.hasMany(db.screener_results, {
as: 'screener_results_screener_run',
foreignKey: {
name: 'screener_runId',
},
constraints: false,
});
//end loop
db.screener_runs.belongsTo(db.screener_filters, {
as: 'screener_filter',
foreignKey: {
name: 'screener_filterId',
},
constraints: false,
});
db.screener_runs.belongsTo(db.users, {
as: 'createdBy',
});
db.screener_runs.belongsTo(db.users, {
as: 'updatedBy',
});
};
return screener_runs;
};

View File

@ -0,0 +1,163 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const symbol_fundamentals = sequelize.define(
'symbol_fundamentals',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
pe_ratio: {
type: DataTypes.DECIMAL,
},
eps: {
type: DataTypes.DECIMAL,
},
market_cap: {
type: DataTypes.DECIMAL,
},
revenue: {
type: DataTypes.DECIMAL,
},
dividend_yield: {
type: DataTypes.DECIMAL,
},
beta: {
type: DataTypes.DECIMAL,
},
shares_outstanding: {
type: DataTypes.DECIMAL,
},
as_of_at: {
type: DataTypes.DATE,
},
source: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
symbol_fundamentals.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.symbol_fundamentals.belongsTo(db.market_symbols, {
as: 'market_symbol',
foreignKey: {
name: 'market_symbolId',
},
constraints: false,
});
db.symbol_fundamentals.belongsTo(db.users, {
as: 'createdBy',
});
db.symbol_fundamentals.belongsTo(db.users, {
as: 'updatedBy',
});
};
return symbol_fundamentals;
};

View File

@ -0,0 +1,225 @@
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 technical_indicators = sequelize.define(
'technical_indicators',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
calculated_at: {
type: DataTypes.DATE,
},
indicator_type: {
type: DataTypes.ENUM,
values: [
"rsi",
"macd",
"bollinger_bands",
"sma",
"ema",
"volume"
],
},
timeframe: {
type: DataTypes.ENUM,
values: [
"1min",
"5min",
"15min",
"30min",
"60min",
"daily",
"weekly",
"monthly"
],
},
period: {
type: DataTypes.INTEGER,
},
value: {
type: DataTypes.DECIMAL,
},
signal: {
type: DataTypes.DECIMAL,
},
histogram: {
type: DataTypes.DECIMAL,
},
upper_band: {
type: DataTypes.DECIMAL,
},
middle_band: {
type: DataTypes.DECIMAL,
},
lower_band: {
type: DataTypes.DECIMAL,
},
source: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
technical_indicators.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.technical_indicators.belongsTo(db.market_symbols, {
as: 'market_symbol',
foreignKey: {
name: 'market_symbolId',
},
constraints: false,
});
db.technical_indicators.belongsTo(db.users, {
as: 'createdBy',
});
db.technical_indicators.belongsTo(db.users, {
as: 'updatedBy',
});
};
return technical_indicators;
};

View File

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

View File

@ -0,0 +1,313 @@
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.article_bookmarks, {
as: 'article_bookmarks_user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.users.hasMany(db.watchlists, {
as: 'watchlists_user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.users.hasMany(db.paper_accounts, {
as: 'paper_accounts_user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.users.hasMany(db.screener_filters, {
as: 'screener_filters_user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.users.hasMany(db.ai_chat_sessions, {
as: 'ai_chat_sessions_user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.users.hasMany(db.user_tooltips, {
as: 'user_tooltips_user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.users.hasMany(db.audit_events, {
as: 'audit_events_user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
//end loop
db.users.belongsTo(db.roles, {
as: 'app_role',
foreignKey: {
name: 'app_roleId',
},
constraints: false,
});
db.users.hasMany(db.file, {
as: 'avatar',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.users.getTableName(),
belongsToColumn: 'avatar',
},
});
db.users.belongsTo(db.users, {
as: 'createdBy',
});
db.users.belongsTo(db.users, {
as: 'updatedBy',
});
};
users.beforeCreate((users, options) => {
users = trimStringFields(users);
if (users.provider !== providers.LOCAL && Object.values(providers).indexOf(users.provider) > -1) {
users.emailVerified = true;
if (!users.password) {
const password = crypto
.randomBytes(20)
.toString('hex');
const hashedPassword = bcrypt.hashSync(
password,
config.bcrypt.saltRounds,
);
users.password = hashedPassword
}
}
});
users.beforeUpdate((users, options) => {
users = trimStringFields(users);
});
return users;
};
function trimStringFields(users) {
users.email = users.email.trim();
users.firstName = users.firstName
? users.firstName.trim()
: null;
users.lastName = users.lastName
? users.lastName.trim()
: null;
return users;
}

View File

@ -0,0 +1,146 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const watchlist_items = sequelize.define(
'watchlist_items',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
added_at: {
type: DataTypes.DATE,
},
alert_above_price: {
type: DataTypes.DECIMAL,
},
alert_below_price: {
type: DataTypes.DECIMAL,
},
alerts_enabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
note: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
watchlist_items.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.watchlist_items.belongsTo(db.watchlists, {
as: 'watchlist',
foreignKey: {
name: 'watchlistId',
},
constraints: false,
});
db.watchlist_items.belongsTo(db.market_symbols, {
as: 'market_symbol',
foreignKey: {
name: 'market_symbolId',
},
constraints: false,
});
db.watchlist_items.belongsTo(db.users, {
as: 'createdBy',
});
db.watchlist_items.belongsTo(db.users, {
as: 'updatedBy',
});
};
return watchlist_items;
};

View File

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

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

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

View File

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

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

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

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

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

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

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

@ -0,0 +1,262 @@
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 api_providersRoutes = require('./routes/api_providers');
const market_symbolsRoutes = require('./routes/market_symbols');
const symbol_fundamentalsRoutes = require('./routes/symbol_fundamentals');
const price_quotesRoutes = require('./routes/price_quotes');
const technical_indicatorsRoutes = require('./routes/technical_indicators');
const analyst_ratingsRoutes = require('./routes/analyst_ratings');
const earnings_reportsRoutes = require('./routes/earnings_reports');
const news_articlesRoutes = require('./routes/news_articles');
const news_article_symbolsRoutes = require('./routes/news_article_symbols');
const article_bookmarksRoutes = require('./routes/article_bookmarks');
const watchlistsRoutes = require('./routes/watchlists');
const watchlist_itemsRoutes = require('./routes/watchlist_items');
const paper_accountsRoutes = require('./routes/paper_accounts');
const paper_ordersRoutes = require('./routes/paper_orders');
const paper_tradesRoutes = require('./routes/paper_trades');
const paper_positionsRoutes = require('./routes/paper_positions');
const portfolio_snapshotsRoutes = require('./routes/portfolio_snapshots');
const screener_filtersRoutes = require('./routes/screener_filters');
const screener_runsRoutes = require('./routes/screener_runs');
const screener_resultsRoutes = require('./routes/screener_results');
const ai_chat_sessionsRoutes = require('./routes/ai_chat_sessions');
const ai_messagesRoutes = require('./routes/ai_messages');
const learning_modulesRoutes = require('./routes/learning_modules');
const user_tooltipsRoutes = require('./routes/user_tooltips');
const ir_companiesRoutes = require('./routes/ir_companies');
const ir_management_membersRoutes = require('./routes/ir_management_members');
const ir_filingsRoutes = require('./routes/ir_filings');
const ir_dividendsRoutes = require('./routes/ir_dividends');
const ir_announcementsRoutes = require('./routes/ir_announcements');
const ir_financial_statement_summariesRoutes = require('./routes/ir_financial_statement_summaries');
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: "App Preview",
description: "App Preview 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/api_providers', passport.authenticate('jwt', {session: false}), api_providersRoutes);
app.use('/api/market_symbols', passport.authenticate('jwt', {session: false}), market_symbolsRoutes);
app.use('/api/symbol_fundamentals', passport.authenticate('jwt', {session: false}), symbol_fundamentalsRoutes);
app.use('/api/price_quotes', passport.authenticate('jwt', {session: false}), price_quotesRoutes);
app.use('/api/technical_indicators', passport.authenticate('jwt', {session: false}), technical_indicatorsRoutes);
app.use('/api/analyst_ratings', passport.authenticate('jwt', {session: false}), analyst_ratingsRoutes);
app.use('/api/earnings_reports', passport.authenticate('jwt', {session: false}), earnings_reportsRoutes);
app.use('/api/news_articles', passport.authenticate('jwt', {session: false}), news_articlesRoutes);
app.use('/api/news_article_symbols', passport.authenticate('jwt', {session: false}), news_article_symbolsRoutes);
app.use('/api/article_bookmarks', passport.authenticate('jwt', {session: false}), article_bookmarksRoutes);
app.use('/api/watchlists', passport.authenticate('jwt', {session: false}), watchlistsRoutes);
app.use('/api/watchlist_items', passport.authenticate('jwt', {session: false}), watchlist_itemsRoutes);
app.use('/api/paper_accounts', passport.authenticate('jwt', {session: false}), paper_accountsRoutes);
app.use('/api/paper_orders', passport.authenticate('jwt', {session: false}), paper_ordersRoutes);
app.use('/api/paper_trades', passport.authenticate('jwt', {session: false}), paper_tradesRoutes);
app.use('/api/paper_positions', passport.authenticate('jwt', {session: false}), paper_positionsRoutes);
app.use('/api/portfolio_snapshots', passport.authenticate('jwt', {session: false}), portfolio_snapshotsRoutes);
app.use('/api/screener_filters', passport.authenticate('jwt', {session: false}), screener_filtersRoutes);
app.use('/api/screener_runs', passport.authenticate('jwt', {session: false}), screener_runsRoutes);
app.use('/api/screener_results', passport.authenticate('jwt', {session: false}), screener_resultsRoutes);
app.use('/api/ai_chat_sessions', passport.authenticate('jwt', {session: false}), ai_chat_sessionsRoutes);
app.use('/api/ai_messages', passport.authenticate('jwt', {session: false}), ai_messagesRoutes);
app.use('/api/learning_modules', passport.authenticate('jwt', {session: false}), learning_modulesRoutes);
app.use('/api/user_tooltips', passport.authenticate('jwt', {session: false}), user_tooltipsRoutes);
app.use('/api/ir_companies', passport.authenticate('jwt', {session: false}), ir_companiesRoutes);
app.use('/api/ir_management_members', passport.authenticate('jwt', {session: false}), ir_management_membersRoutes);
app.use('/api/ir_filings', passport.authenticate('jwt', {session: false}), ir_filingsRoutes);
app.use('/api/ir_dividends', passport.authenticate('jwt', {session: false}), ir_dividendsRoutes);
app.use('/api/ir_announcements', passport.authenticate('jwt', {session: false}), ir_announcementsRoutes);
app.use('/api/ir_financial_statement_summaries', passport.authenticate('jwt', {session: false}), ir_financial_statement_summariesRoutes);
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,
};

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