Initial version

This commit is contained in:
Flatlogic Bot 2026-03-23 16:25:45 +00:00
commit f196e848bf
616 changed files with 206560 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>Plateforme Alzheimer Care</h2>
<p>Plateforme centralisée Alzheimer: stimulation cognitive, alertes IoT, rappels et dashboard partagé pour familles et soignants.</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 @@
# Plateforme Alzheimer Care
## 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_39280
DB_USER=app_39280
DB_PASS=26325c27-3be8-43eb-90a7-370200dd994b
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 @@
#Plateforme Alzheimer Care - 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_plateforme_alzheimer_care;`
- Then give that new user privileges to the new database then quit the `psql`.
- `postgres=> GRANT ALL PRIVILEGES ON DATABASE db_plateforme_alzheimer_care 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": "plateformealzheimercare",
"description": "Plateforme Alzheimer Care - 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});
});
}

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

@ -0,0 +1,81 @@
const os = require('os');
const config = {
gcloud: {
bucket: "fldemo-files",
hash: "afeefb9d49f5b7977577876b99532ac7"
},
bcrypt: {
saltRounds: 12
},
admin_pass: "26325c27",
user_pass: "370200dd994b",
admin_email: "admin@flatlogic.com",
providers: {
LOCAL: 'local',
GOOGLE: 'google',
MICROSOFT: 'microsoft'
},
secret_key: process.env.SECRET_KEY || '26325c27-3be8-43eb-90a7-370200dd994b',
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: 'Plateforme Alzheimer Care <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: {
super_admin: 'Super Administrator',
admin: 'Administrator',
user: 'family_viewer',
},
project_uuid: '26325c27-3be8-43eb-90a7-370200dd994b',
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 = 'Warm sunrise over calm horizon';
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,461 @@
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 AccountsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const accounts = await db.accounts.create(
{
id: data.id || undefined,
name: data.name
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return 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 accountsData = 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 accounts = await db.accounts.bulkCreate(accountsData, { transaction });
// For each item created, replace relation files
return accounts;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const accounts = await db.accounts.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
updatePayload.updatedById = currentUser.id;
await accounts.update(updatePayload, {transaction});
return accounts;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const accounts = await db.accounts.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of accounts) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of accounts) {
await record.destroy({transaction});
}
});
return accounts;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const accounts = await db.accounts.findByPk(id, options);
await accounts.update({
deletedBy: currentUser.id
}, {
transaction,
});
await accounts.destroy({
transaction
});
return accounts;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const accounts = await db.accounts.findOne(
{ where },
{ transaction },
);
if (!accounts) {
return accounts;
}
const output = accounts.get({plain: true});
output.users_accounts = await accounts.getUsers_accounts({
transaction
});
output.patients_account = await accounts.getPatients_account({
transaction
});
output.patient_access_grants_accounts = await accounts.getPatient_access_grants_accounts({
transaction
});
output.medications_accounts = await accounts.getMedications_accounts({
transaction
});
output.medication_schedules_accounts = await accounts.getMedication_schedules_accounts({
transaction
});
output.calendar_events_accounts = await accounts.getCalendar_events_accounts({
transaction
});
output.reminders_accounts = await accounts.getReminders_accounts({
transaction
});
output.cognitive_programs_accounts = await accounts.getCognitive_programs_accounts({
transaction
});
output.cognitive_exercises_accounts = await accounts.getCognitive_exercises_accounts({
transaction
});
output.cognitive_sessions_accounts = await accounts.getCognitive_sessions_accounts({
transaction
});
output.cognitive_attempts_accounts = await accounts.getCognitive_attempts_accounts({
transaction
});
output.stage_assessments_accounts = await accounts.getStage_assessments_accounts({
transaction
});
output.voice_assistant_sessions_accounts = await accounts.getVoice_assistant_sessions_accounts({
transaction
});
output.iot_devices_accounts = await accounts.getIot_devices_accounts({
transaction
});
output.iot_telemetry_events_accounts = await accounts.getIot_telemetry_events_accounts({
transaction
});
output.geofences_accounts = await accounts.getGeofences_accounts({
transaction
});
output.alerts_accounts = await accounts.getAlerts_accounts({
transaction
});
output.alert_notifications_accounts = await accounts.getAlert_notifications_accounts({
transaction
});
output.shared_dashboard_posts_accounts = await accounts.getShared_dashboard_posts_accounts({
transaction
});
output.scientific_articles_accounts = await accounts.getScientific_articles_accounts({
transaction
});
output.article_recommendations_accounts = await accounts.getArticle_recommendations_accounts({
transaction
});
output.clinical_reports_accounts = await accounts.getClinical_reports_accounts({
transaction
});
output.admin_metrics_snapshots_accounts = await accounts.getAdmin_metrics_snapshots_accounts({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userAccounts = (user && user.accounts?.id) || null;
if (userAccounts) {
if (options?.currentUser?.accountsId) {
where.accountsId = options.currentUser.accountsId;
}
}
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(
'accounts',
'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,
},
};
}
}
}
if (globalAccess) {
delete where.accountsId;
}
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.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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'accounts',
'name',
query,
),
],
};
}
const records = await db.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,702 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Admin_metrics_snapshotsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const admin_metrics_snapshots = await db.admin_metrics_snapshots.create(
{
id: data.id || undefined,
snapshot_at: data.snapshot_at
||
null
,
total_accounts: data.total_accounts
||
null
,
total_users: data.total_users
||
null
,
total_patients: data.total_patients
||
null
,
active_devices: data.active_devices
||
null
,
alerts_last_24h: data.alerts_last_24h
||
null
,
cognitive_sessions_last_7d: data.cognitive_sessions_last_7d
||
null
,
reminders_sent_last_24h: data.reminders_sent_last_24h
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await admin_metrics_snapshots.setAccounts( data.accounts || null, {
transaction,
});
return admin_metrics_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 admin_metrics_snapshotsData = data.map((item, index) => ({
id: item.id || undefined,
snapshot_at: item.snapshot_at
||
null
,
total_accounts: item.total_accounts
||
null
,
total_users: item.total_users
||
null
,
total_patients: item.total_patients
||
null
,
active_devices: item.active_devices
||
null
,
alerts_last_24h: item.alerts_last_24h
||
null
,
cognitive_sessions_last_7d: item.cognitive_sessions_last_7d
||
null
,
reminders_sent_last_24h: item.reminders_sent_last_24h
||
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 admin_metrics_snapshots = await db.admin_metrics_snapshots.bulkCreate(admin_metrics_snapshotsData, { transaction });
// For each item created, replace relation files
return admin_metrics_snapshots;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const admin_metrics_snapshots = await db.admin_metrics_snapshots.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.snapshot_at !== undefined) updatePayload.snapshot_at = data.snapshot_at;
if (data.total_accounts !== undefined) updatePayload.total_accounts = data.total_accounts;
if (data.total_users !== undefined) updatePayload.total_users = data.total_users;
if (data.total_patients !== undefined) updatePayload.total_patients = data.total_patients;
if (data.active_devices !== undefined) updatePayload.active_devices = data.active_devices;
if (data.alerts_last_24h !== undefined) updatePayload.alerts_last_24h = data.alerts_last_24h;
if (data.cognitive_sessions_last_7d !== undefined) updatePayload.cognitive_sessions_last_7d = data.cognitive_sessions_last_7d;
if (data.reminders_sent_last_24h !== undefined) updatePayload.reminders_sent_last_24h = data.reminders_sent_last_24h;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await admin_metrics_snapshots.update(updatePayload, {transaction});
if (data.accounts !== undefined) {
await admin_metrics_snapshots.setAccounts(
data.accounts,
{ transaction }
);
}
return admin_metrics_snapshots;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const admin_metrics_snapshots = await db.admin_metrics_snapshots.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of admin_metrics_snapshots) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of admin_metrics_snapshots) {
await record.destroy({transaction});
}
});
return admin_metrics_snapshots;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const admin_metrics_snapshots = await db.admin_metrics_snapshots.findByPk(id, options);
await admin_metrics_snapshots.update({
deletedBy: currentUser.id
}, {
transaction,
});
await admin_metrics_snapshots.destroy({
transaction
});
return admin_metrics_snapshots;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const admin_metrics_snapshots = await db.admin_metrics_snapshots.findOne(
{ where },
{ transaction },
);
if (!admin_metrics_snapshots) {
return admin_metrics_snapshots;
}
const output = admin_metrics_snapshots.get({plain: true});
output.accounts = await admin_metrics_snapshots.getAccounts({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userAccounts = (user && user.accounts?.id) || null;
if (userAccounts) {
if (options?.currentUser?.accountsId) {
where.accountsId = options.currentUser.accountsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.accounts,
as: 'accounts',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'admin_metrics_snapshots',
'notes',
filter.notes,
),
};
}
if (filter.snapshot_atRange) {
const [start, end] = filter.snapshot_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
snapshot_at: {
...where.snapshot_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
snapshot_at: {
...where.snapshot_at,
[Op.lte]: end,
},
};
}
}
if (filter.total_accountsRange) {
const [start, end] = filter.total_accountsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
total_accounts: {
...where.total_accounts,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
total_accounts: {
...where.total_accounts,
[Op.lte]: end,
},
};
}
}
if (filter.total_usersRange) {
const [start, end] = filter.total_usersRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
total_users: {
...where.total_users,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
total_users: {
...where.total_users,
[Op.lte]: end,
},
};
}
}
if (filter.total_patientsRange) {
const [start, end] = filter.total_patientsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
total_patients: {
...where.total_patients,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
total_patients: {
...where.total_patients,
[Op.lte]: end,
},
};
}
}
if (filter.active_devicesRange) {
const [start, end] = filter.active_devicesRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
active_devices: {
...where.active_devices,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
active_devices: {
...where.active_devices,
[Op.lte]: end,
},
};
}
}
if (filter.alerts_last_24hRange) {
const [start, end] = filter.alerts_last_24hRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
alerts_last_24h: {
...where.alerts_last_24h,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
alerts_last_24h: {
...where.alerts_last_24h,
[Op.lte]: end,
},
};
}
}
if (filter.cognitive_sessions_last_7dRange) {
const [start, end] = filter.cognitive_sessions_last_7dRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
cognitive_sessions_last_7d: {
...where.cognitive_sessions_last_7d,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
cognitive_sessions_last_7d: {
...where.cognitive_sessions_last_7d,
[Op.lte]: end,
},
};
}
}
if (filter.reminders_sent_last_24hRange) {
const [start, end] = filter.reminders_sent_last_24hRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
reminders_sent_last_24h: {
...where.reminders_sent_last_24h,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
reminders_sent_last_24h: {
...where.reminders_sent_last_24h,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.accounts) {
const listItems = filter.accounts.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
accountsId: {[Op.or]: listItems}
};
}
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,
},
};
}
}
}
if (globalAccess) {
delete where.accountsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.admin_metrics_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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'admin_metrics_snapshots',
'notes',
query,
),
],
};
}
const records = await db.admin_metrics_snapshots.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,557 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Alert_notificationsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const alert_notifications = await db.alert_notifications.create(
{
id: data.id || undefined,
channel: data.channel
||
null
,
sent_at: data.sent_at
||
null
,
delivery_status: data.delivery_status
||
null
,
provider_message_id: data.provider_message_id
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await alert_notifications.setAlert( data.alert || null, {
transaction,
});
await alert_notifications.setRecipient_user( data.recipient_user || null, {
transaction,
});
await alert_notifications.setAccounts( data.accounts || null, {
transaction,
});
return alert_notifications;
}
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 alert_notificationsData = data.map((item, index) => ({
id: item.id || undefined,
channel: item.channel
||
null
,
sent_at: item.sent_at
||
null
,
delivery_status: item.delivery_status
||
null
,
provider_message_id: item.provider_message_id
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const alert_notifications = await db.alert_notifications.bulkCreate(alert_notificationsData, { transaction });
// For each item created, replace relation files
return alert_notifications;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const alert_notifications = await db.alert_notifications.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.channel !== undefined) updatePayload.channel = data.channel;
if (data.sent_at !== undefined) updatePayload.sent_at = data.sent_at;
if (data.delivery_status !== undefined) updatePayload.delivery_status = data.delivery_status;
if (data.provider_message_id !== undefined) updatePayload.provider_message_id = data.provider_message_id;
updatePayload.updatedById = currentUser.id;
await alert_notifications.update(updatePayload, {transaction});
if (data.alert !== undefined) {
await alert_notifications.setAlert(
data.alert,
{ transaction }
);
}
if (data.recipient_user !== undefined) {
await alert_notifications.setRecipient_user(
data.recipient_user,
{ transaction }
);
}
if (data.accounts !== undefined) {
await alert_notifications.setAccounts(
data.accounts,
{ transaction }
);
}
return alert_notifications;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const alert_notifications = await db.alert_notifications.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of alert_notifications) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of alert_notifications) {
await record.destroy({transaction});
}
});
return alert_notifications;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const alert_notifications = await db.alert_notifications.findByPk(id, options);
await alert_notifications.update({
deletedBy: currentUser.id
}, {
transaction,
});
await alert_notifications.destroy({
transaction
});
return alert_notifications;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const alert_notifications = await db.alert_notifications.findOne(
{ where },
{ transaction },
);
if (!alert_notifications) {
return alert_notifications;
}
const output = alert_notifications.get({plain: true});
output.alert = await alert_notifications.getAlert({
transaction
});
output.recipient_user = await alert_notifications.getRecipient_user({
transaction
});
output.accounts = await alert_notifications.getAccounts({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userAccounts = (user && user.accounts?.id) || null;
if (userAccounts) {
if (options?.currentUser?.accountsId) {
where.accountsId = options.currentUser.accountsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.alerts,
as: 'alert',
where: filter.alert ? {
[Op.or]: [
{ id: { [Op.in]: filter.alert.split('|').map(term => Utils.uuid(term)) } },
{
title_text: {
[Op.or]: filter.alert.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'recipient_user',
where: filter.recipient_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.recipient_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.recipient_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.accounts,
as: 'accounts',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.provider_message_id) {
where = {
...where,
[Op.and]: Utils.ilike(
'alert_notifications',
'provider_message_id',
filter.provider_message_id,
),
};
}
if (filter.sent_atRange) {
const [start, end] = filter.sent_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sent_at: {
...where.sent_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sent_at: {
...where.sent_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.channel) {
where = {
...where,
channel: filter.channel,
};
}
if (filter.delivery_status) {
where = {
...where,
delivery_status: filter.delivery_status,
};
}
if (filter.accounts) {
const listItems = filter.accounts.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
accountsId: {[Op.or]: listItems}
};
}
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,
},
};
}
}
}
if (globalAccess) {
delete where.accountsId;
}
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.alert_notifications.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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'alert_notifications',
'delivery_status',
query,
),
],
};
}
const records = await db.alert_notifications.findAll({
attributes: [ 'id', 'delivery_status' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['delivery_status', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.delivery_status,
}));
}
};

View File

@ -0,0 +1,753 @@
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 AlertsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const alerts = await db.alerts.create(
{
id: data.id || undefined,
alert_type: data.alert_type
||
null
,
severity: data.severity
||
null
,
title_text: data.title_text
||
null
,
details: data.details
||
null
,
triggered_at: data.triggered_at
||
null
,
status: data.status
||
null
,
acknowledged_at: data.acknowledged_at
||
null
,
resolved_at: data.resolved_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await alerts.setPatient( data.patient || null, {
transaction,
});
await alerts.setDevice( data.device || null, {
transaction,
});
await alerts.setTrigger_event( data.trigger_event || null, {
transaction,
});
await alerts.setAssigned_to_user( data.assigned_to_user || null, {
transaction,
});
await alerts.setAccounts( data.accounts || null, {
transaction,
});
return alerts;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const alertsData = data.map((item, index) => ({
id: item.id || undefined,
alert_type: item.alert_type
||
null
,
severity: item.severity
||
null
,
title_text: item.title_text
||
null
,
details: item.details
||
null
,
triggered_at: item.triggered_at
||
null
,
status: item.status
||
null
,
acknowledged_at: item.acknowledged_at
||
null
,
resolved_at: item.resolved_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const alerts = await db.alerts.bulkCreate(alertsData, { transaction });
// For each item created, replace relation files
return alerts;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const alerts = await db.alerts.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.alert_type !== undefined) updatePayload.alert_type = data.alert_type;
if (data.severity !== undefined) updatePayload.severity = data.severity;
if (data.title_text !== undefined) updatePayload.title_text = data.title_text;
if (data.details !== undefined) updatePayload.details = data.details;
if (data.triggered_at !== undefined) updatePayload.triggered_at = data.triggered_at;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.acknowledged_at !== undefined) updatePayload.acknowledged_at = data.acknowledged_at;
if (data.resolved_at !== undefined) updatePayload.resolved_at = data.resolved_at;
updatePayload.updatedById = currentUser.id;
await alerts.update(updatePayload, {transaction});
if (data.patient !== undefined) {
await alerts.setPatient(
data.patient,
{ transaction }
);
}
if (data.device !== undefined) {
await alerts.setDevice(
data.device,
{ transaction }
);
}
if (data.trigger_event !== undefined) {
await alerts.setTrigger_event(
data.trigger_event,
{ transaction }
);
}
if (data.assigned_to_user !== undefined) {
await alerts.setAssigned_to_user(
data.assigned_to_user,
{ transaction }
);
}
if (data.accounts !== undefined) {
await alerts.setAccounts(
data.accounts,
{ transaction }
);
}
return alerts;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const alerts = await db.alerts.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of alerts) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of alerts) {
await record.destroy({transaction});
}
});
return alerts;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const alerts = await db.alerts.findByPk(id, options);
await alerts.update({
deletedBy: currentUser.id
}, {
transaction,
});
await alerts.destroy({
transaction
});
return alerts;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const alerts = await db.alerts.findOne(
{ where },
{ transaction },
);
if (!alerts) {
return alerts;
}
const output = alerts.get({plain: true});
output.alert_notifications_alert = await alerts.getAlert_notifications_alert({
transaction
});
output.patient = await alerts.getPatient({
transaction
});
output.device = await alerts.getDevice({
transaction
});
output.trigger_event = await alerts.getTrigger_event({
transaction
});
output.assigned_to_user = await alerts.getAssigned_to_user({
transaction
});
output.accounts = await alerts.getAccounts({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userAccounts = (user && user.accounts?.id) || null;
if (userAccounts) {
if (options?.currentUser?.accountsId) {
where.accountsId = options.currentUser.accountsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.patients,
as: 'patient',
where: filter.patient ? {
[Op.or]: [
{ id: { [Op.in]: filter.patient.split('|').map(term => Utils.uuid(term)) } },
{
last_name: {
[Op.or]: filter.patient.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.iot_devices,
as: 'device',
where: filter.device ? {
[Op.or]: [
{ id: { [Op.in]: filter.device.split('|').map(term => Utils.uuid(term)) } },
{
device_label: {
[Op.or]: filter.device.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.iot_telemetry_events,
as: 'trigger_event',
where: filter.trigger_event ? {
[Op.or]: [
{ id: { [Op.in]: filter.trigger_event.split('|').map(term => Utils.uuid(term)) } },
{
event_kind: {
[Op.or]: filter.trigger_event.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'assigned_to_user',
where: filter.assigned_to_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.assigned_to_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.assigned_to_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.accounts,
as: 'accounts',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.title_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'alerts',
'title_text',
filter.title_text,
),
};
}
if (filter.details) {
where = {
...where,
[Op.and]: Utils.ilike(
'alerts',
'details',
filter.details,
),
};
}
if (filter.triggered_atRange) {
const [start, end] = filter.triggered_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
triggered_at: {
...where.triggered_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
triggered_at: {
...where.triggered_at,
[Op.lte]: end,
},
};
}
}
if (filter.acknowledged_atRange) {
const [start, end] = filter.acknowledged_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
acknowledged_at: {
...where.acknowledged_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
acknowledged_at: {
...where.acknowledged_at,
[Op.lte]: end,
},
};
}
}
if (filter.resolved_atRange) {
const [start, end] = filter.resolved_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
resolved_at: {
...where.resolved_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
resolved_at: {
...where.resolved_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.alert_type) {
where = {
...where,
alert_type: filter.alert_type,
};
}
if (filter.severity) {
where = {
...where,
severity: filter.severity,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.accounts) {
const listItems = filter.accounts.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
accountsId: {[Op.or]: listItems}
};
}
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,
},
};
}
}
}
if (globalAccess) {
delete where.accountsId;
}
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.alerts.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'alerts',
'title_text',
query,
),
],
};
}
const records = await db.alerts.findAll({
attributes: [ 'id', 'title_text' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['title_text', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.title_text,
}));
}
};

View File

@ -0,0 +1,557 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Article_recommendationsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const article_recommendations = await db.article_recommendations.create(
{
id: data.id || undefined,
recommended_at: data.recommended_at
||
null
,
reason_type: data.reason_type
||
null
,
reason_text: data.reason_text
||
null
,
state: data.state
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await article_recommendations.setPatient( data.patient || null, {
transaction,
});
await article_recommendations.setArticle( data.article || null, {
transaction,
});
await article_recommendations.setAccounts( data.accounts || null, {
transaction,
});
return article_recommendations;
}
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_recommendationsData = data.map((item, index) => ({
id: item.id || undefined,
recommended_at: item.recommended_at
||
null
,
reason_type: item.reason_type
||
null
,
reason_text: item.reason_text
||
null
,
state: item.state
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const article_recommendations = await db.article_recommendations.bulkCreate(article_recommendationsData, { transaction });
// For each item created, replace relation files
return article_recommendations;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const article_recommendations = await db.article_recommendations.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.recommended_at !== undefined) updatePayload.recommended_at = data.recommended_at;
if (data.reason_type !== undefined) updatePayload.reason_type = data.reason_type;
if (data.reason_text !== undefined) updatePayload.reason_text = data.reason_text;
if (data.state !== undefined) updatePayload.state = data.state;
updatePayload.updatedById = currentUser.id;
await article_recommendations.update(updatePayload, {transaction});
if (data.patient !== undefined) {
await article_recommendations.setPatient(
data.patient,
{ transaction }
);
}
if (data.article !== undefined) {
await article_recommendations.setArticle(
data.article,
{ transaction }
);
}
if (data.accounts !== undefined) {
await article_recommendations.setAccounts(
data.accounts,
{ transaction }
);
}
return article_recommendations;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const article_recommendations = await db.article_recommendations.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of article_recommendations) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of article_recommendations) {
await record.destroy({transaction});
}
});
return article_recommendations;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const article_recommendations = await db.article_recommendations.findByPk(id, options);
await article_recommendations.update({
deletedBy: currentUser.id
}, {
transaction,
});
await article_recommendations.destroy({
transaction
});
return article_recommendations;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const article_recommendations = await db.article_recommendations.findOne(
{ where },
{ transaction },
);
if (!article_recommendations) {
return article_recommendations;
}
const output = article_recommendations.get({plain: true});
output.patient = await article_recommendations.getPatient({
transaction
});
output.article = await article_recommendations.getArticle({
transaction
});
output.accounts = await article_recommendations.getAccounts({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userAccounts = (user && user.accounts?.id) || null;
if (userAccounts) {
if (options?.currentUser?.accountsId) {
where.accountsId = options.currentUser.accountsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.patients,
as: 'patient',
where: filter.patient ? {
[Op.or]: [
{ id: { [Op.in]: filter.patient.split('|').map(term => Utils.uuid(term)) } },
{
last_name: {
[Op.or]: filter.patient.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.scientific_articles,
as: 'article',
where: filter.article ? {
[Op.or]: [
{ id: { [Op.in]: filter.article.split('|').map(term => Utils.uuid(term)) } },
{
title_text: {
[Op.or]: filter.article.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.accounts,
as: 'accounts',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.reason_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'article_recommendations',
'reason_text',
filter.reason_text,
),
};
}
if (filter.recommended_atRange) {
const [start, end] = filter.recommended_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
recommended_at: {
...where.recommended_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
recommended_at: {
...where.recommended_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.reason_type) {
where = {
...where,
reason_type: filter.reason_type,
};
}
if (filter.state) {
where = {
...where,
state: filter.state,
};
}
if (filter.accounts) {
const listItems = filter.accounts.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
accountsId: {[Op.or]: listItems}
};
}
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,
},
};
}
}
}
if (globalAccess) {
delete where.accountsId;
}
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_recommendations.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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'article_recommendations',
'reason_type',
query,
),
],
};
}
const records = await db.article_recommendations.findAll({
attributes: [ 'id', 'reason_type' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['reason_type', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.reason_type,
}));
}
};

View File

@ -0,0 +1,760 @@
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 Calendar_eventsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const calendar_events = await db.calendar_events.create(
{
id: data.id || undefined,
event_type: data.event_type
||
null
,
title_text: data.title_text
||
null
,
description: data.description
||
null
,
start_at: data.start_at
||
null
,
end_at: data.end_at
||
null
,
location_text: data.location_text
||
null
,
status: data.status
||
null
,
has_reminder: data.has_reminder
||
false
,
reminder_minutes_before: data.reminder_minutes_before
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await calendar_events.setPatient( data.patient || null, {
transaction,
});
await calendar_events.setCreated_by_user( data.created_by_user || null, {
transaction,
});
await calendar_events.setLinked_medication( data.linked_medication || null, {
transaction,
});
await calendar_events.setAccounts( data.accounts || null, {
transaction,
});
return calendar_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 calendar_eventsData = data.map((item, index) => ({
id: item.id || undefined,
event_type: item.event_type
||
null
,
title_text: item.title_text
||
null
,
description: item.description
||
null
,
start_at: item.start_at
||
null
,
end_at: item.end_at
||
null
,
location_text: item.location_text
||
null
,
status: item.status
||
null
,
has_reminder: item.has_reminder
||
false
,
reminder_minutes_before: item.reminder_minutes_before
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const calendar_events = await db.calendar_events.bulkCreate(calendar_eventsData, { transaction });
// For each item created, replace relation files
return calendar_events;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const calendar_events = await db.calendar_events.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.event_type !== undefined) updatePayload.event_type = data.event_type;
if (data.title_text !== undefined) updatePayload.title_text = data.title_text;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.start_at !== undefined) updatePayload.start_at = data.start_at;
if (data.end_at !== undefined) updatePayload.end_at = data.end_at;
if (data.location_text !== undefined) updatePayload.location_text = data.location_text;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.has_reminder !== undefined) updatePayload.has_reminder = data.has_reminder;
if (data.reminder_minutes_before !== undefined) updatePayload.reminder_minutes_before = data.reminder_minutes_before;
updatePayload.updatedById = currentUser.id;
await calendar_events.update(updatePayload, {transaction});
if (data.patient !== undefined) {
await calendar_events.setPatient(
data.patient,
{ transaction }
);
}
if (data.created_by_user !== undefined) {
await calendar_events.setCreated_by_user(
data.created_by_user,
{ transaction }
);
}
if (data.linked_medication !== undefined) {
await calendar_events.setLinked_medication(
data.linked_medication,
{ transaction }
);
}
if (data.accounts !== undefined) {
await calendar_events.setAccounts(
data.accounts,
{ transaction }
);
}
return calendar_events;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const calendar_events = await db.calendar_events.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of calendar_events) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of calendar_events) {
await record.destroy({transaction});
}
});
return calendar_events;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const calendar_events = await db.calendar_events.findByPk(id, options);
await calendar_events.update({
deletedBy: currentUser.id
}, {
transaction,
});
await calendar_events.destroy({
transaction
});
return calendar_events;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const calendar_events = await db.calendar_events.findOne(
{ where },
{ transaction },
);
if (!calendar_events) {
return calendar_events;
}
const output = calendar_events.get({plain: true});
output.reminders_event = await calendar_events.getReminders_event({
transaction
});
output.patient = await calendar_events.getPatient({
transaction
});
output.created_by_user = await calendar_events.getCreated_by_user({
transaction
});
output.linked_medication = await calendar_events.getLinked_medication({
transaction
});
output.accounts = await calendar_events.getAccounts({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userAccounts = (user && user.accounts?.id) || null;
if (userAccounts) {
if (options?.currentUser?.accountsId) {
where.accountsId = options.currentUser.accountsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.patients,
as: 'patient',
where: filter.patient ? {
[Op.or]: [
{ id: { [Op.in]: filter.patient.split('|').map(term => Utils.uuid(term)) } },
{
last_name: {
[Op.or]: filter.patient.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'created_by_user',
where: filter.created_by_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.created_by_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.created_by_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.medications,
as: 'linked_medication',
where: filter.linked_medication ? {
[Op.or]: [
{ id: { [Op.in]: filter.linked_medication.split('|').map(term => Utils.uuid(term)) } },
{
medication_name: {
[Op.or]: filter.linked_medication.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.accounts,
as: 'accounts',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.title_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'calendar_events',
'title_text',
filter.title_text,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'calendar_events',
'description',
filter.description,
),
};
}
if (filter.location_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'calendar_events',
'location_text',
filter.location_text,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
start_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
end_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.start_atRange) {
const [start, end] = filter.start_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
start_at: {
...where.start_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
start_at: {
...where.start_at,
[Op.lte]: end,
},
};
}
}
if (filter.end_atRange) {
const [start, end] = filter.end_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
end_at: {
...where.end_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
end_at: {
...where.end_at,
[Op.lte]: end,
},
};
}
}
if (filter.reminder_minutes_beforeRange) {
const [start, end] = filter.reminder_minutes_beforeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
reminder_minutes_before: {
...where.reminder_minutes_before,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
reminder_minutes_before: {
...where.reminder_minutes_before,
[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.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.has_reminder) {
where = {
...where,
has_reminder: filter.has_reminder,
};
}
if (filter.accounts) {
const listItems = filter.accounts.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
accountsId: {[Op.or]: listItems}
};
}
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,
},
};
}
}
}
if (globalAccess) {
delete where.accountsId;
}
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.calendar_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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'calendar_events',
'title_text',
query,
),
],
};
}
const records = await db.calendar_events.findAll({
attributes: [ 'id', 'title_text' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['title_text', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.title_text,
}));
}
};

View File

@ -0,0 +1,640 @@
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 Clinical_reportsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const clinical_reports = await db.clinical_reports.create(
{
id: data.id || undefined,
period_start_at: data.period_start_at
||
null
,
period_end_at: data.period_end_at
||
null
,
report_title: data.report_title
||
null
,
summary: data.summary
||
null
,
share_scope: data.share_scope
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await clinical_reports.setPatient( data.patient || null, {
transaction,
});
await clinical_reports.setGenerated_by_user( data.generated_by_user || null, {
transaction,
});
await clinical_reports.setAccounts( data.accounts || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.clinical_reports.getTableName(),
belongsToColumn: 'report_file',
belongsToId: clinical_reports.id,
},
data.report_file,
options,
);
return clinical_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 clinical_reportsData = data.map((item, index) => ({
id: item.id || undefined,
period_start_at: item.period_start_at
||
null
,
period_end_at: item.period_end_at
||
null
,
report_title: item.report_title
||
null
,
summary: item.summary
||
null
,
share_scope: item.share_scope
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const clinical_reports = await db.clinical_reports.bulkCreate(clinical_reportsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < clinical_reports.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.clinical_reports.getTableName(),
belongsToColumn: 'report_file',
belongsToId: clinical_reports[i].id,
},
data[i].report_file,
options,
);
}
return clinical_reports;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const clinical_reports = await db.clinical_reports.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.period_start_at !== undefined) updatePayload.period_start_at = data.period_start_at;
if (data.period_end_at !== undefined) updatePayload.period_end_at = data.period_end_at;
if (data.report_title !== undefined) updatePayload.report_title = data.report_title;
if (data.summary !== undefined) updatePayload.summary = data.summary;
if (data.share_scope !== undefined) updatePayload.share_scope = data.share_scope;
updatePayload.updatedById = currentUser.id;
await clinical_reports.update(updatePayload, {transaction});
if (data.patient !== undefined) {
await clinical_reports.setPatient(
data.patient,
{ transaction }
);
}
if (data.generated_by_user !== undefined) {
await clinical_reports.setGenerated_by_user(
data.generated_by_user,
{ transaction }
);
}
if (data.accounts !== undefined) {
await clinical_reports.setAccounts(
data.accounts,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.clinical_reports.getTableName(),
belongsToColumn: 'report_file',
belongsToId: clinical_reports.id,
},
data.report_file,
options,
);
return clinical_reports;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const clinical_reports = await db.clinical_reports.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of clinical_reports) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of clinical_reports) {
await record.destroy({transaction});
}
});
return clinical_reports;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const clinical_reports = await db.clinical_reports.findByPk(id, options);
await clinical_reports.update({
deletedBy: currentUser.id
}, {
transaction,
});
await clinical_reports.destroy({
transaction
});
return clinical_reports;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const clinical_reports = await db.clinical_reports.findOne(
{ where },
{ transaction },
);
if (!clinical_reports) {
return clinical_reports;
}
const output = clinical_reports.get({plain: true});
output.patient = await clinical_reports.getPatient({
transaction
});
output.generated_by_user = await clinical_reports.getGenerated_by_user({
transaction
});
output.report_file = await clinical_reports.getReport_file({
transaction
});
output.accounts = await clinical_reports.getAccounts({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userAccounts = (user && user.accounts?.id) || null;
if (userAccounts) {
if (options?.currentUser?.accountsId) {
where.accountsId = options.currentUser.accountsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.patients,
as: 'patient',
where: filter.patient ? {
[Op.or]: [
{ id: { [Op.in]: filter.patient.split('|').map(term => Utils.uuid(term)) } },
{
last_name: {
[Op.or]: filter.patient.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'generated_by_user',
where: filter.generated_by_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.generated_by_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.generated_by_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.accounts,
as: 'accounts',
},
{
model: db.file,
as: 'report_file',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.report_title) {
where = {
...where,
[Op.and]: Utils.ilike(
'clinical_reports',
'report_title',
filter.report_title,
),
};
}
if (filter.summary) {
where = {
...where,
[Op.and]: Utils.ilike(
'clinical_reports',
'summary',
filter.summary,
),
};
}
if (filter.period_start_atRange) {
const [start, end] = filter.period_start_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
period_start_at: {
...where.period_start_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
period_start_at: {
...where.period_start_at,
[Op.lte]: end,
},
};
}
}
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.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.share_scope) {
where = {
...where,
share_scope: filter.share_scope,
};
}
if (filter.accounts) {
const listItems = filter.accounts.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
accountsId: {[Op.or]: listItems}
};
}
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,
},
};
}
}
}
if (globalAccess) {
delete where.accountsId;
}
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.clinical_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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'clinical_reports',
'report_title',
query,
),
],
};
}
const records = await db.clinical_reports.findAll({
attributes: [ 'id', 'report_title' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['report_title', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.report_title,
}));
}
};

View File

@ -0,0 +1,648 @@
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 Cognitive_attemptsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const cognitive_attempts = await db.cognitive_attempts.create(
{
id: data.id || undefined,
attempted_at: data.attempted_at
||
null
,
score: data.score
||
null
,
accuracy: data.accuracy
||
null
,
duration_seconds: data.duration_seconds
||
null
,
result: data.result
||
null
,
raw_response: data.raw_response
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await cognitive_attempts.setSession( data.session || null, {
transaction,
});
await cognitive_attempts.setExercise( data.exercise || null, {
transaction,
});
await cognitive_attempts.setAccounts( data.accounts || null, {
transaction,
});
return cognitive_attempts;
}
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 cognitive_attemptsData = data.map((item, index) => ({
id: item.id || undefined,
attempted_at: item.attempted_at
||
null
,
score: item.score
||
null
,
accuracy: item.accuracy
||
null
,
duration_seconds: item.duration_seconds
||
null
,
result: item.result
||
null
,
raw_response: item.raw_response
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const cognitive_attempts = await db.cognitive_attempts.bulkCreate(cognitive_attemptsData, { transaction });
// For each item created, replace relation files
return cognitive_attempts;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const cognitive_attempts = await db.cognitive_attempts.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.attempted_at !== undefined) updatePayload.attempted_at = data.attempted_at;
if (data.score !== undefined) updatePayload.score = data.score;
if (data.accuracy !== undefined) updatePayload.accuracy = data.accuracy;
if (data.duration_seconds !== undefined) updatePayload.duration_seconds = data.duration_seconds;
if (data.result !== undefined) updatePayload.result = data.result;
if (data.raw_response !== undefined) updatePayload.raw_response = data.raw_response;
updatePayload.updatedById = currentUser.id;
await cognitive_attempts.update(updatePayload, {transaction});
if (data.session !== undefined) {
await cognitive_attempts.setSession(
data.session,
{ transaction }
);
}
if (data.exercise !== undefined) {
await cognitive_attempts.setExercise(
data.exercise,
{ transaction }
);
}
if (data.accounts !== undefined) {
await cognitive_attempts.setAccounts(
data.accounts,
{ transaction }
);
}
return cognitive_attempts;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const cognitive_attempts = await db.cognitive_attempts.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of cognitive_attempts) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of cognitive_attempts) {
await record.destroy({transaction});
}
});
return cognitive_attempts;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const cognitive_attempts = await db.cognitive_attempts.findByPk(id, options);
await cognitive_attempts.update({
deletedBy: currentUser.id
}, {
transaction,
});
await cognitive_attempts.destroy({
transaction
});
return cognitive_attempts;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const cognitive_attempts = await db.cognitive_attempts.findOne(
{ where },
{ transaction },
);
if (!cognitive_attempts) {
return cognitive_attempts;
}
const output = cognitive_attempts.get({plain: true});
output.session = await cognitive_attempts.getSession({
transaction
});
output.exercise = await cognitive_attempts.getExercise({
transaction
});
output.accounts = await cognitive_attempts.getAccounts({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userAccounts = (user && user.accounts?.id) || null;
if (userAccounts) {
if (options?.currentUser?.accountsId) {
where.accountsId = options.currentUser.accountsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.cognitive_sessions,
as: 'session',
where: filter.session ? {
[Op.or]: [
{ id: { [Op.in]: filter.session.split('|').map(term => Utils.uuid(term)) } },
{
completion_status: {
[Op.or]: filter.session.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.cognitive_exercises,
as: 'exercise',
where: filter.exercise ? {
[Op.or]: [
{ id: { [Op.in]: filter.exercise.split('|').map(term => Utils.uuid(term)) } },
{
exercise_name: {
[Op.or]: filter.exercise.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.accounts,
as: 'accounts',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.raw_response) {
where = {
...where,
[Op.and]: Utils.ilike(
'cognitive_attempts',
'raw_response',
filter.raw_response,
),
};
}
if (filter.attempted_atRange) {
const [start, end] = filter.attempted_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
attempted_at: {
...where.attempted_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
attempted_at: {
...where.attempted_at,
[Op.lte]: end,
},
};
}
}
if (filter.scoreRange) {
const [start, end] = filter.scoreRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
score: {
...where.score,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
score: {
...where.score,
[Op.lte]: end,
},
};
}
}
if (filter.accuracyRange) {
const [start, end] = filter.accuracyRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
accuracy: {
...where.accuracy,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
accuracy: {
...where.accuracy,
[Op.lte]: end,
},
};
}
}
if (filter.duration_secondsRange) {
const [start, end] = filter.duration_secondsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
duration_seconds: {
...where.duration_seconds,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
duration_seconds: {
...where.duration_seconds,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.result) {
where = {
...where,
result: filter.result,
};
}
if (filter.accounts) {
const listItems = filter.accounts.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
accountsId: {[Op.or]: listItems}
};
}
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,
},
};
}
}
}
if (globalAccess) {
delete where.accountsId;
}
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.cognitive_attempts.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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'cognitive_attempts',
'result',
query,
),
],
};
}
const records = await db.cognitive_attempts.findAll({
attributes: [ 'id', 'result' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['result', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.result,
}));
}
};

View File

@ -0,0 +1,612 @@
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 Cognitive_exercisesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const cognitive_exercises = await db.cognitive_exercises.create(
{
id: data.id || undefined,
exercise_name: data.exercise_name
||
null
,
exercise_type: data.exercise_type
||
null
,
instructions: data.instructions
||
null
,
difficulty_level: data.difficulty_level
||
null
,
max_score: data.max_score
||
null
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await cognitive_exercises.setProgram( data.program || null, {
transaction,
});
await cognitive_exercises.setAccounts( data.accounts || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.cognitive_exercises.getTableName(),
belongsToColumn: 'assets',
belongsToId: cognitive_exercises.id,
},
data.assets,
options,
);
return cognitive_exercises;
}
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 cognitive_exercisesData = data.map((item, index) => ({
id: item.id || undefined,
exercise_name: item.exercise_name
||
null
,
exercise_type: item.exercise_type
||
null
,
instructions: item.instructions
||
null
,
difficulty_level: item.difficulty_level
||
null
,
max_score: item.max_score
||
null
,
is_active: item.is_active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const cognitive_exercises = await db.cognitive_exercises.bulkCreate(cognitive_exercisesData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < cognitive_exercises.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.cognitive_exercises.getTableName(),
belongsToColumn: 'assets',
belongsToId: cognitive_exercises[i].id,
},
data[i].assets,
options,
);
}
return cognitive_exercises;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const cognitive_exercises = await db.cognitive_exercises.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.exercise_name !== undefined) updatePayload.exercise_name = data.exercise_name;
if (data.exercise_type !== undefined) updatePayload.exercise_type = data.exercise_type;
if (data.instructions !== undefined) updatePayload.instructions = data.instructions;
if (data.difficulty_level !== undefined) updatePayload.difficulty_level = data.difficulty_level;
if (data.max_score !== undefined) updatePayload.max_score = data.max_score;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await cognitive_exercises.update(updatePayload, {transaction});
if (data.program !== undefined) {
await cognitive_exercises.setProgram(
data.program,
{ transaction }
);
}
if (data.accounts !== undefined) {
await cognitive_exercises.setAccounts(
data.accounts,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.cognitive_exercises.getTableName(),
belongsToColumn: 'assets',
belongsToId: cognitive_exercises.id,
},
data.assets,
options,
);
return cognitive_exercises;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const cognitive_exercises = await db.cognitive_exercises.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of cognitive_exercises) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of cognitive_exercises) {
await record.destroy({transaction});
}
});
return cognitive_exercises;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const cognitive_exercises = await db.cognitive_exercises.findByPk(id, options);
await cognitive_exercises.update({
deletedBy: currentUser.id
}, {
transaction,
});
await cognitive_exercises.destroy({
transaction
});
return cognitive_exercises;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const cognitive_exercises = await db.cognitive_exercises.findOne(
{ where },
{ transaction },
);
if (!cognitive_exercises) {
return cognitive_exercises;
}
const output = cognitive_exercises.get({plain: true});
output.cognitive_attempts_exercise = await cognitive_exercises.getCognitive_attempts_exercise({
transaction
});
output.program = await cognitive_exercises.getProgram({
transaction
});
output.assets = await cognitive_exercises.getAssets({
transaction
});
output.accounts = await cognitive_exercises.getAccounts({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userAccounts = (user && user.accounts?.id) || null;
if (userAccounts) {
if (options?.currentUser?.accountsId) {
where.accountsId = options.currentUser.accountsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.cognitive_programs,
as: 'program',
where: filter.program ? {
[Op.or]: [
{ id: { [Op.in]: filter.program.split('|').map(term => Utils.uuid(term)) } },
{
program_name: {
[Op.or]: filter.program.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.accounts,
as: 'accounts',
},
{
model: db.file,
as: 'assets',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.exercise_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'cognitive_exercises',
'exercise_name',
filter.exercise_name,
),
};
}
if (filter.instructions) {
where = {
...where,
[Op.and]: Utils.ilike(
'cognitive_exercises',
'instructions',
filter.instructions,
),
};
}
if (filter.max_scoreRange) {
const [start, end] = filter.max_scoreRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
max_score: {
...where.max_score,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
max_score: {
...where.max_score,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.exercise_type) {
where = {
...where,
exercise_type: filter.exercise_type,
};
}
if (filter.difficulty_level) {
where = {
...where,
difficulty_level: filter.difficulty_level,
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
if (filter.accounts) {
const listItems = filter.accounts.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
accountsId: {[Op.or]: listItems}
};
}
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,
},
};
}
}
}
if (globalAccess) {
delete where.accountsId;
}
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.cognitive_exercises.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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'cognitive_exercises',
'exercise_name',
query,
),
],
};
}
const records = await db.cognitive_exercises.findAll({
attributes: [ 'id', 'exercise_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['exercise_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.exercise_name,
}));
}
};

View File

@ -0,0 +1,552 @@
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 Cognitive_programsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const cognitive_programs = await db.cognitive_programs.create(
{
id: data.id || undefined,
program_name: data.program_name
||
null
,
description: data.description
||
null
,
target_stage: data.target_stage
||
null
,
status: data.status
||
null
,
estimated_minutes: data.estimated_minutes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await cognitive_programs.setCreated_by_user( data.created_by_user || null, {
transaction,
});
await cognitive_programs.setAccounts( data.accounts || null, {
transaction,
});
return cognitive_programs;
}
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 cognitive_programsData = data.map((item, index) => ({
id: item.id || undefined,
program_name: item.program_name
||
null
,
description: item.description
||
null
,
target_stage: item.target_stage
||
null
,
status: item.status
||
null
,
estimated_minutes: item.estimated_minutes
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const cognitive_programs = await db.cognitive_programs.bulkCreate(cognitive_programsData, { transaction });
// For each item created, replace relation files
return cognitive_programs;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const cognitive_programs = await db.cognitive_programs.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.program_name !== undefined) updatePayload.program_name = data.program_name;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.target_stage !== undefined) updatePayload.target_stage = data.target_stage;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.estimated_minutes !== undefined) updatePayload.estimated_minutes = data.estimated_minutes;
updatePayload.updatedById = currentUser.id;
await cognitive_programs.update(updatePayload, {transaction});
if (data.created_by_user !== undefined) {
await cognitive_programs.setCreated_by_user(
data.created_by_user,
{ transaction }
);
}
if (data.accounts !== undefined) {
await cognitive_programs.setAccounts(
data.accounts,
{ transaction }
);
}
return cognitive_programs;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const cognitive_programs = await db.cognitive_programs.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of cognitive_programs) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of cognitive_programs) {
await record.destroy({transaction});
}
});
return cognitive_programs;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const cognitive_programs = await db.cognitive_programs.findByPk(id, options);
await cognitive_programs.update({
deletedBy: currentUser.id
}, {
transaction,
});
await cognitive_programs.destroy({
transaction
});
return cognitive_programs;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const cognitive_programs = await db.cognitive_programs.findOne(
{ where },
{ transaction },
);
if (!cognitive_programs) {
return cognitive_programs;
}
const output = cognitive_programs.get({plain: true});
output.cognitive_exercises_program = await cognitive_programs.getCognitive_exercises_program({
transaction
});
output.cognitive_sessions_program = await cognitive_programs.getCognitive_sessions_program({
transaction
});
output.created_by_user = await cognitive_programs.getCreated_by_user({
transaction
});
output.accounts = await cognitive_programs.getAccounts({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userAccounts = (user && user.accounts?.id) || null;
if (userAccounts) {
if (options?.currentUser?.accountsId) {
where.accountsId = options.currentUser.accountsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.users,
as: 'created_by_user',
where: filter.created_by_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.created_by_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.created_by_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.accounts,
as: 'accounts',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.program_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'cognitive_programs',
'program_name',
filter.program_name,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'cognitive_programs',
'description',
filter.description,
),
};
}
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.target_stage) {
where = {
...where,
target_stage: filter.target_stage,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.accounts) {
const listItems = filter.accounts.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
accountsId: {[Op.or]: listItems}
};
}
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,
},
};
}
}
}
if (globalAccess) {
delete where.accountsId;
}
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.cognitive_programs.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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'cognitive_programs',
'program_name',
query,
),
],
};
}
const records = await db.cognitive_programs.findAll({
attributes: [ 'id', 'program_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['program_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.program_name,
}));
}
};

View File

@ -0,0 +1,652 @@
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 Cognitive_sessionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const cognitive_sessions = await db.cognitive_sessions.create(
{
id: data.id || undefined,
started_at: data.started_at
||
null
,
ended_at: data.ended_at
||
null
,
completion_status: data.completion_status
||
null
,
total_score: data.total_score
||
null
,
session_notes: data.session_notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await cognitive_sessions.setPatient( data.patient || null, {
transaction,
});
await cognitive_sessions.setProgram( data.program || null, {
transaction,
});
await cognitive_sessions.setStarted_by_user( data.started_by_user || null, {
transaction,
});
await cognitive_sessions.setAccounts( data.accounts || null, {
transaction,
});
return cognitive_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 cognitive_sessionsData = data.map((item, index) => ({
id: item.id || undefined,
started_at: item.started_at
||
null
,
ended_at: item.ended_at
||
null
,
completion_status: item.completion_status
||
null
,
total_score: item.total_score
||
null
,
session_notes: item.session_notes
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const cognitive_sessions = await db.cognitive_sessions.bulkCreate(cognitive_sessionsData, { transaction });
// For each item created, replace relation files
return cognitive_sessions;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const cognitive_sessions = await db.cognitive_sessions.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
if (data.ended_at !== undefined) updatePayload.ended_at = data.ended_at;
if (data.completion_status !== undefined) updatePayload.completion_status = data.completion_status;
if (data.total_score !== undefined) updatePayload.total_score = data.total_score;
if (data.session_notes !== undefined) updatePayload.session_notes = data.session_notes;
updatePayload.updatedById = currentUser.id;
await cognitive_sessions.update(updatePayload, {transaction});
if (data.patient !== undefined) {
await cognitive_sessions.setPatient(
data.patient,
{ transaction }
);
}
if (data.program !== undefined) {
await cognitive_sessions.setProgram(
data.program,
{ transaction }
);
}
if (data.started_by_user !== undefined) {
await cognitive_sessions.setStarted_by_user(
data.started_by_user,
{ transaction }
);
}
if (data.accounts !== undefined) {
await cognitive_sessions.setAccounts(
data.accounts,
{ transaction }
);
}
return cognitive_sessions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const cognitive_sessions = await db.cognitive_sessions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of cognitive_sessions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of cognitive_sessions) {
await record.destroy({transaction});
}
});
return cognitive_sessions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const cognitive_sessions = await db.cognitive_sessions.findByPk(id, options);
await cognitive_sessions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await cognitive_sessions.destroy({
transaction
});
return cognitive_sessions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const cognitive_sessions = await db.cognitive_sessions.findOne(
{ where },
{ transaction },
);
if (!cognitive_sessions) {
return cognitive_sessions;
}
const output = cognitive_sessions.get({plain: true});
output.cognitive_attempts_session = await cognitive_sessions.getCognitive_attempts_session({
transaction
});
output.patient = await cognitive_sessions.getPatient({
transaction
});
output.program = await cognitive_sessions.getProgram({
transaction
});
output.started_by_user = await cognitive_sessions.getStarted_by_user({
transaction
});
output.accounts = await cognitive_sessions.getAccounts({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userAccounts = (user && user.accounts?.id) || null;
if (userAccounts) {
if (options?.currentUser?.accountsId) {
where.accountsId = options.currentUser.accountsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.patients,
as: 'patient',
where: filter.patient ? {
[Op.or]: [
{ id: { [Op.in]: filter.patient.split('|').map(term => Utils.uuid(term)) } },
{
last_name: {
[Op.or]: filter.patient.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.cognitive_programs,
as: 'program',
where: filter.program ? {
[Op.or]: [
{ id: { [Op.in]: filter.program.split('|').map(term => Utils.uuid(term)) } },
{
program_name: {
[Op.or]: filter.program.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'started_by_user',
where: filter.started_by_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.started_by_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.started_by_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.accounts,
as: 'accounts',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.session_notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'cognitive_sessions',
'session_notes',
filter.session_notes,
),
};
}
if (filter.started_atRange) {
const [start, end] = filter.started_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
started_at: {
...where.started_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
started_at: {
...where.started_at,
[Op.lte]: end,
},
};
}
}
if (filter.ended_atRange) {
const [start, end] = filter.ended_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
ended_at: {
...where.ended_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
ended_at: {
...where.ended_at,
[Op.lte]: end,
},
};
}
}
if (filter.total_scoreRange) {
const [start, end] = filter.total_scoreRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
total_score: {
...where.total_score,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
total_score: {
...where.total_score,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.completion_status) {
where = {
...where,
completion_status: filter.completion_status,
};
}
if (filter.accounts) {
const listItems = filter.accounts.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
accountsId: {[Op.or]: listItems}
};
}
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,
},
};
}
}
}
if (globalAccess) {
delete where.accountsId;
}
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.cognitive_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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'cognitive_sessions',
'completion_status',
query,
),
],
};
}
const records = await db.cognitive_sessions.findAll({
attributes: [ 'id', 'completion_status' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['completion_status', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.completion_status,
}));
}
};

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,640 @@
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 GeofencesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const geofences = await db.geofences.create(
{
id: data.id || undefined,
geofence_name: data.geofence_name
||
null
,
shape_type: data.shape_type
||
null
,
center_latitude: data.center_latitude
||
null
,
center_longitude: data.center_longitude
||
null
,
radius_meters: data.radius_meters
||
null
,
polygon_points: data.polygon_points
||
null
,
is_active: data.is_active
||
false
,
alert_on: data.alert_on
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await geofences.setPatient( data.patient || null, {
transaction,
});
await geofences.setAccounts( data.accounts || null, {
transaction,
});
return geofences;
}
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 geofencesData = data.map((item, index) => ({
id: item.id || undefined,
geofence_name: item.geofence_name
||
null
,
shape_type: item.shape_type
||
null
,
center_latitude: item.center_latitude
||
null
,
center_longitude: item.center_longitude
||
null
,
radius_meters: item.radius_meters
||
null
,
polygon_points: item.polygon_points
||
null
,
is_active: item.is_active
||
false
,
alert_on: item.alert_on
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const geofences = await db.geofences.bulkCreate(geofencesData, { transaction });
// For each item created, replace relation files
return geofences;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const geofences = await db.geofences.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.geofence_name !== undefined) updatePayload.geofence_name = data.geofence_name;
if (data.shape_type !== undefined) updatePayload.shape_type = data.shape_type;
if (data.center_latitude !== undefined) updatePayload.center_latitude = data.center_latitude;
if (data.center_longitude !== undefined) updatePayload.center_longitude = data.center_longitude;
if (data.radius_meters !== undefined) updatePayload.radius_meters = data.radius_meters;
if (data.polygon_points !== undefined) updatePayload.polygon_points = data.polygon_points;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
if (data.alert_on !== undefined) updatePayload.alert_on = data.alert_on;
updatePayload.updatedById = currentUser.id;
await geofences.update(updatePayload, {transaction});
if (data.patient !== undefined) {
await geofences.setPatient(
data.patient,
{ transaction }
);
}
if (data.accounts !== undefined) {
await geofences.setAccounts(
data.accounts,
{ transaction }
);
}
return geofences;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const geofences = await db.geofences.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of geofences) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of geofences) {
await record.destroy({transaction});
}
});
return geofences;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const geofences = await db.geofences.findByPk(id, options);
await geofences.update({
deletedBy: currentUser.id
}, {
transaction,
});
await geofences.destroy({
transaction
});
return geofences;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const geofences = await db.geofences.findOne(
{ where },
{ transaction },
);
if (!geofences) {
return geofences;
}
const output = geofences.get({plain: true});
output.patient = await geofences.getPatient({
transaction
});
output.accounts = await geofences.getAccounts({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userAccounts = (user && user.accounts?.id) || null;
if (userAccounts) {
if (options?.currentUser?.accountsId) {
where.accountsId = options.currentUser.accountsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.patients,
as: 'patient',
where: filter.patient ? {
[Op.or]: [
{ id: { [Op.in]: filter.patient.split('|').map(term => Utils.uuid(term)) } },
{
last_name: {
[Op.or]: filter.patient.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.accounts,
as: 'accounts',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.geofence_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'geofences',
'geofence_name',
filter.geofence_name,
),
};
}
if (filter.polygon_points) {
where = {
...where,
[Op.and]: Utils.ilike(
'geofences',
'polygon_points',
filter.polygon_points,
),
};
}
if (filter.center_latitudeRange) {
const [start, end] = filter.center_latitudeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
center_latitude: {
...where.center_latitude,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
center_latitude: {
...where.center_latitude,
[Op.lte]: end,
},
};
}
}
if (filter.center_longitudeRange) {
const [start, end] = filter.center_longitudeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
center_longitude: {
...where.center_longitude,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
center_longitude: {
...where.center_longitude,
[Op.lte]: end,
},
};
}
}
if (filter.radius_metersRange) {
const [start, end] = filter.radius_metersRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
radius_meters: {
...where.radius_meters,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
radius_meters: {
...where.radius_meters,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.shape_type) {
where = {
...where,
shape_type: filter.shape_type,
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
if (filter.alert_on) {
where = {
...where,
alert_on: filter.alert_on,
};
}
if (filter.accounts) {
const listItems = filter.accounts.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
accountsId: {[Op.or]: listItems}
};
}
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,
},
};
}
}
}
if (globalAccess) {
delete where.accountsId;
}
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.geofences.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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'geofences',
'geofence_name',
query,
),
],
};
}
const records = await db.geofences.findAll({
attributes: [ 'id', 'geofence_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['geofence_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.geofence_name,
}));
}
};

View File

@ -0,0 +1,650 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Iot_devicesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const iot_devices = await db.iot_devices.create(
{
id: data.id || undefined,
device_type: data.device_type
||
null
,
device_label: data.device_label
||
null
,
serial_number: data.serial_number
||
null
,
status: data.status
||
null
,
paired_at: data.paired_at
||
null
,
last_seen_at: data.last_seen_at
||
null
,
battery_level: data.battery_level
||
null
,
firmware_version: data.firmware_version
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await iot_devices.setPatient( data.patient || null, {
transaction,
});
await iot_devices.setAccounts( data.accounts || null, {
transaction,
});
return iot_devices;
}
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 iot_devicesData = data.map((item, index) => ({
id: item.id || undefined,
device_type: item.device_type
||
null
,
device_label: item.device_label
||
null
,
serial_number: item.serial_number
||
null
,
status: item.status
||
null
,
paired_at: item.paired_at
||
null
,
last_seen_at: item.last_seen_at
||
null
,
battery_level: item.battery_level
||
null
,
firmware_version: item.firmware_version
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const iot_devices = await db.iot_devices.bulkCreate(iot_devicesData, { transaction });
// For each item created, replace relation files
return iot_devices;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const iot_devices = await db.iot_devices.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.device_type !== undefined) updatePayload.device_type = data.device_type;
if (data.device_label !== undefined) updatePayload.device_label = data.device_label;
if (data.serial_number !== undefined) updatePayload.serial_number = data.serial_number;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.paired_at !== undefined) updatePayload.paired_at = data.paired_at;
if (data.last_seen_at !== undefined) updatePayload.last_seen_at = data.last_seen_at;
if (data.battery_level !== undefined) updatePayload.battery_level = data.battery_level;
if (data.firmware_version !== undefined) updatePayload.firmware_version = data.firmware_version;
updatePayload.updatedById = currentUser.id;
await iot_devices.update(updatePayload, {transaction});
if (data.patient !== undefined) {
await iot_devices.setPatient(
data.patient,
{ transaction }
);
}
if (data.accounts !== undefined) {
await iot_devices.setAccounts(
data.accounts,
{ transaction }
);
}
return iot_devices;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const iot_devices = await db.iot_devices.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of iot_devices) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of iot_devices) {
await record.destroy({transaction});
}
});
return iot_devices;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const iot_devices = await db.iot_devices.findByPk(id, options);
await iot_devices.update({
deletedBy: currentUser.id
}, {
transaction,
});
await iot_devices.destroy({
transaction
});
return iot_devices;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const iot_devices = await db.iot_devices.findOne(
{ where },
{ transaction },
);
if (!iot_devices) {
return iot_devices;
}
const output = iot_devices.get({plain: true});
output.iot_telemetry_events_device = await iot_devices.getIot_telemetry_events_device({
transaction
});
output.alerts_device = await iot_devices.getAlerts_device({
transaction
});
output.patient = await iot_devices.getPatient({
transaction
});
output.accounts = await iot_devices.getAccounts({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userAccounts = (user && user.accounts?.id) || null;
if (userAccounts) {
if (options?.currentUser?.accountsId) {
where.accountsId = options.currentUser.accountsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.patients,
as: 'patient',
where: filter.patient ? {
[Op.or]: [
{ id: { [Op.in]: filter.patient.split('|').map(term => Utils.uuid(term)) } },
{
last_name: {
[Op.or]: filter.patient.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.accounts,
as: 'accounts',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.device_label) {
where = {
...where,
[Op.and]: Utils.ilike(
'iot_devices',
'device_label',
filter.device_label,
),
};
}
if (filter.serial_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'iot_devices',
'serial_number',
filter.serial_number,
),
};
}
if (filter.firmware_version) {
where = {
...where,
[Op.and]: Utils.ilike(
'iot_devices',
'firmware_version',
filter.firmware_version,
),
};
}
if (filter.paired_atRange) {
const [start, end] = filter.paired_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
paired_at: {
...where.paired_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
paired_at: {
...where.paired_at,
[Op.lte]: end,
},
};
}
}
if (filter.last_seen_atRange) {
const [start, end] = filter.last_seen_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
last_seen_at: {
...where.last_seen_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
last_seen_at: {
...where.last_seen_at,
[Op.lte]: end,
},
};
}
}
if (filter.battery_levelRange) {
const [start, end] = filter.battery_levelRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
battery_level: {
...where.battery_level,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
battery_level: {
...where.battery_level,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.device_type) {
where = {
...where,
device_type: filter.device_type,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.accounts) {
const listItems = filter.accounts.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
accountsId: {[Op.or]: listItems}
};
}
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,
},
};
}
}
}
if (globalAccess) {
delete where.accountsId;
}
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.iot_devices.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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'iot_devices',
'device_label',
query,
),
],
};
}
const records = await db.iot_devices.findAll({
attributes: [ 'id', 'device_label' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['device_label', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.device_label,
}));
}
};

View File

@ -0,0 +1,702 @@
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 Iot_telemetry_eventsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const iot_telemetry_events = await db.iot_telemetry_events.create(
{
id: data.id || undefined,
recorded_at: data.recorded_at
||
null
,
latitude: data.latitude
||
null
,
longitude: data.longitude
||
null
,
speed: data.speed
||
null
,
accuracy_meters: data.accuracy_meters
||
null
,
battery_level: data.battery_level
||
null
,
event_kind: data.event_kind
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await iot_telemetry_events.setDevice( data.device || null, {
transaction,
});
await iot_telemetry_events.setPatient( data.patient || null, {
transaction,
});
await iot_telemetry_events.setAccounts( data.accounts || null, {
transaction,
});
return iot_telemetry_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 iot_telemetry_eventsData = data.map((item, index) => ({
id: item.id || undefined,
recorded_at: item.recorded_at
||
null
,
latitude: item.latitude
||
null
,
longitude: item.longitude
||
null
,
speed: item.speed
||
null
,
accuracy_meters: item.accuracy_meters
||
null
,
battery_level: item.battery_level
||
null
,
event_kind: item.event_kind
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const iot_telemetry_events = await db.iot_telemetry_events.bulkCreate(iot_telemetry_eventsData, { transaction });
// For each item created, replace relation files
return iot_telemetry_events;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const iot_telemetry_events = await db.iot_telemetry_events.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.recorded_at !== undefined) updatePayload.recorded_at = data.recorded_at;
if (data.latitude !== undefined) updatePayload.latitude = data.latitude;
if (data.longitude !== undefined) updatePayload.longitude = data.longitude;
if (data.speed !== undefined) updatePayload.speed = data.speed;
if (data.accuracy_meters !== undefined) updatePayload.accuracy_meters = data.accuracy_meters;
if (data.battery_level !== undefined) updatePayload.battery_level = data.battery_level;
if (data.event_kind !== undefined) updatePayload.event_kind = data.event_kind;
updatePayload.updatedById = currentUser.id;
await iot_telemetry_events.update(updatePayload, {transaction});
if (data.device !== undefined) {
await iot_telemetry_events.setDevice(
data.device,
{ transaction }
);
}
if (data.patient !== undefined) {
await iot_telemetry_events.setPatient(
data.patient,
{ transaction }
);
}
if (data.accounts !== undefined) {
await iot_telemetry_events.setAccounts(
data.accounts,
{ transaction }
);
}
return iot_telemetry_events;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const iot_telemetry_events = await db.iot_telemetry_events.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of iot_telemetry_events) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of iot_telemetry_events) {
await record.destroy({transaction});
}
});
return iot_telemetry_events;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const iot_telemetry_events = await db.iot_telemetry_events.findByPk(id, options);
await iot_telemetry_events.update({
deletedBy: currentUser.id
}, {
transaction,
});
await iot_telemetry_events.destroy({
transaction
});
return iot_telemetry_events;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const iot_telemetry_events = await db.iot_telemetry_events.findOne(
{ where },
{ transaction },
);
if (!iot_telemetry_events) {
return iot_telemetry_events;
}
const output = iot_telemetry_events.get({plain: true});
output.alerts_trigger_event = await iot_telemetry_events.getAlerts_trigger_event({
transaction
});
output.device = await iot_telemetry_events.getDevice({
transaction
});
output.patient = await iot_telemetry_events.getPatient({
transaction
});
output.accounts = await iot_telemetry_events.getAccounts({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userAccounts = (user && user.accounts?.id) || null;
if (userAccounts) {
if (options?.currentUser?.accountsId) {
where.accountsId = options.currentUser.accountsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.iot_devices,
as: 'device',
where: filter.device ? {
[Op.or]: [
{ id: { [Op.in]: filter.device.split('|').map(term => Utils.uuid(term)) } },
{
device_label: {
[Op.or]: filter.device.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.patients,
as: 'patient',
where: filter.patient ? {
[Op.or]: [
{ id: { [Op.in]: filter.patient.split('|').map(term => Utils.uuid(term)) } },
{
last_name: {
[Op.or]: filter.patient.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.accounts,
as: 'accounts',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.recorded_atRange) {
const [start, end] = filter.recorded_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
recorded_at: {
...where.recorded_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
recorded_at: {
...where.recorded_at,
[Op.lte]: end,
},
};
}
}
if (filter.latitudeRange) {
const [start, end] = filter.latitudeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
latitude: {
...where.latitude,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
latitude: {
...where.latitude,
[Op.lte]: end,
},
};
}
}
if (filter.longitudeRange) {
const [start, end] = filter.longitudeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
longitude: {
...where.longitude,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
longitude: {
...where.longitude,
[Op.lte]: end,
},
};
}
}
if (filter.speedRange) {
const [start, end] = filter.speedRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
speed: {
...where.speed,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
speed: {
...where.speed,
[Op.lte]: end,
},
};
}
}
if (filter.accuracy_metersRange) {
const [start, end] = filter.accuracy_metersRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
accuracy_meters: {
...where.accuracy_meters,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
accuracy_meters: {
...where.accuracy_meters,
[Op.lte]: end,
},
};
}
}
if (filter.battery_levelRange) {
const [start, end] = filter.battery_levelRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
battery_level: {
...where.battery_level,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
battery_level: {
...where.battery_level,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.event_kind) {
where = {
...where,
event_kind: filter.event_kind,
};
}
if (filter.accounts) {
const listItems = filter.accounts.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
accountsId: {[Op.or]: listItems}
};
}
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,
},
};
}
}
}
if (globalAccess) {
delete where.accountsId;
}
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.iot_telemetry_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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'iot_telemetry_events',
'event_kind',
query,
),
],
};
}
const records = await db.iot_telemetry_events.findAll({
attributes: [ 'id', 'event_kind' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['event_kind', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.event_kind,
}));
}
};

View File

@ -0,0 +1,620 @@
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 Medication_schedulesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const medication_schedules = await db.medication_schedules.create(
{
id: data.id || undefined,
frequency_type: data.frequency_type
||
null
,
time_of_day: data.time_of_day
||
null
,
days_of_week: data.days_of_week
||
null
,
effective_from: data.effective_from
||
null
,
effective_until: data.effective_until
||
null
,
requires_confirmation: data.requires_confirmation
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await medication_schedules.setMedication( data.medication || null, {
transaction,
});
await medication_schedules.setPatient( data.patient || null, {
transaction,
});
await medication_schedules.setAccounts( data.accounts || null, {
transaction,
});
return medication_schedules;
}
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 medication_schedulesData = data.map((item, index) => ({
id: item.id || undefined,
frequency_type: item.frequency_type
||
null
,
time_of_day: item.time_of_day
||
null
,
days_of_week: item.days_of_week
||
null
,
effective_from: item.effective_from
||
null
,
effective_until: item.effective_until
||
null
,
requires_confirmation: item.requires_confirmation
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const medication_schedules = await db.medication_schedules.bulkCreate(medication_schedulesData, { transaction });
// For each item created, replace relation files
return medication_schedules;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const medication_schedules = await db.medication_schedules.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.frequency_type !== undefined) updatePayload.frequency_type = data.frequency_type;
if (data.time_of_day !== undefined) updatePayload.time_of_day = data.time_of_day;
if (data.days_of_week !== undefined) updatePayload.days_of_week = data.days_of_week;
if (data.effective_from !== undefined) updatePayload.effective_from = data.effective_from;
if (data.effective_until !== undefined) updatePayload.effective_until = data.effective_until;
if (data.requires_confirmation !== undefined) updatePayload.requires_confirmation = data.requires_confirmation;
updatePayload.updatedById = currentUser.id;
await medication_schedules.update(updatePayload, {transaction});
if (data.medication !== undefined) {
await medication_schedules.setMedication(
data.medication,
{ transaction }
);
}
if (data.patient !== undefined) {
await medication_schedules.setPatient(
data.patient,
{ transaction }
);
}
if (data.accounts !== undefined) {
await medication_schedules.setAccounts(
data.accounts,
{ transaction }
);
}
return medication_schedules;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const medication_schedules = await db.medication_schedules.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of medication_schedules) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of medication_schedules) {
await record.destroy({transaction});
}
});
return medication_schedules;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const medication_schedules = await db.medication_schedules.findByPk(id, options);
await medication_schedules.update({
deletedBy: currentUser.id
}, {
transaction,
});
await medication_schedules.destroy({
transaction
});
return medication_schedules;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const medication_schedules = await db.medication_schedules.findOne(
{ where },
{ transaction },
);
if (!medication_schedules) {
return medication_schedules;
}
const output = medication_schedules.get({plain: true});
output.medication = await medication_schedules.getMedication({
transaction
});
output.patient = await medication_schedules.getPatient({
transaction
});
output.accounts = await medication_schedules.getAccounts({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userAccounts = (user && user.accounts?.id) || null;
if (userAccounts) {
if (options?.currentUser?.accountsId) {
where.accountsId = options.currentUser.accountsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.medications,
as: 'medication',
where: filter.medication ? {
[Op.or]: [
{ id: { [Op.in]: filter.medication.split('|').map(term => Utils.uuid(term)) } },
{
medication_name: {
[Op.or]: filter.medication.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.patients,
as: 'patient',
where: filter.patient ? {
[Op.or]: [
{ id: { [Op.in]: filter.patient.split('|').map(term => Utils.uuid(term)) } },
{
last_name: {
[Op.or]: filter.patient.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.accounts,
as: 'accounts',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.time_of_day) {
where = {
...where,
[Op.and]: Utils.ilike(
'medication_schedules',
'time_of_day',
filter.time_of_day,
),
};
}
if (filter.days_of_week) {
where = {
...where,
[Op.and]: Utils.ilike(
'medication_schedules',
'days_of_week',
filter.days_of_week,
),
};
}
if (filter.effective_fromRange) {
const [start, end] = filter.effective_fromRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
effective_from: {
...where.effective_from,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
effective_from: {
...where.effective_from,
[Op.lte]: end,
},
};
}
}
if (filter.effective_untilRange) {
const [start, end] = filter.effective_untilRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
effective_until: {
...where.effective_until,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
effective_until: {
...where.effective_until,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.frequency_type) {
where = {
...where,
frequency_type: filter.frequency_type,
};
}
if (filter.requires_confirmation) {
where = {
...where,
requires_confirmation: filter.requires_confirmation,
};
}
if (filter.accounts) {
const listItems = filter.accounts.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
accountsId: {[Op.or]: listItems}
};
}
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,
},
};
}
}
}
if (globalAccess) {
delete where.accountsId;
}
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.medication_schedules.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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'medication_schedules',
'frequency_type',
query,
),
],
};
}
const records = await db.medication_schedules.findAll({
attributes: [ 'id', 'frequency_type' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['frequency_type', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.frequency_type,
}));
}
};

View File

@ -0,0 +1,656 @@
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 MedicationsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const medications = await db.medications.create(
{
id: data.id || undefined,
medication_name: data.medication_name
||
null
,
dosage: data.dosage
||
null
,
route: data.route
||
null
,
instructions: data.instructions
||
null
,
start_at: data.start_at
||
null
,
end_at: data.end_at
||
null
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await medications.setPatient( data.patient || null, {
transaction,
});
await medications.setPrescribed_by( data.prescribed_by || null, {
transaction,
});
await medications.setAccounts( data.accounts || null, {
transaction,
});
return medications;
}
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 medicationsData = data.map((item, index) => ({
id: item.id || undefined,
medication_name: item.medication_name
||
null
,
dosage: item.dosage
||
null
,
route: item.route
||
null
,
instructions: item.instructions
||
null
,
start_at: item.start_at
||
null
,
end_at: item.end_at
||
null
,
is_active: item.is_active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const medications = await db.medications.bulkCreate(medicationsData, { transaction });
// For each item created, replace relation files
return medications;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const medications = await db.medications.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.medication_name !== undefined) updatePayload.medication_name = data.medication_name;
if (data.dosage !== undefined) updatePayload.dosage = data.dosage;
if (data.route !== undefined) updatePayload.route = data.route;
if (data.instructions !== undefined) updatePayload.instructions = data.instructions;
if (data.start_at !== undefined) updatePayload.start_at = data.start_at;
if (data.end_at !== undefined) updatePayload.end_at = data.end_at;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await medications.update(updatePayload, {transaction});
if (data.patient !== undefined) {
await medications.setPatient(
data.patient,
{ transaction }
);
}
if (data.prescribed_by !== undefined) {
await medications.setPrescribed_by(
data.prescribed_by,
{ transaction }
);
}
if (data.accounts !== undefined) {
await medications.setAccounts(
data.accounts,
{ transaction }
);
}
return medications;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const medications = await db.medications.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of medications) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of medications) {
await record.destroy({transaction});
}
});
return medications;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const medications = await db.medications.findByPk(id, options);
await medications.update({
deletedBy: currentUser.id
}, {
transaction,
});
await medications.destroy({
transaction
});
return medications;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const medications = await db.medications.findOne(
{ where },
{ transaction },
);
if (!medications) {
return medications;
}
const output = medications.get({plain: true});
output.medication_schedules_medication = await medications.getMedication_schedules_medication({
transaction
});
output.calendar_events_linked_medication = await medications.getCalendar_events_linked_medication({
transaction
});
output.patient = await medications.getPatient({
transaction
});
output.prescribed_by = await medications.getPrescribed_by({
transaction
});
output.accounts = await medications.getAccounts({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userAccounts = (user && user.accounts?.id) || null;
if (userAccounts) {
if (options?.currentUser?.accountsId) {
where.accountsId = options.currentUser.accountsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.patients,
as: 'patient',
where: filter.patient ? {
[Op.or]: [
{ id: { [Op.in]: filter.patient.split('|').map(term => Utils.uuid(term)) } },
{
last_name: {
[Op.or]: filter.patient.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'prescribed_by',
where: filter.prescribed_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.prescribed_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.prescribed_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.accounts,
as: 'accounts',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.medication_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'medications',
'medication_name',
filter.medication_name,
),
};
}
if (filter.dosage) {
where = {
...where,
[Op.and]: Utils.ilike(
'medications',
'dosage',
filter.dosage,
),
};
}
if (filter.route) {
where = {
...where,
[Op.and]: Utils.ilike(
'medications',
'route',
filter.route,
),
};
}
if (filter.instructions) {
where = {
...where,
[Op.and]: Utils.ilike(
'medications',
'instructions',
filter.instructions,
),
};
}
if (filter.start_atRange) {
const [start, end] = filter.start_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
start_at: {
...where.start_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
start_at: {
...where.start_at,
[Op.lte]: end,
},
};
}
}
if (filter.end_atRange) {
const [start, end] = filter.end_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
end_at: {
...where.end_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
end_at: {
...where.end_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
if (filter.accounts) {
const listItems = filter.accounts.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
accountsId: {[Op.or]: listItems}
};
}
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,
},
};
}
}
}
if (globalAccess) {
delete where.accountsId;
}
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.medications.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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'medications',
'medication_name',
query,
),
],
};
}
const records = await db.medications.findAll({
attributes: [ 'id', 'medication_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['medication_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.medication_name,
}));
}
};

View File

@ -0,0 +1,638 @@
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 Patient_access_grantsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const patient_access_grants = await db.patient_access_grants.create(
{
id: data.id || undefined,
access_level: data.access_level
||
null
,
can_view_iot_location: data.can_view_iot_location
||
false
,
can_manage_medications: data.can_manage_medications
||
false
,
can_manage_calendar: data.can_manage_calendar
||
false
,
can_view_health_data: data.can_view_health_data
||
false
,
granted_at: data.granted_at
||
null
,
revoked_at: data.revoked_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await patient_access_grants.setPatient( data.patient || null, {
transaction,
});
await patient_access_grants.setUser( data.user || null, {
transaction,
});
await patient_access_grants.setAccounts( data.accounts || null, {
transaction,
});
return patient_access_grants;
}
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 patient_access_grantsData = data.map((item, index) => ({
id: item.id || undefined,
access_level: item.access_level
||
null
,
can_view_iot_location: item.can_view_iot_location
||
false
,
can_manage_medications: item.can_manage_medications
||
false
,
can_manage_calendar: item.can_manage_calendar
||
false
,
can_view_health_data: item.can_view_health_data
||
false
,
granted_at: item.granted_at
||
null
,
revoked_at: item.revoked_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const patient_access_grants = await db.patient_access_grants.bulkCreate(patient_access_grantsData, { transaction });
// For each item created, replace relation files
return patient_access_grants;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const patient_access_grants = await db.patient_access_grants.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.access_level !== undefined) updatePayload.access_level = data.access_level;
if (data.can_view_iot_location !== undefined) updatePayload.can_view_iot_location = data.can_view_iot_location;
if (data.can_manage_medications !== undefined) updatePayload.can_manage_medications = data.can_manage_medications;
if (data.can_manage_calendar !== undefined) updatePayload.can_manage_calendar = data.can_manage_calendar;
if (data.can_view_health_data !== undefined) updatePayload.can_view_health_data = data.can_view_health_data;
if (data.granted_at !== undefined) updatePayload.granted_at = data.granted_at;
if (data.revoked_at !== undefined) updatePayload.revoked_at = data.revoked_at;
updatePayload.updatedById = currentUser.id;
await patient_access_grants.update(updatePayload, {transaction});
if (data.patient !== undefined) {
await patient_access_grants.setPatient(
data.patient,
{ transaction }
);
}
if (data.user !== undefined) {
await patient_access_grants.setUser(
data.user,
{ transaction }
);
}
if (data.accounts !== undefined) {
await patient_access_grants.setAccounts(
data.accounts,
{ transaction }
);
}
return patient_access_grants;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const patient_access_grants = await db.patient_access_grants.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of patient_access_grants) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of patient_access_grants) {
await record.destroy({transaction});
}
});
return patient_access_grants;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const patient_access_grants = await db.patient_access_grants.findByPk(id, options);
await patient_access_grants.update({
deletedBy: currentUser.id
}, {
transaction,
});
await patient_access_grants.destroy({
transaction
});
return patient_access_grants;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const patient_access_grants = await db.patient_access_grants.findOne(
{ where },
{ transaction },
);
if (!patient_access_grants) {
return patient_access_grants;
}
const output = patient_access_grants.get({plain: true});
output.patient = await patient_access_grants.getPatient({
transaction
});
output.user = await patient_access_grants.getUser({
transaction
});
output.accounts = await patient_access_grants.getAccounts({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userAccounts = (user && user.accounts?.id) || null;
if (userAccounts) {
if (options?.currentUser?.accountsId) {
where.accountsId = options.currentUser.accountsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.patients,
as: 'patient',
where: filter.patient ? {
[Op.or]: [
{ id: { [Op.in]: filter.patient.split('|').map(term => Utils.uuid(term)) } },
{
last_name: {
[Op.or]: filter.patient.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'user',
where: filter.user ? {
[Op.or]: [
{ id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.accounts,
as: 'accounts',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.granted_atRange) {
const [start, end] = filter.granted_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
granted_at: {
...where.granted_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
granted_at: {
...where.granted_at,
[Op.lte]: end,
},
};
}
}
if (filter.revoked_atRange) {
const [start, end] = filter.revoked_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
revoked_at: {
...where.revoked_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
revoked_at: {
...where.revoked_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.access_level) {
where = {
...where,
access_level: filter.access_level,
};
}
if (filter.can_view_iot_location) {
where = {
...where,
can_view_iot_location: filter.can_view_iot_location,
};
}
if (filter.can_manage_medications) {
where = {
...where,
can_manage_medications: filter.can_manage_medications,
};
}
if (filter.can_manage_calendar) {
where = {
...where,
can_manage_calendar: filter.can_manage_calendar,
};
}
if (filter.can_view_health_data) {
where = {
...where,
can_view_health_data: filter.can_view_health_data,
};
}
if (filter.accounts) {
const listItems = filter.accounts.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
accountsId: {[Op.or]: listItems}
};
}
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,
},
};
}
}
}
if (globalAccess) {
delete where.accountsId;
}
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.patient_access_grants.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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'patient_access_grants',
'access_level',
query,
),
],
};
}
const records = await db.patient_access_grants.findAll({
attributes: [ 'id', 'access_level' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['access_level', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.access_level,
}));
}
};

View File

@ -0,0 +1,731 @@
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 PatientsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const patients = await db.patients.create(
{
id: data.id || undefined,
patient_code: data.patient_code
||
null
,
first_name: data.first_name
||
null
,
last_name: data.last_name
||
null
,
date_of_birth: data.date_of_birth
||
null
,
sex: data.sex
||
null
,
disease_stage: data.disease_stage
||
null
,
diagnosis_date: data.diagnosis_date
||
null
,
medical_notes: data.medical_notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await patients.setAccount( data.account || null, {
transaction,
});
await patients.setPrimary_physician( data.primary_physician || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.patients.getTableName(),
belongsToColumn: 'profile_photo',
belongsToId: patients.id,
},
data.profile_photo,
options,
);
return patients;
}
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 patientsData = data.map((item, index) => ({
id: item.id || undefined,
patient_code: item.patient_code
||
null
,
first_name: item.first_name
||
null
,
last_name: item.last_name
||
null
,
date_of_birth: item.date_of_birth
||
null
,
sex: item.sex
||
null
,
disease_stage: item.disease_stage
||
null
,
diagnosis_date: item.diagnosis_date
||
null
,
medical_notes: item.medical_notes
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const patients = await db.patients.bulkCreate(patientsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < patients.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.patients.getTableName(),
belongsToColumn: 'profile_photo',
belongsToId: patients[i].id,
},
data[i].profile_photo,
options,
);
}
return patients;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const patients = await db.patients.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.patient_code !== undefined) updatePayload.patient_code = data.patient_code;
if (data.first_name !== undefined) updatePayload.first_name = data.first_name;
if (data.last_name !== undefined) updatePayload.last_name = data.last_name;
if (data.date_of_birth !== undefined) updatePayload.date_of_birth = data.date_of_birth;
if (data.sex !== undefined) updatePayload.sex = data.sex;
if (data.disease_stage !== undefined) updatePayload.disease_stage = data.disease_stage;
if (data.diagnosis_date !== undefined) updatePayload.diagnosis_date = data.diagnosis_date;
if (data.medical_notes !== undefined) updatePayload.medical_notes = data.medical_notes;
updatePayload.updatedById = currentUser.id;
await patients.update(updatePayload, {transaction});
if (data.account !== undefined) {
await patients.setAccount(
data.account,
{ transaction }
);
}
if (data.primary_physician !== undefined) {
await patients.setPrimary_physician(
data.primary_physician,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.patients.getTableName(),
belongsToColumn: 'profile_photo',
belongsToId: patients.id,
},
data.profile_photo,
options,
);
return patients;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const patients = await db.patients.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of patients) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of patients) {
await record.destroy({transaction});
}
});
return patients;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const patients = await db.patients.findByPk(id, options);
await patients.update({
deletedBy: currentUser.id
}, {
transaction,
});
await patients.destroy({
transaction
});
return patients;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const patients = await db.patients.findOne(
{ where },
{ transaction },
);
if (!patients) {
return patients;
}
const output = patients.get({plain: true});
output.patient_access_grants_patient = await patients.getPatient_access_grants_patient({
transaction
});
output.medications_patient = await patients.getMedications_patient({
transaction
});
output.medication_schedules_patient = await patients.getMedication_schedules_patient({
transaction
});
output.calendar_events_patient = await patients.getCalendar_events_patient({
transaction
});
output.reminders_patient = await patients.getReminders_patient({
transaction
});
output.cognitive_sessions_patient = await patients.getCognitive_sessions_patient({
transaction
});
output.stage_assessments_patient = await patients.getStage_assessments_patient({
transaction
});
output.voice_assistant_sessions_patient = await patients.getVoice_assistant_sessions_patient({
transaction
});
output.iot_devices_patient = await patients.getIot_devices_patient({
transaction
});
output.iot_telemetry_events_patient = await patients.getIot_telemetry_events_patient({
transaction
});
output.geofences_patient = await patients.getGeofences_patient({
transaction
});
output.alerts_patient = await patients.getAlerts_patient({
transaction
});
output.shared_dashboard_posts_patient = await patients.getShared_dashboard_posts_patient({
transaction
});
output.article_recommendations_patient = await patients.getArticle_recommendations_patient({
transaction
});
output.clinical_reports_patient = await patients.getClinical_reports_patient({
transaction
});
output.profile_photo = await patients.getProfile_photo({
transaction
});
output.account = await patients.getAccount({
transaction
});
output.primary_physician = await patients.getPrimary_physician({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userAccounts = (user && user.accounts?.id) || null;
if (userAccounts) {
if (options?.currentUser?.accountsId) {
where.accountsId = options.currentUser.accountsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.accounts,
as: 'account',
},
{
model: db.users,
as: 'primary_physician',
where: filter.primary_physician ? {
[Op.or]: [
{ id: { [Op.in]: filter.primary_physician.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.primary_physician.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.file,
as: 'profile_photo',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.patient_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'patients',
'patient_code',
filter.patient_code,
),
};
}
if (filter.first_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'patients',
'first_name',
filter.first_name,
),
};
}
if (filter.last_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'patients',
'last_name',
filter.last_name,
),
};
}
if (filter.medical_notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'patients',
'medical_notes',
filter.medical_notes,
),
};
}
if (filter.date_of_birthRange) {
const [start, end] = filter.date_of_birthRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
date_of_birth: {
...where.date_of_birth,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
date_of_birth: {
...where.date_of_birth,
[Op.lte]: end,
},
};
}
}
if (filter.diagnosis_dateRange) {
const [start, end] = filter.diagnosis_dateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
diagnosis_date: {
...where.diagnosis_date,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
diagnosis_date: {
...where.diagnosis_date,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.sex) {
where = {
...where,
sex: filter.sex,
};
}
if (filter.disease_stage) {
where = {
...where,
disease_stage: filter.disease_stage,
};
}
if (filter.account) {
const listItems = filter.account.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
accountId: {[Op.or]: listItems}
};
}
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,
},
};
}
}
}
if (globalAccess) {
delete where.accountsId;
}
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.patients.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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'patients',
'last_name',
query,
),
],
};
}
const records = await db.patients.findAll({
attributes: [ 'id', 'last_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['last_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.last_name,
}));
}
};

View File

@ -0,0 +1,355 @@
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 globalAccess = currentUser.app_role?.globalAccess;
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;
const user = (options && options.currentUser) || null;
const userAccounts = (user && user.accounts?.id) || null;
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,594 @@
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 RemindersDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const reminders = await db.reminders.create(
{
id: data.id || undefined,
channel: data.channel
||
null
,
scheduled_at: data.scheduled_at
||
null
,
state: data.state
||
null
,
message: data.message
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await reminders.setPatient( data.patient || null, {
transaction,
});
await reminders.setEvent( data.event || null, {
transaction,
});
await reminders.setRecipient_user( data.recipient_user || null, {
transaction,
});
await reminders.setAccounts( data.accounts || null, {
transaction,
});
return reminders;
}
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 remindersData = data.map((item, index) => ({
id: item.id || undefined,
channel: item.channel
||
null
,
scheduled_at: item.scheduled_at
||
null
,
state: item.state
||
null
,
message: item.message
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const reminders = await db.reminders.bulkCreate(remindersData, { transaction });
// For each item created, replace relation files
return reminders;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const reminders = await db.reminders.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.channel !== undefined) updatePayload.channel = data.channel;
if (data.scheduled_at !== undefined) updatePayload.scheduled_at = data.scheduled_at;
if (data.state !== undefined) updatePayload.state = data.state;
if (data.message !== undefined) updatePayload.message = data.message;
updatePayload.updatedById = currentUser.id;
await reminders.update(updatePayload, {transaction});
if (data.patient !== undefined) {
await reminders.setPatient(
data.patient,
{ transaction }
);
}
if (data.event !== undefined) {
await reminders.setEvent(
data.event,
{ transaction }
);
}
if (data.recipient_user !== undefined) {
await reminders.setRecipient_user(
data.recipient_user,
{ transaction }
);
}
if (data.accounts !== undefined) {
await reminders.setAccounts(
data.accounts,
{ transaction }
);
}
return reminders;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const reminders = await db.reminders.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of reminders) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of reminders) {
await record.destroy({transaction});
}
});
return reminders;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const reminders = await db.reminders.findByPk(id, options);
await reminders.update({
deletedBy: currentUser.id
}, {
transaction,
});
await reminders.destroy({
transaction
});
return reminders;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const reminders = await db.reminders.findOne(
{ where },
{ transaction },
);
if (!reminders) {
return reminders;
}
const output = reminders.get({plain: true});
output.patient = await reminders.getPatient({
transaction
});
output.event = await reminders.getEvent({
transaction
});
output.recipient_user = await reminders.getRecipient_user({
transaction
});
output.accounts = await reminders.getAccounts({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userAccounts = (user && user.accounts?.id) || null;
if (userAccounts) {
if (options?.currentUser?.accountsId) {
where.accountsId = options.currentUser.accountsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.patients,
as: 'patient',
where: filter.patient ? {
[Op.or]: [
{ id: { [Op.in]: filter.patient.split('|').map(term => Utils.uuid(term)) } },
{
last_name: {
[Op.or]: filter.patient.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.calendar_events,
as: 'event',
where: filter.event ? {
[Op.or]: [
{ id: { [Op.in]: filter.event.split('|').map(term => Utils.uuid(term)) } },
{
title_text: {
[Op.or]: filter.event.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'recipient_user',
where: filter.recipient_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.recipient_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.recipient_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.accounts,
as: 'accounts',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.message) {
where = {
...where,
[Op.and]: Utils.ilike(
'reminders',
'message',
filter.message,
),
};
}
if (filter.scheduled_atRange) {
const [start, end] = filter.scheduled_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
scheduled_at: {
...where.scheduled_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
scheduled_at: {
...where.scheduled_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.channel) {
where = {
...where,
channel: filter.channel,
};
}
if (filter.state) {
where = {
...where,
state: filter.state,
};
}
if (filter.accounts) {
const listItems = filter.accounts.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
accountsId: {[Op.or]: listItems}
};
}
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,
},
};
}
}
}
if (globalAccess) {
delete where.accountsId;
}
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.reminders.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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'reminders',
'channel',
query,
),
],
};
}
const records = await db.reminders.findAll({
attributes: [ 'id', 'channel' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['channel', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.channel,
}));
}
};

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

@ -0,0 +1,457 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const config = require('../../config');
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
,
globalAccess: data.globalAccess
||
false
,
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
,
globalAccess: item.globalAccess
||
false
,
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 globalAccess = currentUser.app_role?.globalAccess;
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;
if (data.globalAccess !== undefined) updatePayload.globalAccess = data.globalAccess;
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,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userAccounts = (user && user.accounts?.id) || null;
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.globalAccess) {
where = {
...where,
globalAccess: filter.globalAccess,
};
}
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,
},
};
}
}
}
if (!globalAccess) {
where = { name: { [Op.ne]: config.roles.super_admin } };
}
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, globalAccess,) {
let where = {};
if (!globalAccess) {
where = { name: { [Op.ne]: config.roles.super_admin } };
}
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,690 @@
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 Scientific_articlesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const scientific_articles = await db.scientific_articles.create(
{
id: data.id || undefined,
title_text: data.title_text
||
null
,
abstract_text: data.abstract_text
||
null
,
journal: data.journal
||
null
,
published_at: data.published_at
||
null
,
doi: data.doi
||
null
,
url: data.url
||
null
,
keywords: data.keywords
||
null
,
validation_status: data.validation_status
||
null
,
validation_notes: data.validation_notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await scientific_articles.setValidated_by_user( data.validated_by_user || null, {
transaction,
});
await scientific_articles.setAccounts( data.accounts || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.scientific_articles.getTableName(),
belongsToColumn: 'pdf_file',
belongsToId: scientific_articles.id,
},
data.pdf_file,
options,
);
return scientific_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 scientific_articlesData = data.map((item, index) => ({
id: item.id || undefined,
title_text: item.title_text
||
null
,
abstract_text: item.abstract_text
||
null
,
journal: item.journal
||
null
,
published_at: item.published_at
||
null
,
doi: item.doi
||
null
,
url: item.url
||
null
,
keywords: item.keywords
||
null
,
validation_status: item.validation_status
||
null
,
validation_notes: item.validation_notes
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const scientific_articles = await db.scientific_articles.bulkCreate(scientific_articlesData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < scientific_articles.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.scientific_articles.getTableName(),
belongsToColumn: 'pdf_file',
belongsToId: scientific_articles[i].id,
},
data[i].pdf_file,
options,
);
}
return scientific_articles;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const scientific_articles = await db.scientific_articles.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.title_text !== undefined) updatePayload.title_text = data.title_text;
if (data.abstract_text !== undefined) updatePayload.abstract_text = data.abstract_text;
if (data.journal !== undefined) updatePayload.journal = data.journal;
if (data.published_at !== undefined) updatePayload.published_at = data.published_at;
if (data.doi !== undefined) updatePayload.doi = data.doi;
if (data.url !== undefined) updatePayload.url = data.url;
if (data.keywords !== undefined) updatePayload.keywords = data.keywords;
if (data.validation_status !== undefined) updatePayload.validation_status = data.validation_status;
if (data.validation_notes !== undefined) updatePayload.validation_notes = data.validation_notes;
updatePayload.updatedById = currentUser.id;
await scientific_articles.update(updatePayload, {transaction});
if (data.validated_by_user !== undefined) {
await scientific_articles.setValidated_by_user(
data.validated_by_user,
{ transaction }
);
}
if (data.accounts !== undefined) {
await scientific_articles.setAccounts(
data.accounts,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.scientific_articles.getTableName(),
belongsToColumn: 'pdf_file',
belongsToId: scientific_articles.id,
},
data.pdf_file,
options,
);
return scientific_articles;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const scientific_articles = await db.scientific_articles.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of scientific_articles) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of scientific_articles) {
await record.destroy({transaction});
}
});
return scientific_articles;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const scientific_articles = await db.scientific_articles.findByPk(id, options);
await scientific_articles.update({
deletedBy: currentUser.id
}, {
transaction,
});
await scientific_articles.destroy({
transaction
});
return scientific_articles;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const scientific_articles = await db.scientific_articles.findOne(
{ where },
{ transaction },
);
if (!scientific_articles) {
return scientific_articles;
}
const output = scientific_articles.get({plain: true});
output.article_recommendations_article = await scientific_articles.getArticle_recommendations_article({
transaction
});
output.validated_by_user = await scientific_articles.getValidated_by_user({
transaction
});
output.pdf_file = await scientific_articles.getPdf_file({
transaction
});
output.accounts = await scientific_articles.getAccounts({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userAccounts = (user && user.accounts?.id) || null;
if (userAccounts) {
if (options?.currentUser?.accountsId) {
where.accountsId = options.currentUser.accountsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.users,
as: 'validated_by_user',
where: filter.validated_by_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.validated_by_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.validated_by_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.accounts,
as: 'accounts',
},
{
model: db.file,
as: 'pdf_file',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.title_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'scientific_articles',
'title_text',
filter.title_text,
),
};
}
if (filter.abstract_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'scientific_articles',
'abstract_text',
filter.abstract_text,
),
};
}
if (filter.journal) {
where = {
...where,
[Op.and]: Utils.ilike(
'scientific_articles',
'journal',
filter.journal,
),
};
}
if (filter.doi) {
where = {
...where,
[Op.and]: Utils.ilike(
'scientific_articles',
'doi',
filter.doi,
),
};
}
if (filter.url) {
where = {
...where,
[Op.and]: Utils.ilike(
'scientific_articles',
'url',
filter.url,
),
};
}
if (filter.keywords) {
where = {
...where,
[Op.and]: Utils.ilike(
'scientific_articles',
'keywords',
filter.keywords,
),
};
}
if (filter.validation_notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'scientific_articles',
'validation_notes',
filter.validation_notes,
),
};
}
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.validation_status) {
where = {
...where,
validation_status: filter.validation_status,
};
}
if (filter.accounts) {
const listItems = filter.accounts.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
accountsId: {[Op.or]: listItems}
};
}
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,
},
};
}
}
}
if (globalAccess) {
delete where.accountsId;
}
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.scientific_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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'scientific_articles',
'title_text',
query,
),
],
};
}
const records = await db.scientific_articles.findAll({
attributes: [ 'id', 'title_text' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['title_text', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.title_text,
}));
}
};

View File

@ -0,0 +1,665 @@
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 Shared_dashboard_postsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const shared_dashboard_posts = await db.shared_dashboard_posts.create(
{
id: data.id || undefined,
post_type: data.post_type
||
null
,
title_text: data.title_text
||
null
,
content: data.content
||
null
,
posted_at: data.posted_at
||
null
,
visibility: data.visibility
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await shared_dashboard_posts.setPatient( data.patient || null, {
transaction,
});
await shared_dashboard_posts.setAuthor_user( data.author_user || null, {
transaction,
});
await shared_dashboard_posts.setAccounts( data.accounts || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.shared_dashboard_posts.getTableName(),
belongsToColumn: 'photos',
belongsToId: shared_dashboard_posts.id,
},
data.photos,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.shared_dashboard_posts.getTableName(),
belongsToColumn: 'attachments',
belongsToId: shared_dashboard_posts.id,
},
data.attachments,
options,
);
return shared_dashboard_posts;
}
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 shared_dashboard_postsData = data.map((item, index) => ({
id: item.id || undefined,
post_type: item.post_type
||
null
,
title_text: item.title_text
||
null
,
content: item.content
||
null
,
posted_at: item.posted_at
||
null
,
visibility: item.visibility
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const shared_dashboard_posts = await db.shared_dashboard_posts.bulkCreate(shared_dashboard_postsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < shared_dashboard_posts.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.shared_dashboard_posts.getTableName(),
belongsToColumn: 'photos',
belongsToId: shared_dashboard_posts[i].id,
},
data[i].photos,
options,
);
}
for (let i = 0; i < shared_dashboard_posts.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.shared_dashboard_posts.getTableName(),
belongsToColumn: 'attachments',
belongsToId: shared_dashboard_posts[i].id,
},
data[i].attachments,
options,
);
}
return shared_dashboard_posts;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const shared_dashboard_posts = await db.shared_dashboard_posts.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.post_type !== undefined) updatePayload.post_type = data.post_type;
if (data.title_text !== undefined) updatePayload.title_text = data.title_text;
if (data.content !== undefined) updatePayload.content = data.content;
if (data.posted_at !== undefined) updatePayload.posted_at = data.posted_at;
if (data.visibility !== undefined) updatePayload.visibility = data.visibility;
updatePayload.updatedById = currentUser.id;
await shared_dashboard_posts.update(updatePayload, {transaction});
if (data.patient !== undefined) {
await shared_dashboard_posts.setPatient(
data.patient,
{ transaction }
);
}
if (data.author_user !== undefined) {
await shared_dashboard_posts.setAuthor_user(
data.author_user,
{ transaction }
);
}
if (data.accounts !== undefined) {
await shared_dashboard_posts.setAccounts(
data.accounts,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.shared_dashboard_posts.getTableName(),
belongsToColumn: 'photos',
belongsToId: shared_dashboard_posts.id,
},
data.photos,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.shared_dashboard_posts.getTableName(),
belongsToColumn: 'attachments',
belongsToId: shared_dashboard_posts.id,
},
data.attachments,
options,
);
return shared_dashboard_posts;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const shared_dashboard_posts = await db.shared_dashboard_posts.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of shared_dashboard_posts) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of shared_dashboard_posts) {
await record.destroy({transaction});
}
});
return shared_dashboard_posts;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const shared_dashboard_posts = await db.shared_dashboard_posts.findByPk(id, options);
await shared_dashboard_posts.update({
deletedBy: currentUser.id
}, {
transaction,
});
await shared_dashboard_posts.destroy({
transaction
});
return shared_dashboard_posts;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const shared_dashboard_posts = await db.shared_dashboard_posts.findOne(
{ where },
{ transaction },
);
if (!shared_dashboard_posts) {
return shared_dashboard_posts;
}
const output = shared_dashboard_posts.get({plain: true});
output.patient = await shared_dashboard_posts.getPatient({
transaction
});
output.author_user = await shared_dashboard_posts.getAuthor_user({
transaction
});
output.photos = await shared_dashboard_posts.getPhotos({
transaction
});
output.attachments = await shared_dashboard_posts.getAttachments({
transaction
});
output.accounts = await shared_dashboard_posts.getAccounts({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userAccounts = (user && user.accounts?.id) || null;
if (userAccounts) {
if (options?.currentUser?.accountsId) {
where.accountsId = options.currentUser.accountsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.patients,
as: 'patient',
where: filter.patient ? {
[Op.or]: [
{ id: { [Op.in]: filter.patient.split('|').map(term => Utils.uuid(term)) } },
{
last_name: {
[Op.or]: filter.patient.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'author_user',
where: filter.author_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.author_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.author_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.accounts,
as: 'accounts',
},
{
model: db.file,
as: 'photos',
},
{
model: db.file,
as: 'attachments',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.title_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'shared_dashboard_posts',
'title_text',
filter.title_text,
),
};
}
if (filter.content) {
where = {
...where,
[Op.and]: Utils.ilike(
'shared_dashboard_posts',
'content',
filter.content,
),
};
}
if (filter.posted_atRange) {
const [start, end] = filter.posted_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
posted_at: {
...where.posted_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
posted_at: {
...where.posted_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.post_type) {
where = {
...where,
post_type: filter.post_type,
};
}
if (filter.visibility) {
where = {
...where,
visibility: filter.visibility,
};
}
if (filter.accounts) {
const listItems = filter.accounts.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
accountsId: {[Op.or]: listItems}
};
}
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,
},
};
}
}
}
if (globalAccess) {
delete where.accountsId;
}
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.shared_dashboard_posts.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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'shared_dashboard_posts',
'title_text',
query,
),
],
};
}
const records = await db.shared_dashboard_posts.findAll({
attributes: [ 'id', 'title_text' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['title_text', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.title_text,
}));
}
};

View File

@ -0,0 +1,618 @@
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 Stage_assessmentsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const stage_assessments = await db.stage_assessments.create(
{
id: data.id || undefined,
assessed_at: data.assessed_at
||
null
,
predicted_stage: data.predicted_stage
||
null
,
confidence_score: data.confidence_score
||
null
,
method: data.method
||
null
,
model_version: data.model_version
||
null
,
explanation: data.explanation
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await stage_assessments.setPatient( data.patient || null, {
transaction,
});
await stage_assessments.setReviewed_by_user( data.reviewed_by_user || null, {
transaction,
});
await stage_assessments.setAccounts( data.accounts || null, {
transaction,
});
return stage_assessments;
}
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 stage_assessmentsData = data.map((item, index) => ({
id: item.id || undefined,
assessed_at: item.assessed_at
||
null
,
predicted_stage: item.predicted_stage
||
null
,
confidence_score: item.confidence_score
||
null
,
method: item.method
||
null
,
model_version: item.model_version
||
null
,
explanation: item.explanation
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const stage_assessments = await db.stage_assessments.bulkCreate(stage_assessmentsData, { transaction });
// For each item created, replace relation files
return stage_assessments;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const stage_assessments = await db.stage_assessments.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.assessed_at !== undefined) updatePayload.assessed_at = data.assessed_at;
if (data.predicted_stage !== undefined) updatePayload.predicted_stage = data.predicted_stage;
if (data.confidence_score !== undefined) updatePayload.confidence_score = data.confidence_score;
if (data.method !== undefined) updatePayload.method = data.method;
if (data.model_version !== undefined) updatePayload.model_version = data.model_version;
if (data.explanation !== undefined) updatePayload.explanation = data.explanation;
updatePayload.updatedById = currentUser.id;
await stage_assessments.update(updatePayload, {transaction});
if (data.patient !== undefined) {
await stage_assessments.setPatient(
data.patient,
{ transaction }
);
}
if (data.reviewed_by_user !== undefined) {
await stage_assessments.setReviewed_by_user(
data.reviewed_by_user,
{ transaction }
);
}
if (data.accounts !== undefined) {
await stage_assessments.setAccounts(
data.accounts,
{ transaction }
);
}
return stage_assessments;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const stage_assessments = await db.stage_assessments.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of stage_assessments) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of stage_assessments) {
await record.destroy({transaction});
}
});
return stage_assessments;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const stage_assessments = await db.stage_assessments.findByPk(id, options);
await stage_assessments.update({
deletedBy: currentUser.id
}, {
transaction,
});
await stage_assessments.destroy({
transaction
});
return stage_assessments;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const stage_assessments = await db.stage_assessments.findOne(
{ where },
{ transaction },
);
if (!stage_assessments) {
return stage_assessments;
}
const output = stage_assessments.get({plain: true});
output.patient = await stage_assessments.getPatient({
transaction
});
output.reviewed_by_user = await stage_assessments.getReviewed_by_user({
transaction
});
output.accounts = await stage_assessments.getAccounts({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userAccounts = (user && user.accounts?.id) || null;
if (userAccounts) {
if (options?.currentUser?.accountsId) {
where.accountsId = options.currentUser.accountsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.patients,
as: 'patient',
where: filter.patient ? {
[Op.or]: [
{ id: { [Op.in]: filter.patient.split('|').map(term => Utils.uuid(term)) } },
{
last_name: {
[Op.or]: filter.patient.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'reviewed_by_user',
where: filter.reviewed_by_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.reviewed_by_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.reviewed_by_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.accounts,
as: 'accounts',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.model_version) {
where = {
...where,
[Op.and]: Utils.ilike(
'stage_assessments',
'model_version',
filter.model_version,
),
};
}
if (filter.explanation) {
where = {
...where,
[Op.and]: Utils.ilike(
'stage_assessments',
'explanation',
filter.explanation,
),
};
}
if (filter.assessed_atRange) {
const [start, end] = filter.assessed_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
assessed_at: {
...where.assessed_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
assessed_at: {
...where.assessed_at,
[Op.lte]: end,
},
};
}
}
if (filter.confidence_scoreRange) {
const [start, end] = filter.confidence_scoreRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
confidence_score: {
...where.confidence_score,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
confidence_score: {
...where.confidence_score,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.predicted_stage) {
where = {
...where,
predicted_stage: filter.predicted_stage,
};
}
if (filter.method) {
where = {
...where,
method: filter.method,
};
}
if (filter.accounts) {
const listItems = filter.accounts.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
accountsId: {[Op.or]: listItems}
};
}
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,
},
};
}
}
}
if (globalAccess) {
delete where.accountsId;
}
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.stage_assessments.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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'stage_assessments',
'model_version',
query,
),
],
};
}
const records = await db.stage_assessments.findAll({
attributes: [ 'id', 'model_version' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['model_version', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.model_version,
}));
}
};

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

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,618 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Voice_assistant_sessionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const voice_assistant_sessions = await db.voice_assistant_sessions.create(
{
id: data.id || undefined,
started_at: data.started_at
||
null
,
ended_at: data.ended_at
||
null
,
channel: data.channel
||
null
,
transcript: data.transcript
||
null
,
assistant_summary: data.assistant_summary
||
null
,
outcome: data.outcome
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await voice_assistant_sessions.setPatient( data.patient || null, {
transaction,
});
await voice_assistant_sessions.setInitiated_by_user( data.initiated_by_user || null, {
transaction,
});
await voice_assistant_sessions.setAccounts( data.accounts || null, {
transaction,
});
return voice_assistant_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 voice_assistant_sessionsData = data.map((item, index) => ({
id: item.id || undefined,
started_at: item.started_at
||
null
,
ended_at: item.ended_at
||
null
,
channel: item.channel
||
null
,
transcript: item.transcript
||
null
,
assistant_summary: item.assistant_summary
||
null
,
outcome: item.outcome
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const voice_assistant_sessions = await db.voice_assistant_sessions.bulkCreate(voice_assistant_sessionsData, { transaction });
// For each item created, replace relation files
return voice_assistant_sessions;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const voice_assistant_sessions = await db.voice_assistant_sessions.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
if (data.ended_at !== undefined) updatePayload.ended_at = data.ended_at;
if (data.channel !== undefined) updatePayload.channel = data.channel;
if (data.transcript !== undefined) updatePayload.transcript = data.transcript;
if (data.assistant_summary !== undefined) updatePayload.assistant_summary = data.assistant_summary;
if (data.outcome !== undefined) updatePayload.outcome = data.outcome;
updatePayload.updatedById = currentUser.id;
await voice_assistant_sessions.update(updatePayload, {transaction});
if (data.patient !== undefined) {
await voice_assistant_sessions.setPatient(
data.patient,
{ transaction }
);
}
if (data.initiated_by_user !== undefined) {
await voice_assistant_sessions.setInitiated_by_user(
data.initiated_by_user,
{ transaction }
);
}
if (data.accounts !== undefined) {
await voice_assistant_sessions.setAccounts(
data.accounts,
{ transaction }
);
}
return voice_assistant_sessions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const voice_assistant_sessions = await db.voice_assistant_sessions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of voice_assistant_sessions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of voice_assistant_sessions) {
await record.destroy({transaction});
}
});
return voice_assistant_sessions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const voice_assistant_sessions = await db.voice_assistant_sessions.findByPk(id, options);
await voice_assistant_sessions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await voice_assistant_sessions.destroy({
transaction
});
return voice_assistant_sessions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const voice_assistant_sessions = await db.voice_assistant_sessions.findOne(
{ where },
{ transaction },
);
if (!voice_assistant_sessions) {
return voice_assistant_sessions;
}
const output = voice_assistant_sessions.get({plain: true});
output.patient = await voice_assistant_sessions.getPatient({
transaction
});
output.initiated_by_user = await voice_assistant_sessions.getInitiated_by_user({
transaction
});
output.accounts = await voice_assistant_sessions.getAccounts({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userAccounts = (user && user.accounts?.id) || null;
if (userAccounts) {
if (options?.currentUser?.accountsId) {
where.accountsId = options.currentUser.accountsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.patients,
as: 'patient',
where: filter.patient ? {
[Op.or]: [
{ id: { [Op.in]: filter.patient.split('|').map(term => Utils.uuid(term)) } },
{
last_name: {
[Op.or]: filter.patient.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'initiated_by_user',
where: filter.initiated_by_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.initiated_by_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.initiated_by_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.accounts,
as: 'accounts',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.transcript) {
where = {
...where,
[Op.and]: Utils.ilike(
'voice_assistant_sessions',
'transcript',
filter.transcript,
),
};
}
if (filter.assistant_summary) {
where = {
...where,
[Op.and]: Utils.ilike(
'voice_assistant_sessions',
'assistant_summary',
filter.assistant_summary,
),
};
}
if (filter.started_atRange) {
const [start, end] = filter.started_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
started_at: {
...where.started_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
started_at: {
...where.started_at,
[Op.lte]: end,
},
};
}
}
if (filter.ended_atRange) {
const [start, end] = filter.ended_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
ended_at: {
...where.ended_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
ended_at: {
...where.ended_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.channel) {
where = {
...where,
channel: filter.channel,
};
}
if (filter.outcome) {
where = {
...where,
outcome: filter.outcome,
};
}
if (filter.accounts) {
const listItems = filter.accounts.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
accountsId: {[Op.or]: listItems}
};
}
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,
},
};
}
}
}
if (globalAccess) {
delete where.accountsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.voice_assistant_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, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'voice_assistant_sessions',
'outcome',
query,
),
],
};
}
const records = await db.voice_assistant_sessions.findAll({
attributes: [ 'id', 'outcome' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['outcome', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.outcome,
}));
}
};

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

File diff suppressed because it is too large Load Diff

View File

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

View File

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

View File

@ -0,0 +1,275 @@
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 accounts = sequelize.define(
'accounts',
{
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,
},
);
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.accounts.hasMany(db.users, {
as: 'users_accounts',
foreignKey: {
name: 'accountsId',
},
constraints: false,
});
db.accounts.hasMany(db.patients, {
as: 'patients_account',
foreignKey: {
name: 'accountId',
},
constraints: false,
});
db.accounts.hasMany(db.patient_access_grants, {
as: 'patient_access_grants_accounts',
foreignKey: {
name: 'accountsId',
},
constraints: false,
});
db.accounts.hasMany(db.medications, {
as: 'medications_accounts',
foreignKey: {
name: 'accountsId',
},
constraints: false,
});
db.accounts.hasMany(db.medication_schedules, {
as: 'medication_schedules_accounts',
foreignKey: {
name: 'accountsId',
},
constraints: false,
});
db.accounts.hasMany(db.calendar_events, {
as: 'calendar_events_accounts',
foreignKey: {
name: 'accountsId',
},
constraints: false,
});
db.accounts.hasMany(db.reminders, {
as: 'reminders_accounts',
foreignKey: {
name: 'accountsId',
},
constraints: false,
});
db.accounts.hasMany(db.cognitive_programs, {
as: 'cognitive_programs_accounts',
foreignKey: {
name: 'accountsId',
},
constraints: false,
});
db.accounts.hasMany(db.cognitive_exercises, {
as: 'cognitive_exercises_accounts',
foreignKey: {
name: 'accountsId',
},
constraints: false,
});
db.accounts.hasMany(db.cognitive_sessions, {
as: 'cognitive_sessions_accounts',
foreignKey: {
name: 'accountsId',
},
constraints: false,
});
db.accounts.hasMany(db.cognitive_attempts, {
as: 'cognitive_attempts_accounts',
foreignKey: {
name: 'accountsId',
},
constraints: false,
});
db.accounts.hasMany(db.stage_assessments, {
as: 'stage_assessments_accounts',
foreignKey: {
name: 'accountsId',
},
constraints: false,
});
db.accounts.hasMany(db.voice_assistant_sessions, {
as: 'voice_assistant_sessions_accounts',
foreignKey: {
name: 'accountsId',
},
constraints: false,
});
db.accounts.hasMany(db.iot_devices, {
as: 'iot_devices_accounts',
foreignKey: {
name: 'accountsId',
},
constraints: false,
});
db.accounts.hasMany(db.iot_telemetry_events, {
as: 'iot_telemetry_events_accounts',
foreignKey: {
name: 'accountsId',
},
constraints: false,
});
db.accounts.hasMany(db.geofences, {
as: 'geofences_accounts',
foreignKey: {
name: 'accountsId',
},
constraints: false,
});
db.accounts.hasMany(db.alerts, {
as: 'alerts_accounts',
foreignKey: {
name: 'accountsId',
},
constraints: false,
});
db.accounts.hasMany(db.alert_notifications, {
as: 'alert_notifications_accounts',
foreignKey: {
name: 'accountsId',
},
constraints: false,
});
db.accounts.hasMany(db.shared_dashboard_posts, {
as: 'shared_dashboard_posts_accounts',
foreignKey: {
name: 'accountsId',
},
constraints: false,
});
db.accounts.hasMany(db.scientific_articles, {
as: 'scientific_articles_accounts',
foreignKey: {
name: 'accountsId',
},
constraints: false,
});
db.accounts.hasMany(db.article_recommendations, {
as: 'article_recommendations_accounts',
foreignKey: {
name: 'accountsId',
},
constraints: false,
});
db.accounts.hasMany(db.clinical_reports, {
as: 'clinical_reports_accounts',
foreignKey: {
name: 'accountsId',
},
constraints: false,
});
db.accounts.hasMany(db.admin_metrics_snapshots, {
as: 'admin_metrics_snapshots_accounts',
foreignKey: {
name: 'accountsId',
},
constraints: false,
});
//end loop
db.accounts.belongsTo(db.users, {
as: 'createdBy',
});
db.accounts.belongsTo(db.users, {
as: 'updatedBy',
});
};
return accounts;
};

View File

@ -0,0 +1,155 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const admin_metrics_snapshots = sequelize.define(
'admin_metrics_snapshots',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
snapshot_at: {
type: DataTypes.DATE,
},
total_accounts: {
type: DataTypes.INTEGER,
},
total_users: {
type: DataTypes.INTEGER,
},
total_patients: {
type: DataTypes.INTEGER,
},
active_devices: {
type: DataTypes.INTEGER,
},
alerts_last_24h: {
type: DataTypes.INTEGER,
},
cognitive_sessions_last_7d: {
type: DataTypes.INTEGER,
},
reminders_sent_last_24h: {
type: DataTypes.INTEGER,
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
admin_metrics_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.admin_metrics_snapshots.belongsTo(db.accounts, {
as: 'accounts',
foreignKey: {
name: 'accountsId',
},
constraints: false,
});
db.admin_metrics_snapshots.belongsTo(db.users, {
as: 'createdBy',
});
db.admin_metrics_snapshots.belongsTo(db.users, {
as: 'updatedBy',
});
};
return admin_metrics_snapshots;
};

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 alert_notifications = sequelize.define(
'alert_notifications',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
channel: {
type: DataTypes.ENUM,
values: [
"push",
"sms",
"email",
"voice"
],
},
sent_at: {
type: DataTypes.DATE,
},
delivery_status: {
type: DataTypes.ENUM,
values: [
"pending",
"sent",
"delivered",
"failed"
],
},
provider_message_id: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
alert_notifications.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.alert_notifications.belongsTo(db.alerts, {
as: 'alert',
foreignKey: {
name: 'alertId',
},
constraints: false,
});
db.alert_notifications.belongsTo(db.users, {
as: 'recipient_user',
foreignKey: {
name: 'recipient_userId',
},
constraints: false,
});
db.alert_notifications.belongsTo(db.accounts, {
as: 'accounts',
foreignKey: {
name: 'accountsId',
},
constraints: false,
});
db.alert_notifications.belongsTo(db.users, {
as: 'createdBy',
});
db.alert_notifications.belongsTo(db.users, {
as: 'updatedBy',
});
};
return alert_notifications;
};

View File

@ -0,0 +1,242 @@
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 alerts = sequelize.define(
'alerts',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
alert_type: {
type: DataTypes.ENUM,
values: [
"wandering",
"geofence_breach",
"panic",
"fall_suspected",
"missed_medication",
"device_offline",
"other"
],
},
severity: {
type: DataTypes.ENUM,
values: [
"low",
"medium",
"high",
"critical"
],
},
title_text: {
type: DataTypes.TEXT,
},
details: {
type: DataTypes.TEXT,
},
triggered_at: {
type: DataTypes.DATE,
},
status: {
type: DataTypes.ENUM,
values: [
"open",
"acknowledged",
"resolved",
"dismissed"
],
},
acknowledged_at: {
type: DataTypes.DATE,
},
resolved_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
alerts.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.alerts.hasMany(db.alert_notifications, {
as: 'alert_notifications_alert',
foreignKey: {
name: 'alertId',
},
constraints: false,
});
//end loop
db.alerts.belongsTo(db.patients, {
as: 'patient',
foreignKey: {
name: 'patientId',
},
constraints: false,
});
db.alerts.belongsTo(db.iot_devices, {
as: 'device',
foreignKey: {
name: 'deviceId',
},
constraints: false,
});
db.alerts.belongsTo(db.iot_telemetry_events, {
as: 'trigger_event',
foreignKey: {
name: 'trigger_eventId',
},
constraints: false,
});
db.alerts.belongsTo(db.users, {
as: 'assigned_to_user',
foreignKey: {
name: 'assigned_to_userId',
},
constraints: false,
});
db.alerts.belongsTo(db.accounts, {
as: 'accounts',
foreignKey: {
name: 'accountsId',
},
constraints: false,
});
db.alerts.belongsTo(db.users, {
as: 'createdBy',
});
db.alerts.belongsTo(db.users, {
as: 'updatedBy',
});
};
return alerts;
};

View File

@ -0,0 +1,169 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const article_recommendations = sequelize.define(
'article_recommendations',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
recommended_at: {
type: DataTypes.DATE,
},
reason_type: {
type: DataTypes.ENUM,
values: [
"stage_based",
"symptom_based",
"caregiver_interest",
"clinician_selected",
"trending"
],
},
reason_text: {
type: DataTypes.TEXT,
},
state: {
type: DataTypes.ENUM,
values: [
"new",
"viewed",
"saved",
"dismissed"
],
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
article_recommendations.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_recommendations.belongsTo(db.patients, {
as: 'patient',
foreignKey: {
name: 'patientId',
},
constraints: false,
});
db.article_recommendations.belongsTo(db.scientific_articles, {
as: 'article',
foreignKey: {
name: 'articleId',
},
constraints: false,
});
db.article_recommendations.belongsTo(db.accounts, {
as: 'accounts',
foreignKey: {
name: 'accountsId',
},
constraints: false,
});
db.article_recommendations.belongsTo(db.users, {
as: 'createdBy',
});
db.article_recommendations.belongsTo(db.users, {
as: 'updatedBy',
});
};
return article_recommendations;
};

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 calendar_events = sequelize.define(
'calendar_events',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
event_type: {
type: DataTypes.ENUM,
values: [
"medication",
"appointment",
"cognitive_session",
"care_task",
"family_note",
"other"
],
},
title_text: {
type: DataTypes.TEXT,
},
description: {
type: DataTypes.TEXT,
},
start_at: {
type: DataTypes.DATE,
},
end_at: {
type: DataTypes.DATE,
},
location_text: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"scheduled",
"completed",
"cancelled"
],
},
has_reminder: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
reminder_minutes_before: {
type: DataTypes.INTEGER,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
calendar_events.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.calendar_events.hasMany(db.reminders, {
as: 'reminders_event',
foreignKey: {
name: 'eventId',
},
constraints: false,
});
//end loop
db.calendar_events.belongsTo(db.patients, {
as: 'patient',
foreignKey: {
name: 'patientId',
},
constraints: false,
});
db.calendar_events.belongsTo(db.users, {
as: 'created_by_user',
foreignKey: {
name: 'created_by_userId',
},
constraints: false,
});
db.calendar_events.belongsTo(db.medications, {
as: 'linked_medication',
foreignKey: {
name: 'linked_medicationId',
},
constraints: false,
});
db.calendar_events.belongsTo(db.accounts, {
as: 'accounts',
foreignKey: {
name: 'accountsId',
},
constraints: false,
});
db.calendar_events.belongsTo(db.users, {
as: 'createdBy',
});
db.calendar_events.belongsTo(db.users, {
as: 'updatedBy',
});
};
return calendar_events;
};

View File

@ -0,0 +1,165 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const clinical_reports = sequelize.define(
'clinical_reports',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
period_start_at: {
type: DataTypes.DATE,
},
period_end_at: {
type: DataTypes.DATE,
},
report_title: {
type: DataTypes.TEXT,
},
summary: {
type: DataTypes.TEXT,
},
share_scope: {
type: DataTypes.ENUM,
values: [
"family",
"clinicians",
"admin"
],
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
clinical_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.clinical_reports.belongsTo(db.patients, {
as: 'patient',
foreignKey: {
name: 'patientId',
},
constraints: false,
});
db.clinical_reports.belongsTo(db.users, {
as: 'generated_by_user',
foreignKey: {
name: 'generated_by_userId',
},
constraints: false,
});
db.clinical_reports.belongsTo(db.accounts, {
as: 'accounts',
foreignKey: {
name: 'accountsId',
},
constraints: false,
});
db.clinical_reports.hasMany(db.file, {
as: 'report_file',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.clinical_reports.getTableName(),
belongsToColumn: 'report_file',
},
});
db.clinical_reports.belongsTo(db.users, {
as: 'createdBy',
});
db.clinical_reports.belongsTo(db.users, {
as: 'updatedBy',
});
};
return clinical_reports;
};

View File

@ -0,0 +1,162 @@
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 cognitive_attempts = sequelize.define(
'cognitive_attempts',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
attempted_at: {
type: DataTypes.DATE,
},
score: {
type: DataTypes.DECIMAL,
},
accuracy: {
type: DataTypes.DECIMAL,
},
duration_seconds: {
type: DataTypes.INTEGER,
},
result: {
type: DataTypes.ENUM,
values: [
"success",
"partial",
"failed"
],
},
raw_response: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
cognitive_attempts.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.cognitive_attempts.belongsTo(db.cognitive_sessions, {
as: 'session',
foreignKey: {
name: 'sessionId',
},
constraints: false,
});
db.cognitive_attempts.belongsTo(db.cognitive_exercises, {
as: 'exercise',
foreignKey: {
name: 'exerciseId',
},
constraints: false,
});
db.cognitive_attempts.belongsTo(db.accounts, {
as: 'accounts',
foreignKey: {
name: 'accountsId',
},
constraints: false,
});
db.cognitive_attempts.belongsTo(db.users, {
as: 'createdBy',
});
db.cognitive_attempts.belongsTo(db.users, {
as: 'updatedBy',
});
};
return cognitive_attempts;
};

View File

@ -0,0 +1,196 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const cognitive_exercises = sequelize.define(
'cognitive_exercises',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
exercise_name: {
type: DataTypes.TEXT,
},
exercise_type: {
type: DataTypes.ENUM,
values: [
"memory",
"attention",
"language",
"orientation",
"executive_function"
],
},
instructions: {
type: DataTypes.TEXT,
},
difficulty_level: {
type: DataTypes.ENUM,
values: [
"easy",
"medium",
"hard",
"adaptive"
],
},
max_score: {
type: DataTypes.INTEGER,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
cognitive_exercises.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.cognitive_exercises.hasMany(db.cognitive_attempts, {
as: 'cognitive_attempts_exercise',
foreignKey: {
name: 'exerciseId',
},
constraints: false,
});
//end loop
db.cognitive_exercises.belongsTo(db.cognitive_programs, {
as: 'program',
foreignKey: {
name: 'programId',
},
constraints: false,
});
db.cognitive_exercises.belongsTo(db.accounts, {
as: 'accounts',
foreignKey: {
name: 'accountsId',
},
constraints: false,
});
db.cognitive_exercises.hasMany(db.file, {
as: 'assets',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.cognitive_exercises.getTableName(),
belongsToColumn: 'assets',
},
});
db.cognitive_exercises.belongsTo(db.users, {
as: 'createdBy',
});
db.cognitive_exercises.belongsTo(db.users, {
as: 'updatedBy',
});
};
return cognitive_exercises;
};

View File

@ -0,0 +1,178 @@
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 cognitive_programs = sequelize.define(
'cognitive_programs',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
program_name: {
type: DataTypes.TEXT,
},
description: {
type: DataTypes.TEXT,
},
target_stage: {
type: DataTypes.ENUM,
values: [
"mild",
"moderate",
"severe",
"all"
],
},
status: {
type: DataTypes.ENUM,
values: [
"draft",
"published",
"archived"
],
},
estimated_minutes: {
type: DataTypes.INTEGER,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
cognitive_programs.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.cognitive_programs.hasMany(db.cognitive_exercises, {
as: 'cognitive_exercises_program',
foreignKey: {
name: 'programId',
},
constraints: false,
});
db.cognitive_programs.hasMany(db.cognitive_sessions, {
as: 'cognitive_sessions_program',
foreignKey: {
name: 'programId',
},
constraints: false,
});
//end loop
db.cognitive_programs.belongsTo(db.users, {
as: 'created_by_user',
foreignKey: {
name: 'created_by_userId',
},
constraints: false,
});
db.cognitive_programs.belongsTo(db.accounts, {
as: 'accounts',
foreignKey: {
name: 'accountsId',
},
constraints: false,
});
db.cognitive_programs.belongsTo(db.users, {
as: 'createdBy',
});
db.cognitive_programs.belongsTo(db.users, {
as: 'updatedBy',
});
};
return cognitive_programs;
};

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 cognitive_sessions = sequelize.define(
'cognitive_sessions',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
started_at: {
type: DataTypes.DATE,
},
ended_at: {
type: DataTypes.DATE,
},
completion_status: {
type: DataTypes.ENUM,
values: [
"in_progress",
"completed",
"abandoned"
],
},
total_score: {
type: DataTypes.DECIMAL,
},
session_notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
cognitive_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.cognitive_sessions.hasMany(db.cognitive_attempts, {
as: 'cognitive_attempts_session',
foreignKey: {
name: 'sessionId',
},
constraints: false,
});
//end loop
db.cognitive_sessions.belongsTo(db.patients, {
as: 'patient',
foreignKey: {
name: 'patientId',
},
constraints: false,
});
db.cognitive_sessions.belongsTo(db.cognitive_programs, {
as: 'program',
foreignKey: {
name: 'programId',
},
constraints: false,
});
db.cognitive_sessions.belongsTo(db.users, {
as: 'started_by_user',
foreignKey: {
name: 'started_by_userId',
},
constraints: false,
});
db.cognitive_sessions.belongsTo(db.accounts, {
as: 'accounts',
foreignKey: {
name: 'accountsId',
},
constraints: false,
});
db.cognitive_sessions.belongsTo(db.users, {
as: 'createdBy',
});
db.cognitive_sessions.belongsTo(db.users, {
as: 'updatedBy',
});
};
return cognitive_sessions;
};

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,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 geofences = sequelize.define(
'geofences',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
geofence_name: {
type: DataTypes.TEXT,
},
shape_type: {
type: DataTypes.ENUM,
values: [
"circle",
"polygon"
],
},
center_latitude: {
type: DataTypes.DECIMAL,
},
center_longitude: {
type: DataTypes.DECIMAL,
},
radius_meters: {
type: DataTypes.DECIMAL,
},
polygon_points: {
type: DataTypes.TEXT,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
alert_on: {
type: DataTypes.ENUM,
values: [
"enter",
"exit",
"enter_or_exit"
],
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
geofences.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.geofences.belongsTo(db.patients, {
as: 'patient',
foreignKey: {
name: 'patientId',
},
constraints: false,
});
db.geofences.belongsTo(db.accounts, {
as: 'accounts',
foreignKey: {
name: 'accountsId',
},
constraints: false,
});
db.geofences.belongsTo(db.users, {
as: 'createdBy',
});
db.geofences.belongsTo(db.users, {
as: 'updatedBy',
});
};
return geofences;
};

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,202 @@
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 iot_devices = sequelize.define(
'iot_devices',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
device_type: {
type: DataTypes.ENUM,
values: [
"gps_bracelet",
"phone",
"beacon",
"other"
],
},
device_label: {
type: DataTypes.TEXT,
},
serial_number: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"active",
"inactive",
"lost",
"maintenance"
],
},
paired_at: {
type: DataTypes.DATE,
},
last_seen_at: {
type: DataTypes.DATE,
},
battery_level: {
type: DataTypes.DECIMAL,
},
firmware_version: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
iot_devices.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.iot_devices.hasMany(db.iot_telemetry_events, {
as: 'iot_telemetry_events_device',
foreignKey: {
name: 'deviceId',
},
constraints: false,
});
db.iot_devices.hasMany(db.alerts, {
as: 'alerts_device',
foreignKey: {
name: 'deviceId',
},
constraints: false,
});
//end loop
db.iot_devices.belongsTo(db.patients, {
as: 'patient',
foreignKey: {
name: 'patientId',
},
constraints: false,
});
db.iot_devices.belongsTo(db.accounts, {
as: 'accounts',
foreignKey: {
name: 'accountsId',
},
constraints: false,
});
db.iot_devices.belongsTo(db.users, {
as: 'createdBy',
});
db.iot_devices.belongsTo(db.users, {
as: 'updatedBy',
});
};
return iot_devices;
};

View File

@ -0,0 +1,186 @@
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 iot_telemetry_events = sequelize.define(
'iot_telemetry_events',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
recorded_at: {
type: DataTypes.DATE,
},
latitude: {
type: DataTypes.DECIMAL,
},
longitude: {
type: DataTypes.DECIMAL,
},
speed: {
type: DataTypes.DECIMAL,
},
accuracy_meters: {
type: DataTypes.DECIMAL,
},
battery_level: {
type: DataTypes.DECIMAL,
},
event_kind: {
type: DataTypes.ENUM,
values: [
"location_update",
"geofence_enter",
"geofence_exit",
"panic",
"fall_suspected",
"device_offline"
],
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
iot_telemetry_events.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.iot_telemetry_events.hasMany(db.alerts, {
as: 'alerts_trigger_event',
foreignKey: {
name: 'trigger_eventId',
},
constraints: false,
});
//end loop
db.iot_telemetry_events.belongsTo(db.iot_devices, {
as: 'device',
foreignKey: {
name: 'deviceId',
},
constraints: false,
});
db.iot_telemetry_events.belongsTo(db.patients, {
as: 'patient',
foreignKey: {
name: 'patientId',
},
constraints: false,
});
db.iot_telemetry_events.belongsTo(db.accounts, {
as: 'accounts',
foreignKey: {
name: 'accountsId',
},
constraints: false,
});
db.iot_telemetry_events.belongsTo(db.users, {
as: 'createdBy',
});
db.iot_telemetry_events.belongsTo(db.users, {
as: 'updatedBy',
});
};
return iot_telemetry_events;
};

View File

@ -0,0 +1,165 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const medication_schedules = sequelize.define(
'medication_schedules',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
frequency_type: {
type: DataTypes.ENUM,
values: [
"daily",
"weekly",
"custom"
],
},
time_of_day: {
type: DataTypes.TEXT,
},
days_of_week: {
type: DataTypes.TEXT,
},
effective_from: {
type: DataTypes.DATE,
},
effective_until: {
type: DataTypes.DATE,
},
requires_confirmation: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
medication_schedules.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.medication_schedules.belongsTo(db.medications, {
as: 'medication',
foreignKey: {
name: 'medicationId',
},
constraints: false,
});
db.medication_schedules.belongsTo(db.patients, {
as: 'patient',
foreignKey: {
name: 'patientId',
},
constraints: false,
});
db.medication_schedules.belongsTo(db.accounts, {
as: 'accounts',
foreignKey: {
name: 'accountsId',
},
constraints: false,
});
db.medication_schedules.belongsTo(db.users, {
as: 'createdBy',
});
db.medication_schedules.belongsTo(db.users, {
as: 'updatedBy',
});
};
return medication_schedules;
};

View File

@ -0,0 +1,176 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const medications = sequelize.define(
'medications',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
medication_name: {
type: DataTypes.TEXT,
},
dosage: {
type: DataTypes.TEXT,
},
route: {
type: DataTypes.TEXT,
},
instructions: {
type: DataTypes.TEXT,
},
start_at: {
type: DataTypes.DATE,
},
end_at: {
type: DataTypes.DATE,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
medications.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.medications.hasMany(db.medication_schedules, {
as: 'medication_schedules_medication',
foreignKey: {
name: 'medicationId',
},
constraints: false,
});
db.medications.hasMany(db.calendar_events, {
as: 'calendar_events_linked_medication',
foreignKey: {
name: 'linked_medicationId',
},
constraints: false,
});
//end loop
db.medications.belongsTo(db.patients, {
as: 'patient',
foreignKey: {
name: 'patientId',
},
constraints: false,
});
db.medications.belongsTo(db.users, {
as: 'prescribed_by',
foreignKey: {
name: 'prescribed_byId',
},
constraints: false,
});
db.medications.belongsTo(db.accounts, {
as: 'accounts',
foreignKey: {
name: 'accountsId',
},
constraints: false,
});
db.medications.belongsTo(db.users, {
as: 'createdBy',
});
db.medications.belongsTo(db.users, {
as: 'updatedBy',
});
};
return medications;
};

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 patient_access_grants = sequelize.define(
'patient_access_grants',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
access_level: {
type: DataTypes.ENUM,
values: [
"view",
"edit",
"clinician",
"owner"
],
},
can_view_iot_location: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
can_manage_medications: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
can_manage_calendar: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
can_view_health_data: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
granted_at: {
type: DataTypes.DATE,
},
revoked_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
patient_access_grants.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.patient_access_grants.belongsTo(db.patients, {
as: 'patient',
foreignKey: {
name: 'patientId',
},
constraints: false,
});
db.patient_access_grants.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.patient_access_grants.belongsTo(db.accounts, {
as: 'accounts',
foreignKey: {
name: 'accountsId',
},
constraints: false,
});
db.patient_access_grants.belongsTo(db.users, {
as: 'createdBy',
});
db.patient_access_grants.belongsTo(db.users, {
as: 'updatedBy',
});
};
return patient_access_grants;
};

View File

@ -0,0 +1,316 @@
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 patients = sequelize.define(
'patients',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
patient_code: {
type: DataTypes.TEXT,
},
first_name: {
type: DataTypes.TEXT,
},
last_name: {
type: DataTypes.TEXT,
},
date_of_birth: {
type: DataTypes.DATE,
},
sex: {
type: DataTypes.ENUM,
values: [
"female",
"male",
"other",
"unknown"
],
},
disease_stage: {
type: DataTypes.ENUM,
values: [
"mild",
"moderate",
"severe",
"unknown"
],
},
diagnosis_date: {
type: DataTypes.DATE,
},
medical_notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
patients.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.patients.hasMany(db.patient_access_grants, {
as: 'patient_access_grants_patient',
foreignKey: {
name: 'patientId',
},
constraints: false,
});
db.patients.hasMany(db.medications, {
as: 'medications_patient',
foreignKey: {
name: 'patientId',
},
constraints: false,
});
db.patients.hasMany(db.medication_schedules, {
as: 'medication_schedules_patient',
foreignKey: {
name: 'patientId',
},
constraints: false,
});
db.patients.hasMany(db.calendar_events, {
as: 'calendar_events_patient',
foreignKey: {
name: 'patientId',
},
constraints: false,
});
db.patients.hasMany(db.reminders, {
as: 'reminders_patient',
foreignKey: {
name: 'patientId',
},
constraints: false,
});
db.patients.hasMany(db.cognitive_sessions, {
as: 'cognitive_sessions_patient',
foreignKey: {
name: 'patientId',
},
constraints: false,
});
db.patients.hasMany(db.stage_assessments, {
as: 'stage_assessments_patient',
foreignKey: {
name: 'patientId',
},
constraints: false,
});
db.patients.hasMany(db.voice_assistant_sessions, {
as: 'voice_assistant_sessions_patient',
foreignKey: {
name: 'patientId',
},
constraints: false,
});
db.patients.hasMany(db.iot_devices, {
as: 'iot_devices_patient',
foreignKey: {
name: 'patientId',
},
constraints: false,
});
db.patients.hasMany(db.iot_telemetry_events, {
as: 'iot_telemetry_events_patient',
foreignKey: {
name: 'patientId',
},
constraints: false,
});
db.patients.hasMany(db.geofences, {
as: 'geofences_patient',
foreignKey: {
name: 'patientId',
},
constraints: false,
});
db.patients.hasMany(db.alerts, {
as: 'alerts_patient',
foreignKey: {
name: 'patientId',
},
constraints: false,
});
db.patients.hasMany(db.shared_dashboard_posts, {
as: 'shared_dashboard_posts_patient',
foreignKey: {
name: 'patientId',
},
constraints: false,
});
db.patients.hasMany(db.article_recommendations, {
as: 'article_recommendations_patient',
foreignKey: {
name: 'patientId',
},
constraints: false,
});
db.patients.hasMany(db.clinical_reports, {
as: 'clinical_reports_patient',
foreignKey: {
name: 'patientId',
},
constraints: false,
});
//end loop
db.patients.belongsTo(db.accounts, {
as: 'account',
foreignKey: {
name: 'accountId',
},
constraints: false,
});
db.patients.belongsTo(db.users, {
as: 'primary_physician',
foreignKey: {
name: 'primary_physicianId',
},
constraints: false,
});
db.patients.hasMany(db.file, {
as: 'profile_photo',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.patients.getTableName(),
belongsToColumn: 'profile_photo',
},
});
db.patients.belongsTo(db.users, {
as: 'createdBy',
});
db.patients.belongsTo(db.users, {
as: 'updatedBy',
});
};
return patients;
};

View File

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

View File

@ -0,0 +1,174 @@
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 reminders = sequelize.define(
'reminders',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
channel: {
type: DataTypes.ENUM,
values: [
"push",
"sms",
"email",
"voice"
],
},
scheduled_at: {
type: DataTypes.DATE,
},
state: {
type: DataTypes.ENUM,
values: [
"pending",
"sent",
"failed",
"cancelled"
],
},
message: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
reminders.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.reminders.belongsTo(db.patients, {
as: 'patient',
foreignKey: {
name: 'patientId',
},
constraints: false,
});
db.reminders.belongsTo(db.calendar_events, {
as: 'event',
foreignKey: {
name: 'eventId',
},
constraints: false,
});
db.reminders.belongsTo(db.users, {
as: 'recipient_user',
foreignKey: {
name: 'recipient_userId',
},
constraints: false,
});
db.reminders.belongsTo(db.accounts, {
as: 'accounts',
foreignKey: {
name: 'accountsId',
},
constraints: false,
});
db.reminders.belongsTo(db.users, {
as: 'createdBy',
});
db.reminders.belongsTo(db.users, {
as: 'updatedBy',
});
};
return reminders;
};

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 roles = sequelize.define(
'roles',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
role_customization: {
type: DataTypes.TEXT,
},
globalAccess: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
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,193 @@
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 scientific_articles = sequelize.define(
'scientific_articles',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
title_text: {
type: DataTypes.TEXT,
},
abstract_text: {
type: DataTypes.TEXT,
},
journal: {
type: DataTypes.TEXT,
},
published_at: {
type: DataTypes.DATE,
},
doi: {
type: DataTypes.TEXT,
},
url: {
type: DataTypes.TEXT,
},
keywords: {
type: DataTypes.TEXT,
},
validation_status: {
type: DataTypes.ENUM,
values: [
"pending",
"validated",
"rejected"
],
},
validation_notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
scientific_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.scientific_articles.hasMany(db.article_recommendations, {
as: 'article_recommendations_article',
foreignKey: {
name: 'articleId',
},
constraints: false,
});
//end loop
db.scientific_articles.belongsTo(db.users, {
as: 'validated_by_user',
foreignKey: {
name: 'validated_by_userId',
},
constraints: false,
});
db.scientific_articles.belongsTo(db.accounts, {
as: 'accounts',
foreignKey: {
name: 'accountsId',
},
constraints: false,
});
db.scientific_articles.hasMany(db.file, {
as: 'pdf_file',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.scientific_articles.getTableName(),
belongsToColumn: 'pdf_file',
},
});
db.scientific_articles.belongsTo(db.users, {
as: 'createdBy',
});
db.scientific_articles.belongsTo(db.users, {
as: 'updatedBy',
});
};
return scientific_articles;
};

View File

@ -0,0 +1,193 @@
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 shared_dashboard_posts = sequelize.define(
'shared_dashboard_posts',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
post_type: {
type: DataTypes.ENUM,
values: [
"update",
"question",
"note",
"photo",
"document"
],
},
title_text: {
type: DataTypes.TEXT,
},
content: {
type: DataTypes.TEXT,
},
posted_at: {
type: DataTypes.DATE,
},
visibility: {
type: DataTypes.ENUM,
values: [
"family_only",
"care_team",
"all_authorized"
],
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
shared_dashboard_posts.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.shared_dashboard_posts.belongsTo(db.patients, {
as: 'patient',
foreignKey: {
name: 'patientId',
},
constraints: false,
});
db.shared_dashboard_posts.belongsTo(db.users, {
as: 'author_user',
foreignKey: {
name: 'author_userId',
},
constraints: false,
});
db.shared_dashboard_posts.belongsTo(db.accounts, {
as: 'accounts',
foreignKey: {
name: 'accountsId',
},
constraints: false,
});
db.shared_dashboard_posts.hasMany(db.file, {
as: 'photos',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.shared_dashboard_posts.getTableName(),
belongsToColumn: 'photos',
},
});
db.shared_dashboard_posts.hasMany(db.file, {
as: 'attachments',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.shared_dashboard_posts.getTableName(),
belongsToColumn: 'attachments',
},
});
db.shared_dashboard_posts.belongsTo(db.users, {
as: 'createdBy',
});
db.shared_dashboard_posts.belongsTo(db.users, {
as: 'updatedBy',
});
};
return shared_dashboard_posts;
};

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 stage_assessments = sequelize.define(
'stage_assessments',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
assessed_at: {
type: DataTypes.DATE,
},
predicted_stage: {
type: DataTypes.ENUM,
values: [
"mild",
"moderate",
"severe",
"unknown"
],
},
confidence_score: {
type: DataTypes.DECIMAL,
},
method: {
type: DataTypes.ENUM,
values: [
"questionnaire",
"cognitive_model",
"clinician",
"hybrid"
],
},
model_version: {
type: DataTypes.TEXT,
},
explanation: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
stage_assessments.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.stage_assessments.belongsTo(db.patients, {
as: 'patient',
foreignKey: {
name: 'patientId',
},
constraints: false,
});
db.stage_assessments.belongsTo(db.users, {
as: 'reviewed_by_user',
foreignKey: {
name: 'reviewed_by_userId',
},
constraints: false,
});
db.stage_assessments.belongsTo(db.accounts, {
as: 'accounts',
foreignKey: {
name: 'accountsId',
},
constraints: false,
});
db.stage_assessments.belongsTo(db.users, {
as: 'createdBy',
});
db.stage_assessments.belongsTo(db.users, {
as: 'updatedBy',
});
};
return stage_assessments;
};

View File

@ -0,0 +1,369 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const users = sequelize.define(
'users',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
firstName: {
type: DataTypes.TEXT,
},
lastName: {
type: DataTypes.TEXT,
},
phoneNumber: {
type: DataTypes.TEXT,
},
email: {
type: DataTypes.TEXT,
},
disabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
password: {
type: DataTypes.TEXT,
},
emailVerified: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
emailVerificationToken: {
type: DataTypes.TEXT,
},
emailVerificationTokenExpiresAt: {
type: DataTypes.DATE,
},
passwordResetToken: {
type: DataTypes.TEXT,
},
passwordResetTokenExpiresAt: {
type: DataTypes.DATE,
},
provider: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
users.associate = (db) => {
db.users.belongsToMany(db.permissions, {
as: 'custom_permissions',
foreignKey: {
name: 'users_custom_permissionsId',
},
constraints: false,
through: 'usersCustom_permissionsPermissions',
});
db.users.belongsToMany(db.permissions, {
as: 'custom_permissions_filter',
foreignKey: {
name: 'users_custom_permissionsId',
},
constraints: false,
through: 'usersCustom_permissionsPermissions',
});
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.users.hasMany(db.patients, {
as: 'patients_primary_physician',
foreignKey: {
name: 'primary_physicianId',
},
constraints: false,
});
db.users.hasMany(db.patient_access_grants, {
as: 'patient_access_grants_user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.users.hasMany(db.medications, {
as: 'medications_prescribed_by',
foreignKey: {
name: 'prescribed_byId',
},
constraints: false,
});
db.users.hasMany(db.calendar_events, {
as: 'calendar_events_created_by_user',
foreignKey: {
name: 'created_by_userId',
},
constraints: false,
});
db.users.hasMany(db.reminders, {
as: 'reminders_recipient_user',
foreignKey: {
name: 'recipient_userId',
},
constraints: false,
});
db.users.hasMany(db.cognitive_programs, {
as: 'cognitive_programs_created_by_user',
foreignKey: {
name: 'created_by_userId',
},
constraints: false,
});
db.users.hasMany(db.cognitive_sessions, {
as: 'cognitive_sessions_started_by_user',
foreignKey: {
name: 'started_by_userId',
},
constraints: false,
});
db.users.hasMany(db.stage_assessments, {
as: 'stage_assessments_reviewed_by_user',
foreignKey: {
name: 'reviewed_by_userId',
},
constraints: false,
});
db.users.hasMany(db.voice_assistant_sessions, {
as: 'voice_assistant_sessions_initiated_by_user',
foreignKey: {
name: 'initiated_by_userId',
},
constraints: false,
});
db.users.hasMany(db.alerts, {
as: 'alerts_assigned_to_user',
foreignKey: {
name: 'assigned_to_userId',
},
constraints: false,
});
db.users.hasMany(db.alert_notifications, {
as: 'alert_notifications_recipient_user',
foreignKey: {
name: 'recipient_userId',
},
constraints: false,
});
db.users.hasMany(db.shared_dashboard_posts, {
as: 'shared_dashboard_posts_author_user',
foreignKey: {
name: 'author_userId',
},
constraints: false,
});
db.users.hasMany(db.scientific_articles, {
as: 'scientific_articles_validated_by_user',
foreignKey: {
name: 'validated_by_userId',
},
constraints: false,
});
db.users.hasMany(db.clinical_reports, {
as: 'clinical_reports_generated_by_user',
foreignKey: {
name: 'generated_by_userId',
},
constraints: false,
});
//end loop
db.users.belongsTo(db.roles, {
as: 'app_role',
foreignKey: {
name: 'app_roleId',
},
constraints: false,
});
db.users.belongsTo(db.accounts, {
as: 'accounts',
foreignKey: {
name: 'accountsId',
},
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,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 voice_assistant_sessions = sequelize.define(
'voice_assistant_sessions',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
started_at: {
type: DataTypes.DATE,
},
ended_at: {
type: DataTypes.DATE,
},
channel: {
type: DataTypes.ENUM,
values: [
"mobile",
"web",
"smart_speaker"
],
},
transcript: {
type: DataTypes.TEXT,
},
assistant_summary: {
type: DataTypes.TEXT,
},
outcome: {
type: DataTypes.ENUM,
values: [
"info",
"reminder_created",
"alert_created",
"handoff_to_caregiver",
"other"
],
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
voice_assistant_sessions.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.voice_assistant_sessions.belongsTo(db.patients, {
as: 'patient',
foreignKey: {
name: 'patientId',
},
constraints: false,
});
db.voice_assistant_sessions.belongsTo(db.users, {
as: 'initiated_by_user',
foreignKey: {
name: 'initiated_by_userId',
},
constraints: false,
});
db.voice_assistant_sessions.belongsTo(db.accounts, {
as: 'accounts',
foreignKey: {
name: 'accountsId',
},
constraints: false,
});
db.voice_assistant_sessions.belongsTo(db.users, {
as: 'createdBy',
});
db.voice_assistant_sessions.belongsTo(db.users, {
as: 'updatedBy',
});
};
return voice_assistant_sessions;
};

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,77 @@
'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',
'ab4cf9bf-4eef-4107-b73d-9d0274cf69bc',
]
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()
},
{
id: ids[3],
firstName: 'Super Admin',
email: 'super_admin@flatlogic.com',
emailVerified: true,
provider: config.providers.LOCAL,
password: admin_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'});
};
};

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

@ -0,0 +1,235 @@
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 organizationForAuthRoutes = require('./routes/organizationLogin');
const openaiRoutes = require('./routes/openai');
const usersRoutes = require('./routes/users');
const rolesRoutes = require('./routes/roles');
const permissionsRoutes = require('./routes/permissions');
const accountsRoutes = require('./routes/accounts');
const patientsRoutes = require('./routes/patients');
const patient_access_grantsRoutes = require('./routes/patient_access_grants');
const medicationsRoutes = require('./routes/medications');
const medication_schedulesRoutes = require('./routes/medication_schedules');
const calendar_eventsRoutes = require('./routes/calendar_events');
const remindersRoutes = require('./routes/reminders');
const cognitive_programsRoutes = require('./routes/cognitive_programs');
const cognitive_exercisesRoutes = require('./routes/cognitive_exercises');
const cognitive_sessionsRoutes = require('./routes/cognitive_sessions');
const cognitive_attemptsRoutes = require('./routes/cognitive_attempts');
const stage_assessmentsRoutes = require('./routes/stage_assessments');
const voice_assistant_sessionsRoutes = require('./routes/voice_assistant_sessions');
const iot_devicesRoutes = require('./routes/iot_devices');
const iot_telemetry_eventsRoutes = require('./routes/iot_telemetry_events');
const geofencesRoutes = require('./routes/geofences');
const alertsRoutes = require('./routes/alerts');
const alert_notificationsRoutes = require('./routes/alert_notifications');
const shared_dashboard_postsRoutes = require('./routes/shared_dashboard_posts');
const scientific_articlesRoutes = require('./routes/scientific_articles');
const article_recommendationsRoutes = require('./routes/article_recommendations');
const clinical_reportsRoutes = require('./routes/clinical_reports');
const admin_metrics_snapshotsRoutes = require('./routes/admin_metrics_snapshots');
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: "Plateforme Alzheimer Care",
description: "Plateforme Alzheimer Care 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/accounts', passport.authenticate('jwt', {session: false}), accountsRoutes);
app.use('/api/patients', passport.authenticate('jwt', {session: false}), patientsRoutes);
app.use('/api/patient_access_grants', passport.authenticate('jwt', {session: false}), patient_access_grantsRoutes);
app.use('/api/medications', passport.authenticate('jwt', {session: false}), medicationsRoutes);
app.use('/api/medication_schedules', passport.authenticate('jwt', {session: false}), medication_schedulesRoutes);
app.use('/api/calendar_events', passport.authenticate('jwt', {session: false}), calendar_eventsRoutes);
app.use('/api/reminders', passport.authenticate('jwt', {session: false}), remindersRoutes);
app.use('/api/cognitive_programs', passport.authenticate('jwt', {session: false}), cognitive_programsRoutes);
app.use('/api/cognitive_exercises', passport.authenticate('jwt', {session: false}), cognitive_exercisesRoutes);
app.use('/api/cognitive_sessions', passport.authenticate('jwt', {session: false}), cognitive_sessionsRoutes);
app.use('/api/cognitive_attempts', passport.authenticate('jwt', {session: false}), cognitive_attemptsRoutes);
app.use('/api/stage_assessments', passport.authenticate('jwt', {session: false}), stage_assessmentsRoutes);
app.use('/api/voice_assistant_sessions', passport.authenticate('jwt', {session: false}), voice_assistant_sessionsRoutes);
app.use('/api/iot_devices', passport.authenticate('jwt', {session: false}), iot_devicesRoutes);
app.use('/api/iot_telemetry_events', passport.authenticate('jwt', {session: false}), iot_telemetry_eventsRoutes);
app.use('/api/geofences', passport.authenticate('jwt', {session: false}), geofencesRoutes);
app.use('/api/alerts', passport.authenticate('jwt', {session: false}), alertsRoutes);
app.use('/api/alert_notifications', passport.authenticate('jwt', {session: false}), alert_notificationsRoutes);
app.use('/api/shared_dashboard_posts', passport.authenticate('jwt', {session: false}), shared_dashboard_postsRoutes);
app.use('/api/scientific_articles', passport.authenticate('jwt', {session: false}), scientific_articlesRoutes);
app.use('/api/article_recommendations', passport.authenticate('jwt', {session: false}), article_recommendationsRoutes);
app.use('/api/clinical_reports', passport.authenticate('jwt', {session: false}), clinical_reportsRoutes);
app.use('/api/admin_metrics_snapshots', passport.authenticate('jwt', {session: false}), admin_metrics_snapshotsRoutes);
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);
app.use(
'/api/org-for-auth',
organizationForAuthRoutes,
);
const publicDir = path.join(
__dirname,
'../public',
);
if (fs.existsSync(publicDir)) {
app.use('/', express.static(publicDir));
app.get('*', function(request, response) {
response.sendFile(
path.resolve(publicDir, 'index.html'),
);
});
}
const PORT = process.env.NODE_ENV === 'dev_stage' ? 3000 : 8080;
app.listen(PORT, () => {
console.log(`Listening on port ${PORT}`);
});
module.exports = app;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

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

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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