Initial version

This commit is contained in:
Flatlogic Bot 2026-04-11 03:47:51 +00:00
commit 4e92c44da5
556 changed files with 166656 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>EPI Unified Vocacao App</h2>
<p>Wizard-based real estate vocation analysis with scoring, dashboard, and PDF/JSON exports.</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 @@
# EPI Unified Vocacao App
## 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_39547
DB_USER=app_39547
DB_PASS=aa89e9ad-c2d0-430c-9360-9326d3301917
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 @@
#EPI Unified Vocacao App - 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_epi_unified_vocacao_app;`
- Then give that new user privileges to the new database then quit the `psql`.
- `postgres=> GRANT ALL PRIVILEGES ON DATABASE db_epi_unified_vocacao_app 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": "epiunifiedvocacaoapp",
"description": "EPI Unified Vocacao App - 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: "aa89e9ad",
user_pass: "9326d3301917",
admin_email: "admin@flatlogic.com",
providers: {
LOCAL: 'local',
GOOGLE: 'google',
MICROSOFT: 'microsoft'
},
secret_key: process.env.SECRET_KEY || 'aa89e9ad-c2d0-430c-9360-9326d3301917',
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: 'EPI Unified Vocacao App <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: 'Report Viewer',
},
project_uuid: 'aa89e9ad-c2d0-430c-9360-9326d3301917',
flHost: process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'dev_stage' ? 'https://flatlogic.com/projects' : 'http://localhost:3000/projects',
gpt_key: process.env.GPT_KEY || '',
};
config.pexelsKey = process.env.PEXELS_KEY || '';
config.pexelsQuery = 'Compass over abstract city map';
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,801 @@
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 AnalysesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const analyses = await db.analyses.create(
{
id: data.id || undefined,
title: data.title
||
null
,
status: data.status
||
null
,
started_at: data.started_at
||
null
,
calculated_at: data.calculated_at
||
null
,
dashboard_generated_at: data.dashboard_generated_at
||
null
,
classification: data.classification
||
null
,
pending_data_notes: data.pending_data_notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await analyses.setAsset( data.asset || null, {
transaction,
});
await analyses.setAnalyst( data.analyst || null, {
transaction,
});
await analyses.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.analyses.getTableName(),
belongsToColumn: 'exported_json_file',
belongsToId: analyses.id,
},
data.exported_json_file,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.analyses.getTableName(),
belongsToColumn: 'exported_pdf_file',
belongsToId: analyses.id,
},
data.exported_pdf_file,
options,
);
return analyses;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const analysesData = data.map((item, index) => ({
id: item.id || undefined,
title: item.title
||
null
,
status: item.status
||
null
,
started_at: item.started_at
||
null
,
calculated_at: item.calculated_at
||
null
,
dashboard_generated_at: item.dashboard_generated_at
||
null
,
classification: item.classification
||
null
,
pending_data_notes: item.pending_data_notes
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const analyses = await db.analyses.bulkCreate(analysesData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < analyses.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.analyses.getTableName(),
belongsToColumn: 'exported_json_file',
belongsToId: analyses[i].id,
},
data[i].exported_json_file,
options,
);
}
for (let i = 0; i < analyses.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.analyses.getTableName(),
belongsToColumn: 'exported_pdf_file',
belongsToId: analyses[i].id,
},
data[i].exported_pdf_file,
options,
);
}
return analyses;
}
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 analyses = await db.analyses.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.title !== undefined) updatePayload.title = data.title;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
if (data.calculated_at !== undefined) updatePayload.calculated_at = data.calculated_at;
if (data.dashboard_generated_at !== undefined) updatePayload.dashboard_generated_at = data.dashboard_generated_at;
if (data.classification !== undefined) updatePayload.classification = data.classification;
if (data.pending_data_notes !== undefined) updatePayload.pending_data_notes = data.pending_data_notes;
updatePayload.updatedById = currentUser.id;
await analyses.update(updatePayload, {transaction});
if (data.asset !== undefined) {
await analyses.setAsset(
data.asset,
{ transaction }
);
}
if (data.analyst !== undefined) {
await analyses.setAnalyst(
data.analyst,
{ transaction }
);
}
if (data.organizations !== undefined) {
await analyses.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.analyses.getTableName(),
belongsToColumn: 'exported_json_file',
belongsToId: analyses.id,
},
data.exported_json_file,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.analyses.getTableName(),
belongsToColumn: 'exported_pdf_file',
belongsToId: analyses.id,
},
data.exported_pdf_file,
options,
);
return analyses;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const analyses = await db.analyses.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of analyses) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of analyses) {
await record.destroy({transaction});
}
});
return analyses;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const analyses = await db.analyses.findByPk(id, options);
await analyses.update({
deletedBy: currentUser.id
}, {
transaction,
});
await analyses.destroy({
transaction
});
return analyses;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const analyses = await db.analyses.findOne(
{ where },
{ transaction },
);
if (!analyses) {
return analyses;
}
const output = analyses.get({plain: true});
output.client_profiles_analysis = await analyses.getClient_profiles_analysis({
transaction
});
output.urbanistic_parameters_analysis = await analyses.getUrbanistic_parameters_analysis({
transaction
});
output.environmental_constraints_analysis = await analyses.getEnvironmental_constraints_analysis({
transaction
});
output.analysis_infrastructure_analysis = await analyses.getAnalysis_infrastructure_analysis({
transaction
});
output.socioeconomic_profiles_analysis = await analyses.getSocioeconomic_profiles_analysis({
transaction
});
output.analysis_programs_analysis = await analyses.getAnalysis_programs_analysis({
transaction
});
output.analysis_vocation_results_analysis = await analyses.getAnalysis_vocation_results_analysis({
transaction
});
output.market_assessments_analysis = await analyses.getMarket_assessments_analysis({
transaction
});
output.holding_costs_analysis = await analyses.getHolding_costs_analysis({
transaction
});
output.external_value_vectors_analysis = await analyses.getExternal_value_vectors_analysis({
transaction
});
output.development_alternatives_analysis = await analyses.getDevelopment_alternatives_analysis({
transaction
});
output.dashboard_summaries_analysis = await analyses.getDashboard_summaries_analysis({
transaction
});
output.asset = await analyses.getAsset({
transaction
});
output.analyst = await analyses.getAnalyst({
transaction
});
output.exported_json_file = await analyses.getExported_json_file({
transaction
});
output.exported_pdf_file = await analyses.getExported_pdf_file({
transaction
});
output.organizations = await analyses.getOrganizations({
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 userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.assets,
as: 'asset',
where: filter.asset ? {
[Op.or]: [
{ id: { [Op.in]: filter.asset.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.asset.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'analyst',
where: filter.analyst ? {
[Op.or]: [
{ id: { [Op.in]: filter.analyst.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.analyst.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'exported_json_file',
},
{
model: db.file,
as: 'exported_pdf_file',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.title) {
where = {
...where,
[Op.and]: Utils.ilike(
'analyses',
'title',
filter.title,
),
};
}
if (filter.pending_data_notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'analyses',
'pending_data_notes',
filter.pending_data_notes,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
started_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
dashboard_generated_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.started_atRange) {
const [start, end] = filter.started_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
started_at: {
...where.started_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
started_at: {
...where.started_at,
[Op.lte]: end,
},
};
}
}
if (filter.calculated_atRange) {
const [start, end] = filter.calculated_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
calculated_at: {
...where.calculated_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
calculated_at: {
...where.calculated_at,
[Op.lte]: end,
},
};
}
}
if (filter.dashboard_generated_atRange) {
const [start, end] = filter.dashboard_generated_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
dashboard_generated_at: {
...where.dashboard_generated_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
dashboard_generated_at: {
...where.dashboard_generated_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.classification) {
where = {
...where,
classification: filter.classification,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[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.organizationsId;
}
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.analyses.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'analyses',
'title',
query,
),
],
};
}
const records = await db.analyses.findAll({
attributes: [ 'id', 'title' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['title', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.title,
}));
}
};

View File

@ -0,0 +1,498 @@
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 Analysis_infrastructureDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const analysis_infrastructure = await db.analysis_infrastructure.create(
{
id: data.id || undefined,
is_available: data.is_available
||
false
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await analysis_infrastructure.setAnalysis( data.analysis || null, {
transaction,
});
await analysis_infrastructure.setInfrastructure_item( data.infrastructure_item || null, {
transaction,
});
await analysis_infrastructure.setOrganizations( data.organizations || null, {
transaction,
});
return analysis_infrastructure;
}
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 analysis_infrastructureData = data.map((item, index) => ({
id: item.id || undefined,
is_available: item.is_available
||
false
,
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 analysis_infrastructure = await db.analysis_infrastructure.bulkCreate(analysis_infrastructureData, { transaction });
// For each item created, replace relation files
return analysis_infrastructure;
}
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 analysis_infrastructure = await db.analysis_infrastructure.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.is_available !== undefined) updatePayload.is_available = data.is_available;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await analysis_infrastructure.update(updatePayload, {transaction});
if (data.analysis !== undefined) {
await analysis_infrastructure.setAnalysis(
data.analysis,
{ transaction }
);
}
if (data.infrastructure_item !== undefined) {
await analysis_infrastructure.setInfrastructure_item(
data.infrastructure_item,
{ transaction }
);
}
if (data.organizations !== undefined) {
await analysis_infrastructure.setOrganizations(
data.organizations,
{ transaction }
);
}
return analysis_infrastructure;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const analysis_infrastructure = await db.analysis_infrastructure.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of analysis_infrastructure) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of analysis_infrastructure) {
await record.destroy({transaction});
}
});
return analysis_infrastructure;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const analysis_infrastructure = await db.analysis_infrastructure.findByPk(id, options);
await analysis_infrastructure.update({
deletedBy: currentUser.id
}, {
transaction,
});
await analysis_infrastructure.destroy({
transaction
});
return analysis_infrastructure;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const analysis_infrastructure = await db.analysis_infrastructure.findOne(
{ where },
{ transaction },
);
if (!analysis_infrastructure) {
return analysis_infrastructure;
}
const output = analysis_infrastructure.get({plain: true});
output.analysis = await analysis_infrastructure.getAnalysis({
transaction
});
output.infrastructure_item = await analysis_infrastructure.getInfrastructure_item({
transaction
});
output.organizations = await analysis_infrastructure.getOrganizations({
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 userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.analyses,
as: 'analysis',
where: filter.analysis ? {
[Op.or]: [
{ id: { [Op.in]: filter.analysis.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.analysis.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.infrastructure_items,
as: 'infrastructure_item',
where: filter.infrastructure_item ? {
[Op.or]: [
{ id: { [Op.in]: filter.infrastructure_item.split('|').map(term => Utils.uuid(term)) } },
{
label: {
[Op.or]: filter.infrastructure_item.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'analysis_infrastructure',
'notes',
filter.notes,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.is_available) {
where = {
...where,
is_available: filter.is_available,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[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.organizationsId;
}
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.analysis_infrastructure.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(
'analysis_infrastructure',
'notes',
query,
),
],
};
}
const records = await db.analysis_infrastructure.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,498 @@
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 Analysis_programsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const analysis_programs = await db.analysis_programs.create(
{
id: data.id || undefined,
is_active: data.is_active
||
false
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await analysis_programs.setAnalysis( data.analysis || null, {
transaction,
});
await analysis_programs.setHousing_program( data.housing_program || null, {
transaction,
});
await analysis_programs.setOrganizations( data.organizations || null, {
transaction,
});
return analysis_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 analysis_programsData = data.map((item, index) => ({
id: item.id || undefined,
is_active: item.is_active
||
false
,
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 analysis_programs = await db.analysis_programs.bulkCreate(analysis_programsData, { transaction });
// For each item created, replace relation files
return analysis_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 analysis_programs = await db.analysis_programs.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await analysis_programs.update(updatePayload, {transaction});
if (data.analysis !== undefined) {
await analysis_programs.setAnalysis(
data.analysis,
{ transaction }
);
}
if (data.housing_program !== undefined) {
await analysis_programs.setHousing_program(
data.housing_program,
{ transaction }
);
}
if (data.organizations !== undefined) {
await analysis_programs.setOrganizations(
data.organizations,
{ transaction }
);
}
return analysis_programs;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const analysis_programs = await db.analysis_programs.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of analysis_programs) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of analysis_programs) {
await record.destroy({transaction});
}
});
return analysis_programs;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const analysis_programs = await db.analysis_programs.findByPk(id, options);
await analysis_programs.update({
deletedBy: currentUser.id
}, {
transaction,
});
await analysis_programs.destroy({
transaction
});
return analysis_programs;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const analysis_programs = await db.analysis_programs.findOne(
{ where },
{ transaction },
);
if (!analysis_programs) {
return analysis_programs;
}
const output = analysis_programs.get({plain: true});
output.analysis = await analysis_programs.getAnalysis({
transaction
});
output.housing_program = await analysis_programs.getHousing_program({
transaction
});
output.organizations = await analysis_programs.getOrganizations({
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 userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.analyses,
as: 'analysis',
where: filter.analysis ? {
[Op.or]: [
{ id: { [Op.in]: filter.analysis.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.analysis.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.housing_programs,
as: 'housing_program',
where: filter.housing_program ? {
[Op.or]: [
{ id: { [Op.in]: filter.housing_program.split('|').map(term => Utils.uuid(term)) } },
{
label: {
[Op.or]: filter.housing_program.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'analysis_programs',
'notes',
filter.notes,
),
};
}
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.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[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.organizationsId;
}
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.analysis_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(
'analysis_programs',
'notes',
query,
),
],
};
}
const records = await db.analysis_programs.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,609 @@
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 Analysis_vocation_resultsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const analysis_vocation_results = await db.analysis_vocation_results.create(
{
id: data.id || undefined,
raw_score: data.raw_score
||
null
,
normalized_score: data.normalized_score
||
null
,
is_blocked: data.is_blocked
||
false
,
rank_position: data.rank_position
||
null
,
factors_json: data.factors_json
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await analysis_vocation_results.setAnalysis( data.analysis || null, {
transaction,
});
await analysis_vocation_results.setVocation_option( data.vocation_option || null, {
transaction,
});
await analysis_vocation_results.setOrganizations( data.organizations || null, {
transaction,
});
return analysis_vocation_results;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const analysis_vocation_resultsData = data.map((item, index) => ({
id: item.id || undefined,
raw_score: item.raw_score
||
null
,
normalized_score: item.normalized_score
||
null
,
is_blocked: item.is_blocked
||
false
,
rank_position: item.rank_position
||
null
,
factors_json: item.factors_json
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const analysis_vocation_results = await db.analysis_vocation_results.bulkCreate(analysis_vocation_resultsData, { transaction });
// For each item created, replace relation files
return analysis_vocation_results;
}
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 analysis_vocation_results = await db.analysis_vocation_results.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.raw_score !== undefined) updatePayload.raw_score = data.raw_score;
if (data.normalized_score !== undefined) updatePayload.normalized_score = data.normalized_score;
if (data.is_blocked !== undefined) updatePayload.is_blocked = data.is_blocked;
if (data.rank_position !== undefined) updatePayload.rank_position = data.rank_position;
if (data.factors_json !== undefined) updatePayload.factors_json = data.factors_json;
updatePayload.updatedById = currentUser.id;
await analysis_vocation_results.update(updatePayload, {transaction});
if (data.analysis !== undefined) {
await analysis_vocation_results.setAnalysis(
data.analysis,
{ transaction }
);
}
if (data.vocation_option !== undefined) {
await analysis_vocation_results.setVocation_option(
data.vocation_option,
{ transaction }
);
}
if (data.organizations !== undefined) {
await analysis_vocation_results.setOrganizations(
data.organizations,
{ transaction }
);
}
return analysis_vocation_results;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const analysis_vocation_results = await db.analysis_vocation_results.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of analysis_vocation_results) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of analysis_vocation_results) {
await record.destroy({transaction});
}
});
return analysis_vocation_results;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const analysis_vocation_results = await db.analysis_vocation_results.findByPk(id, options);
await analysis_vocation_results.update({
deletedBy: currentUser.id
}, {
transaction,
});
await analysis_vocation_results.destroy({
transaction
});
return analysis_vocation_results;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const analysis_vocation_results = await db.analysis_vocation_results.findOne(
{ where },
{ transaction },
);
if (!analysis_vocation_results) {
return analysis_vocation_results;
}
const output = analysis_vocation_results.get({plain: true});
output.analysis = await analysis_vocation_results.getAnalysis({
transaction
});
output.vocation_option = await analysis_vocation_results.getVocation_option({
transaction
});
output.organizations = await analysis_vocation_results.getOrganizations({
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 userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.analyses,
as: 'analysis',
where: filter.analysis ? {
[Op.or]: [
{ id: { [Op.in]: filter.analysis.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.analysis.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.vocation_options,
as: 'vocation_option',
where: filter.vocation_option ? {
[Op.or]: [
{ id: { [Op.in]: filter.vocation_option.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.vocation_option.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.factors_json) {
where = {
...where,
[Op.and]: Utils.ilike(
'analysis_vocation_results',
'factors_json',
filter.factors_json,
),
};
}
if (filter.raw_scoreRange) {
const [start, end] = filter.raw_scoreRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
raw_score: {
...where.raw_score,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
raw_score: {
...where.raw_score,
[Op.lte]: end,
},
};
}
}
if (filter.normalized_scoreRange) {
const [start, end] = filter.normalized_scoreRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
normalized_score: {
...where.normalized_score,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
normalized_score: {
...where.normalized_score,
[Op.lte]: end,
},
};
}
}
if (filter.rank_positionRange) {
const [start, end] = filter.rank_positionRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
rank_position: {
...where.rank_position,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
rank_position: {
...where.rank_position,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.is_blocked) {
where = {
...where,
is_blocked: filter.is_blocked,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[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.organizationsId;
}
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.analysis_vocation_results.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'analysis_vocation_results',
'factors_json',
query,
),
],
};
}
const records = await db.analysis_vocation_results.findAll({
attributes: [ 'id', 'factors_json' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['factors_json', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.factors_json,
}));
}
};

View File

@ -0,0 +1,861 @@
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 AssetsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const assets = await db.assets.create(
{
id: data.id || undefined,
name: data.name
||
null
,
municipality_uf: data.municipality_uf
||
null
,
owner_name: data.owner_name
||
null
,
registry_number: data.registry_number
||
null
,
appraisal_source: data.appraisal_source
||
null
,
total_area_m2: data.total_area_m2
||
null
,
total_area_ha: data.total_area_ha
||
null
,
topography: data.topography
||
null
,
shape: data.shape
||
null
,
vegetation: data.vegetation
||
null
,
current_occupation: data.current_occupation
||
null
,
urban_distance_band: data.urban_distance_band
||
null
,
logistics_distance_band: data.logistics_distance_band
||
null
,
biome_region: data.biome_region
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await assets.setClient( data.client || null, {
transaction,
});
await assets.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.assets.getTableName(),
belongsToColumn: 'documents',
belongsToId: assets.id,
},
data.documents,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.assets.getTableName(),
belongsToColumn: 'images',
belongsToId: assets.id,
},
data.images,
options,
);
return assets;
}
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 assetsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
municipality_uf: item.municipality_uf
||
null
,
owner_name: item.owner_name
||
null
,
registry_number: item.registry_number
||
null
,
appraisal_source: item.appraisal_source
||
null
,
total_area_m2: item.total_area_m2
||
null
,
total_area_ha: item.total_area_ha
||
null
,
topography: item.topography
||
null
,
shape: item.shape
||
null
,
vegetation: item.vegetation
||
null
,
current_occupation: item.current_occupation
||
null
,
urban_distance_band: item.urban_distance_band
||
null
,
logistics_distance_band: item.logistics_distance_band
||
null
,
biome_region: item.biome_region
||
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 assets = await db.assets.bulkCreate(assetsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < assets.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.assets.getTableName(),
belongsToColumn: 'documents',
belongsToId: assets[i].id,
},
data[i].documents,
options,
);
}
for (let i = 0; i < assets.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.assets.getTableName(),
belongsToColumn: 'images',
belongsToId: assets[i].id,
},
data[i].images,
options,
);
}
return assets;
}
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 assets = await db.assets.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.municipality_uf !== undefined) updatePayload.municipality_uf = data.municipality_uf;
if (data.owner_name !== undefined) updatePayload.owner_name = data.owner_name;
if (data.registry_number !== undefined) updatePayload.registry_number = data.registry_number;
if (data.appraisal_source !== undefined) updatePayload.appraisal_source = data.appraisal_source;
if (data.total_area_m2 !== undefined) updatePayload.total_area_m2 = data.total_area_m2;
if (data.total_area_ha !== undefined) updatePayload.total_area_ha = data.total_area_ha;
if (data.topography !== undefined) updatePayload.topography = data.topography;
if (data.shape !== undefined) updatePayload.shape = data.shape;
if (data.vegetation !== undefined) updatePayload.vegetation = data.vegetation;
if (data.current_occupation !== undefined) updatePayload.current_occupation = data.current_occupation;
if (data.urban_distance_band !== undefined) updatePayload.urban_distance_band = data.urban_distance_band;
if (data.logistics_distance_band !== undefined) updatePayload.logistics_distance_band = data.logistics_distance_band;
if (data.biome_region !== undefined) updatePayload.biome_region = data.biome_region;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await assets.update(updatePayload, {transaction});
if (data.client !== undefined) {
await assets.setClient(
data.client,
{ transaction }
);
}
if (data.organizations !== undefined) {
await assets.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.assets.getTableName(),
belongsToColumn: 'documents',
belongsToId: assets.id,
},
data.documents,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.assets.getTableName(),
belongsToColumn: 'images',
belongsToId: assets.id,
},
data.images,
options,
);
return assets;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const assets = await db.assets.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of assets) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of assets) {
await record.destroy({transaction});
}
});
return assets;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const assets = await db.assets.findByPk(id, options);
await assets.update({
deletedBy: currentUser.id
}, {
transaction,
});
await assets.destroy({
transaction
});
return assets;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const assets = await db.assets.findOne(
{ where },
{ transaction },
);
if (!assets) {
return assets;
}
const output = assets.get({plain: true});
output.analyses_asset = await assets.getAnalyses_asset({
transaction
});
output.client = await assets.getClient({
transaction
});
output.documents = await assets.getDocuments({
transaction
});
output.images = await assets.getImages({
transaction
});
output.organizations = await assets.getOrganizations({
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 userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.clients,
as: 'client',
where: filter.client ? {
[Op.or]: [
{ id: { [Op.in]: filter.client.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.client.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'documents',
},
{
model: db.file,
as: 'images',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'assets',
'name',
filter.name,
),
};
}
if (filter.municipality_uf) {
where = {
...where,
[Op.and]: Utils.ilike(
'assets',
'municipality_uf',
filter.municipality_uf,
),
};
}
if (filter.owner_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'assets',
'owner_name',
filter.owner_name,
),
};
}
if (filter.registry_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'assets',
'registry_number',
filter.registry_number,
),
};
}
if (filter.appraisal_source) {
where = {
...where,
[Op.and]: Utils.ilike(
'assets',
'appraisal_source',
filter.appraisal_source,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'assets',
'notes',
filter.notes,
),
};
}
if (filter.total_area_m2Range) {
const [start, end] = filter.total_area_m2Range;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
total_area_m2: {
...where.total_area_m2,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
total_area_m2: {
...where.total_area_m2,
[Op.lte]: end,
},
};
}
}
if (filter.total_area_haRange) {
const [start, end] = filter.total_area_haRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
total_area_ha: {
...where.total_area_ha,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
total_area_ha: {
...where.total_area_ha,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.topography) {
where = {
...where,
topography: filter.topography,
};
}
if (filter.shape) {
where = {
...where,
shape: filter.shape,
};
}
if (filter.vegetation) {
where = {
...where,
vegetation: filter.vegetation,
};
}
if (filter.current_occupation) {
where = {
...where,
current_occupation: filter.current_occupation,
};
}
if (filter.urban_distance_band) {
where = {
...where,
urban_distance_band: filter.urban_distance_band,
};
}
if (filter.logistics_distance_band) {
where = {
...where,
logistics_distance_band: filter.logistics_distance_band,
};
}
if (filter.biome_region) {
where = {
...where,
biome_region: filter.biome_region,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[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.organizationsId;
}
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.assets.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(
'assets',
'name',
query,
),
],
};
}
const records = await db.assets.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,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 Client_profilesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const client_profiles = await db.client_profiles.create(
{
id: data.id || undefined,
sale_motivation: data.sale_motivation
||
null
,
fii_relationship: data.fii_relationship
||
null
,
prazo_tolerance: data.prazo_tolerance
||
null
,
risco_tolerance: data.risco_tolerance
||
null
,
capex_tolerance: data.capex_tolerance
||
null
,
priority: data.priority
||
null
,
management_capacity: data.management_capacity
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await client_profiles.setAnalysis( data.analysis || null, {
transaction,
});
await client_profiles.setOrganizations( data.organizations || null, {
transaction,
});
return client_profiles;
}
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 client_profilesData = data.map((item, index) => ({
id: item.id || undefined,
sale_motivation: item.sale_motivation
||
null
,
fii_relationship: item.fii_relationship
||
null
,
prazo_tolerance: item.prazo_tolerance
||
null
,
risco_tolerance: item.risco_tolerance
||
null
,
capex_tolerance: item.capex_tolerance
||
null
,
priority: item.priority
||
null
,
management_capacity: item.management_capacity
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const client_profiles = await db.client_profiles.bulkCreate(client_profilesData, { transaction });
// For each item created, replace relation files
return client_profiles;
}
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 client_profiles = await db.client_profiles.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.sale_motivation !== undefined) updatePayload.sale_motivation = data.sale_motivation;
if (data.fii_relationship !== undefined) updatePayload.fii_relationship = data.fii_relationship;
if (data.prazo_tolerance !== undefined) updatePayload.prazo_tolerance = data.prazo_tolerance;
if (data.risco_tolerance !== undefined) updatePayload.risco_tolerance = data.risco_tolerance;
if (data.capex_tolerance !== undefined) updatePayload.capex_tolerance = data.capex_tolerance;
if (data.priority !== undefined) updatePayload.priority = data.priority;
if (data.management_capacity !== undefined) updatePayload.management_capacity = data.management_capacity;
updatePayload.updatedById = currentUser.id;
await client_profiles.update(updatePayload, {transaction});
if (data.analysis !== undefined) {
await client_profiles.setAnalysis(
data.analysis,
{ transaction }
);
}
if (data.organizations !== undefined) {
await client_profiles.setOrganizations(
data.organizations,
{ transaction }
);
}
return client_profiles;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const client_profiles = await db.client_profiles.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of client_profiles) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of client_profiles) {
await record.destroy({transaction});
}
});
return client_profiles;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const client_profiles = await db.client_profiles.findByPk(id, options);
await client_profiles.update({
deletedBy: currentUser.id
}, {
transaction,
});
await client_profiles.destroy({
transaction
});
return client_profiles;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const client_profiles = await db.client_profiles.findOne(
{ where },
{ transaction },
);
if (!client_profiles) {
return client_profiles;
}
const output = client_profiles.get({plain: true});
output.analysis = await client_profiles.getAnalysis({
transaction
});
output.organizations = await client_profiles.getOrganizations({
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 userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.analyses,
as: 'analysis',
where: filter.analysis ? {
[Op.or]: [
{ id: { [Op.in]: filter.analysis.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.analysis.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.prazo_toleranceRange) {
const [start, end] = filter.prazo_toleranceRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
prazo_tolerance: {
...where.prazo_tolerance,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
prazo_tolerance: {
...where.prazo_tolerance,
[Op.lte]: end,
},
};
}
}
if (filter.risco_toleranceRange) {
const [start, end] = filter.risco_toleranceRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
risco_tolerance: {
...where.risco_tolerance,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
risco_tolerance: {
...where.risco_tolerance,
[Op.lte]: end,
},
};
}
}
if (filter.capex_toleranceRange) {
const [start, end] = filter.capex_toleranceRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
capex_tolerance: {
...where.capex_tolerance,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
capex_tolerance: {
...where.capex_tolerance,
[Op.lte]: end,
},
};
}
}
if (filter.priorityRange) {
const [start, end] = filter.priorityRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
priority: {
...where.priority,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
priority: {
...where.priority,
[Op.lte]: end,
},
};
}
}
if (filter.management_capacityRange) {
const [start, end] = filter.management_capacityRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
management_capacity: {
...where.management_capacity,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
management_capacity: {
...where.management_capacity,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.sale_motivation) {
where = {
...where,
sale_motivation: filter.sale_motivation,
};
}
if (filter.fii_relationship) {
where = {
...where,
fii_relationship: filter.fii_relationship,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[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.organizationsId;
}
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.client_profiles.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(
'client_profiles',
'sale_motivation',
query,
),
],
};
}
const records = await db.client_profiles.findAll({
attributes: [ 'id', 'sale_motivation' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['sale_motivation', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.sale_motivation,
}));
}
};

View File

@ -0,0 +1,526 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class ClientsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const clients = await db.clients.create(
{
id: data.id || undefined,
name: data.name
||
null
,
department: data.department
||
null
,
responsible_name: data.responsible_name
||
null
,
responsible_email: data.responsible_email
||
null
,
responsible_phone: data.responsible_phone
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await clients.setOrganization(currentUser.organization.id || null, {
transaction,
});
return clients;
}
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 clientsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
department: item.department
||
null
,
responsible_name: item.responsible_name
||
null
,
responsible_email: item.responsible_email
||
null
,
responsible_phone: item.responsible_phone
||
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 clients = await db.clients.bulkCreate(clientsData, { transaction });
// For each item created, replace relation files
return clients;
}
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 clients = await db.clients.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.department !== undefined) updatePayload.department = data.department;
if (data.responsible_name !== undefined) updatePayload.responsible_name = data.responsible_name;
if (data.responsible_email !== undefined) updatePayload.responsible_email = data.responsible_email;
if (data.responsible_phone !== undefined) updatePayload.responsible_phone = data.responsible_phone;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await clients.update(updatePayload, {transaction});
if (data.organization !== undefined) {
await clients.setOrganization(
(globalAccess ? data.organization : currentUser.organization.id),
{ transaction }
);
}
return clients;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const clients = await db.clients.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of clients) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of clients) {
await record.destroy({transaction});
}
});
return clients;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const clients = await db.clients.findByPk(id, options);
await clients.update({
deletedBy: currentUser.id
}, {
transaction,
});
await clients.destroy({
transaction
});
return clients;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const clients = await db.clients.findOne(
{ where },
{ transaction },
);
if (!clients) {
return clients;
}
const output = clients.get({plain: true});
output.assets_client = await clients.getAssets_client({
transaction
});
output.organization = await clients.getOrganization({
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 userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.organizations,
as: 'organization',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'clients',
'name',
filter.name,
),
};
}
if (filter.department) {
where = {
...where,
[Op.and]: Utils.ilike(
'clients',
'department',
filter.department,
),
};
}
if (filter.responsible_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'clients',
'responsible_name',
filter.responsible_name,
),
};
}
if (filter.responsible_email) {
where = {
...where,
[Op.and]: Utils.ilike(
'clients',
'responsible_email',
filter.responsible_email,
),
};
}
if (filter.responsible_phone) {
where = {
...where,
[Op.and]: Utils.ilike(
'clients',
'responsible_phone',
filter.responsible_phone,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'clients',
'notes',
filter.notes,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.organization) {
const listItems = filter.organization.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationId: {[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.organizationsId;
}
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.clients.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(
'clients',
'name',
query,
),
],
};
}
const records = await db.clients.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,709 @@
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 Dashboard_summariesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const dashboard_summaries = await db.dashboard_summaries.create(
{
id: data.id || undefined,
market_value_avg: data.market_value_avg
||
null
,
npv_alienation_net: data.npv_alienation_net
||
null
,
npv_forced_liquidation: data.npv_forced_liquidation
||
null
,
npv_fractionated_sale: data.npv_fractionated_sale
||
null
,
npv_development: data.npv_development
||
null
,
optionality_score: data.optionality_score
||
null
,
top_vocation_name: data.top_vocation_name
||
null
,
alerts_text: data.alerts_text
||
null
,
pendings_text: data.pendings_text
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await dashboard_summaries.setAnalysis( data.analysis || null, {
transaction,
});
await dashboard_summaries.setOrganizations( data.organizations || null, {
transaction,
});
return dashboard_summaries;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const dashboard_summariesData = data.map((item, index) => ({
id: item.id || undefined,
market_value_avg: item.market_value_avg
||
null
,
npv_alienation_net: item.npv_alienation_net
||
null
,
npv_forced_liquidation: item.npv_forced_liquidation
||
null
,
npv_fractionated_sale: item.npv_fractionated_sale
||
null
,
npv_development: item.npv_development
||
null
,
optionality_score: item.optionality_score
||
null
,
top_vocation_name: item.top_vocation_name
||
null
,
alerts_text: item.alerts_text
||
null
,
pendings_text: item.pendings_text
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const dashboard_summaries = await db.dashboard_summaries.bulkCreate(dashboard_summariesData, { transaction });
// For each item created, replace relation files
return dashboard_summaries;
}
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 dashboard_summaries = await db.dashboard_summaries.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.market_value_avg !== undefined) updatePayload.market_value_avg = data.market_value_avg;
if (data.npv_alienation_net !== undefined) updatePayload.npv_alienation_net = data.npv_alienation_net;
if (data.npv_forced_liquidation !== undefined) updatePayload.npv_forced_liquidation = data.npv_forced_liquidation;
if (data.npv_fractionated_sale !== undefined) updatePayload.npv_fractionated_sale = data.npv_fractionated_sale;
if (data.npv_development !== undefined) updatePayload.npv_development = data.npv_development;
if (data.optionality_score !== undefined) updatePayload.optionality_score = data.optionality_score;
if (data.top_vocation_name !== undefined) updatePayload.top_vocation_name = data.top_vocation_name;
if (data.alerts_text !== undefined) updatePayload.alerts_text = data.alerts_text;
if (data.pendings_text !== undefined) updatePayload.pendings_text = data.pendings_text;
updatePayload.updatedById = currentUser.id;
await dashboard_summaries.update(updatePayload, {transaction});
if (data.analysis !== undefined) {
await dashboard_summaries.setAnalysis(
data.analysis,
{ transaction }
);
}
if (data.organizations !== undefined) {
await dashboard_summaries.setOrganizations(
data.organizations,
{ transaction }
);
}
return dashboard_summaries;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const dashboard_summaries = await db.dashboard_summaries.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of dashboard_summaries) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of dashboard_summaries) {
await record.destroy({transaction});
}
});
return dashboard_summaries;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const dashboard_summaries = await db.dashboard_summaries.findByPk(id, options);
await dashboard_summaries.update({
deletedBy: currentUser.id
}, {
transaction,
});
await dashboard_summaries.destroy({
transaction
});
return dashboard_summaries;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const dashboard_summaries = await db.dashboard_summaries.findOne(
{ where },
{ transaction },
);
if (!dashboard_summaries) {
return dashboard_summaries;
}
const output = dashboard_summaries.get({plain: true});
output.analysis = await dashboard_summaries.getAnalysis({
transaction
});
output.organizations = await dashboard_summaries.getOrganizations({
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 userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.analyses,
as: 'analysis',
where: filter.analysis ? {
[Op.or]: [
{ id: { [Op.in]: filter.analysis.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.analysis.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.top_vocation_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'dashboard_summaries',
'top_vocation_name',
filter.top_vocation_name,
),
};
}
if (filter.alerts_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'dashboard_summaries',
'alerts_text',
filter.alerts_text,
),
};
}
if (filter.pendings_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'dashboard_summaries',
'pendings_text',
filter.pendings_text,
),
};
}
if (filter.market_value_avgRange) {
const [start, end] = filter.market_value_avgRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
market_value_avg: {
...where.market_value_avg,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
market_value_avg: {
...where.market_value_avg,
[Op.lte]: end,
},
};
}
}
if (filter.npv_alienation_netRange) {
const [start, end] = filter.npv_alienation_netRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
npv_alienation_net: {
...where.npv_alienation_net,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
npv_alienation_net: {
...where.npv_alienation_net,
[Op.lte]: end,
},
};
}
}
if (filter.npv_forced_liquidationRange) {
const [start, end] = filter.npv_forced_liquidationRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
npv_forced_liquidation: {
...where.npv_forced_liquidation,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
npv_forced_liquidation: {
...where.npv_forced_liquidation,
[Op.lte]: end,
},
};
}
}
if (filter.npv_fractionated_saleRange) {
const [start, end] = filter.npv_fractionated_saleRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
npv_fractionated_sale: {
...where.npv_fractionated_sale,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
npv_fractionated_sale: {
...where.npv_fractionated_sale,
[Op.lte]: end,
},
};
}
}
if (filter.npv_developmentRange) {
const [start, end] = filter.npv_developmentRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
npv_development: {
...where.npv_development,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
npv_development: {
...where.npv_development,
[Op.lte]: end,
},
};
}
}
if (filter.optionality_scoreRange) {
const [start, end] = filter.optionality_scoreRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
optionality_score: {
...where.optionality_score,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
optionality_score: {
...where.optionality_score,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[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.organizationsId;
}
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.dashboard_summaries.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'dashboard_summaries',
'top_vocation_name',
query,
),
],
};
}
const records = await db.dashboard_summaries.findAll({
attributes: [ 'id', 'top_vocation_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['top_vocation_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.top_vocation_name,
}));
}
};

View File

@ -0,0 +1,805 @@
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 Development_alternativesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const development_alternatives = await db.development_alternatives.create(
{
id: data.id || undefined,
development_type: data.development_type
||
null
,
roads_public_area_pct: data.roads_public_area_pct
||
null
,
lot_sale_price_m2: data.lot_sale_price_m2
||
null
,
infrastructure_cost_m2: data.infrastructure_cost_m2
||
null
,
projects_licenses_cost: data.projects_licenses_cost
||
null
,
total_term_years: data.total_term_years
||
null
,
fractionated_premium_pct: data.fractionated_premium_pct
||
null
,
fractionated_absorption_years: data.fractionated_absorption_years
||
null
,
subdivision_cost: data.subdivision_cost
||
null
,
computed_vpl_development: data.computed_vpl_development
||
null
,
computed_vpl_fractionated: data.computed_vpl_fractionated
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await development_alternatives.setAnalysis( data.analysis || null, {
transaction,
});
await development_alternatives.setOrganizations( data.organizations || null, {
transaction,
});
return development_alternatives;
}
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 development_alternativesData = data.map((item, index) => ({
id: item.id || undefined,
development_type: item.development_type
||
null
,
roads_public_area_pct: item.roads_public_area_pct
||
null
,
lot_sale_price_m2: item.lot_sale_price_m2
||
null
,
infrastructure_cost_m2: item.infrastructure_cost_m2
||
null
,
projects_licenses_cost: item.projects_licenses_cost
||
null
,
total_term_years: item.total_term_years
||
null
,
fractionated_premium_pct: item.fractionated_premium_pct
||
null
,
fractionated_absorption_years: item.fractionated_absorption_years
||
null
,
subdivision_cost: item.subdivision_cost
||
null
,
computed_vpl_development: item.computed_vpl_development
||
null
,
computed_vpl_fractionated: item.computed_vpl_fractionated
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const development_alternatives = await db.development_alternatives.bulkCreate(development_alternativesData, { transaction });
// For each item created, replace relation files
return development_alternatives;
}
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 development_alternatives = await db.development_alternatives.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.development_type !== undefined) updatePayload.development_type = data.development_type;
if (data.roads_public_area_pct !== undefined) updatePayload.roads_public_area_pct = data.roads_public_area_pct;
if (data.lot_sale_price_m2 !== undefined) updatePayload.lot_sale_price_m2 = data.lot_sale_price_m2;
if (data.infrastructure_cost_m2 !== undefined) updatePayload.infrastructure_cost_m2 = data.infrastructure_cost_m2;
if (data.projects_licenses_cost !== undefined) updatePayload.projects_licenses_cost = data.projects_licenses_cost;
if (data.total_term_years !== undefined) updatePayload.total_term_years = data.total_term_years;
if (data.fractionated_premium_pct !== undefined) updatePayload.fractionated_premium_pct = data.fractionated_premium_pct;
if (data.fractionated_absorption_years !== undefined) updatePayload.fractionated_absorption_years = data.fractionated_absorption_years;
if (data.subdivision_cost !== undefined) updatePayload.subdivision_cost = data.subdivision_cost;
if (data.computed_vpl_development !== undefined) updatePayload.computed_vpl_development = data.computed_vpl_development;
if (data.computed_vpl_fractionated !== undefined) updatePayload.computed_vpl_fractionated = data.computed_vpl_fractionated;
updatePayload.updatedById = currentUser.id;
await development_alternatives.update(updatePayload, {transaction});
if (data.analysis !== undefined) {
await development_alternatives.setAnalysis(
data.analysis,
{ transaction }
);
}
if (data.organizations !== undefined) {
await development_alternatives.setOrganizations(
data.organizations,
{ transaction }
);
}
return development_alternatives;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const development_alternatives = await db.development_alternatives.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of development_alternatives) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of development_alternatives) {
await record.destroy({transaction});
}
});
return development_alternatives;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const development_alternatives = await db.development_alternatives.findByPk(id, options);
await development_alternatives.update({
deletedBy: currentUser.id
}, {
transaction,
});
await development_alternatives.destroy({
transaction
});
return development_alternatives;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const development_alternatives = await db.development_alternatives.findOne(
{ where },
{ transaction },
);
if (!development_alternatives) {
return development_alternatives;
}
const output = development_alternatives.get({plain: true});
output.analysis = await development_alternatives.getAnalysis({
transaction
});
output.organizations = await development_alternatives.getOrganizations({
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 userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.analyses,
as: 'analysis',
where: filter.analysis ? {
[Op.or]: [
{ id: { [Op.in]: filter.analysis.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.analysis.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.roads_public_area_pctRange) {
const [start, end] = filter.roads_public_area_pctRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
roads_public_area_pct: {
...where.roads_public_area_pct,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
roads_public_area_pct: {
...where.roads_public_area_pct,
[Op.lte]: end,
},
};
}
}
if (filter.lot_sale_price_m2Range) {
const [start, end] = filter.lot_sale_price_m2Range;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
lot_sale_price_m2: {
...where.lot_sale_price_m2,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
lot_sale_price_m2: {
...where.lot_sale_price_m2,
[Op.lte]: end,
},
};
}
}
if (filter.infrastructure_cost_m2Range) {
const [start, end] = filter.infrastructure_cost_m2Range;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
infrastructure_cost_m2: {
...where.infrastructure_cost_m2,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
infrastructure_cost_m2: {
...where.infrastructure_cost_m2,
[Op.lte]: end,
},
};
}
}
if (filter.projects_licenses_costRange) {
const [start, end] = filter.projects_licenses_costRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
projects_licenses_cost: {
...where.projects_licenses_cost,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
projects_licenses_cost: {
...where.projects_licenses_cost,
[Op.lte]: end,
},
};
}
}
if (filter.total_term_yearsRange) {
const [start, end] = filter.total_term_yearsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
total_term_years: {
...where.total_term_years,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
total_term_years: {
...where.total_term_years,
[Op.lte]: end,
},
};
}
}
if (filter.fractionated_premium_pctRange) {
const [start, end] = filter.fractionated_premium_pctRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
fractionated_premium_pct: {
...where.fractionated_premium_pct,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
fractionated_premium_pct: {
...where.fractionated_premium_pct,
[Op.lte]: end,
},
};
}
}
if (filter.fractionated_absorption_yearsRange) {
const [start, end] = filter.fractionated_absorption_yearsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
fractionated_absorption_years: {
...where.fractionated_absorption_years,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
fractionated_absorption_years: {
...where.fractionated_absorption_years,
[Op.lte]: end,
},
};
}
}
if (filter.subdivision_costRange) {
const [start, end] = filter.subdivision_costRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
subdivision_cost: {
...where.subdivision_cost,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
subdivision_cost: {
...where.subdivision_cost,
[Op.lte]: end,
},
};
}
}
if (filter.computed_vpl_developmentRange) {
const [start, end] = filter.computed_vpl_developmentRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
computed_vpl_development: {
...where.computed_vpl_development,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
computed_vpl_development: {
...where.computed_vpl_development,
[Op.lte]: end,
},
};
}
}
if (filter.computed_vpl_fractionatedRange) {
const [start, end] = filter.computed_vpl_fractionatedRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
computed_vpl_fractionated: {
...where.computed_vpl_fractionated,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
computed_vpl_fractionated: {
...where.computed_vpl_fractionated,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.development_type) {
where = {
...where,
development_type: filter.development_type,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[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.organizationsId;
}
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.development_alternatives.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(
'development_alternatives',
'development_type',
query,
),
],
};
}
const records = await db.development_alternatives.findAll({
attributes: [ 'id', 'development_type' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['development_type', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.development_type,
}));
}
};

View File

@ -0,0 +1,662 @@
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 Environmental_constraintsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const environmental_constraints = await db.environmental_constraints.create(
{
id: data.id || undefined,
app_status: data.app_status
||
null
,
app_area_m2: data.app_area_m2
||
null
,
rl_status: data.rl_status
||
null
,
rl_area_m2: data.rl_area_m2
||
null
,
restricted_area_m2: data.restricted_area_m2
||
null
,
restricted_area_pct: data.restricted_area_pct
||
null
,
estimated_usable_area_m2: data.estimated_usable_area_m2
||
null
,
is_blocked_for_development: data.is_blocked_for_development
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await environmental_constraints.setAnalysis( data.analysis || null, {
transaction,
});
await environmental_constraints.setOrganizations( data.organizations || null, {
transaction,
});
return environmental_constraints;
}
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 environmental_constraintsData = data.map((item, index) => ({
id: item.id || undefined,
app_status: item.app_status
||
null
,
app_area_m2: item.app_area_m2
||
null
,
rl_status: item.rl_status
||
null
,
rl_area_m2: item.rl_area_m2
||
null
,
restricted_area_m2: item.restricted_area_m2
||
null
,
restricted_area_pct: item.restricted_area_pct
||
null
,
estimated_usable_area_m2: item.estimated_usable_area_m2
||
null
,
is_blocked_for_development: item.is_blocked_for_development
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const environmental_constraints = await db.environmental_constraints.bulkCreate(environmental_constraintsData, { transaction });
// For each item created, replace relation files
return environmental_constraints;
}
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 environmental_constraints = await db.environmental_constraints.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.app_status !== undefined) updatePayload.app_status = data.app_status;
if (data.app_area_m2 !== undefined) updatePayload.app_area_m2 = data.app_area_m2;
if (data.rl_status !== undefined) updatePayload.rl_status = data.rl_status;
if (data.rl_area_m2 !== undefined) updatePayload.rl_area_m2 = data.rl_area_m2;
if (data.restricted_area_m2 !== undefined) updatePayload.restricted_area_m2 = data.restricted_area_m2;
if (data.restricted_area_pct !== undefined) updatePayload.restricted_area_pct = data.restricted_area_pct;
if (data.estimated_usable_area_m2 !== undefined) updatePayload.estimated_usable_area_m2 = data.estimated_usable_area_m2;
if (data.is_blocked_for_development !== undefined) updatePayload.is_blocked_for_development = data.is_blocked_for_development;
updatePayload.updatedById = currentUser.id;
await environmental_constraints.update(updatePayload, {transaction});
if (data.analysis !== undefined) {
await environmental_constraints.setAnalysis(
data.analysis,
{ transaction }
);
}
if (data.organizations !== undefined) {
await environmental_constraints.setOrganizations(
data.organizations,
{ transaction }
);
}
return environmental_constraints;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const environmental_constraints = await db.environmental_constraints.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of environmental_constraints) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of environmental_constraints) {
await record.destroy({transaction});
}
});
return environmental_constraints;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const environmental_constraints = await db.environmental_constraints.findByPk(id, options);
await environmental_constraints.update({
deletedBy: currentUser.id
}, {
transaction,
});
await environmental_constraints.destroy({
transaction
});
return environmental_constraints;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const environmental_constraints = await db.environmental_constraints.findOne(
{ where },
{ transaction },
);
if (!environmental_constraints) {
return environmental_constraints;
}
const output = environmental_constraints.get({plain: true});
output.analysis = await environmental_constraints.getAnalysis({
transaction
});
output.organizations = await environmental_constraints.getOrganizations({
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 userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.analyses,
as: 'analysis',
where: filter.analysis ? {
[Op.or]: [
{ id: { [Op.in]: filter.analysis.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.analysis.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.app_area_m2Range) {
const [start, end] = filter.app_area_m2Range;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
app_area_m2: {
...where.app_area_m2,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
app_area_m2: {
...where.app_area_m2,
[Op.lte]: end,
},
};
}
}
if (filter.rl_area_m2Range) {
const [start, end] = filter.rl_area_m2Range;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
rl_area_m2: {
...where.rl_area_m2,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
rl_area_m2: {
...where.rl_area_m2,
[Op.lte]: end,
},
};
}
}
if (filter.restricted_area_m2Range) {
const [start, end] = filter.restricted_area_m2Range;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
restricted_area_m2: {
...where.restricted_area_m2,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
restricted_area_m2: {
...where.restricted_area_m2,
[Op.lte]: end,
},
};
}
}
if (filter.restricted_area_pctRange) {
const [start, end] = filter.restricted_area_pctRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
restricted_area_pct: {
...where.restricted_area_pct,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
restricted_area_pct: {
...where.restricted_area_pct,
[Op.lte]: end,
},
};
}
}
if (filter.estimated_usable_area_m2Range) {
const [start, end] = filter.estimated_usable_area_m2Range;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
estimated_usable_area_m2: {
...where.estimated_usable_area_m2,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
estimated_usable_area_m2: {
...where.estimated_usable_area_m2,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.app_status) {
where = {
...where,
app_status: filter.app_status,
};
}
if (filter.rl_status) {
where = {
...where,
rl_status: filter.rl_status,
};
}
if (filter.is_blocked_for_development) {
where = {
...where,
is_blocked_for_development: filter.is_blocked_for_development,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[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.organizationsId;
}
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.environmental_constraints.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(
'environmental_constraints',
'app_status',
query,
),
],
};
}
const records = await db.environmental_constraints.findAll({
attributes: [ 'id', 'app_status' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['app_status', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.app_status,
}));
}
};

View File

@ -0,0 +1,590 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class External_value_vectorsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const external_value_vectors = await db.external_value_vectors.create(
{
id: data.id || undefined,
vector_type: data.vector_type
||
null
,
stage: data.stage
||
null
,
name_description: data.name_description
||
null
,
base_points: data.base_points
||
null
,
stage_multiplier: data.stage_multiplier
||
null
,
computed_points: data.computed_points
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await external_value_vectors.setAnalysis( data.analysis || null, {
transaction,
});
await external_value_vectors.setOrganizations( data.organizations || null, {
transaction,
});
return external_value_vectors;
}
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 external_value_vectorsData = data.map((item, index) => ({
id: item.id || undefined,
vector_type: item.vector_type
||
null
,
stage: item.stage
||
null
,
name_description: item.name_description
||
null
,
base_points: item.base_points
||
null
,
stage_multiplier: item.stage_multiplier
||
null
,
computed_points: item.computed_points
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const external_value_vectors = await db.external_value_vectors.bulkCreate(external_value_vectorsData, { transaction });
// For each item created, replace relation files
return external_value_vectors;
}
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 external_value_vectors = await db.external_value_vectors.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.vector_type !== undefined) updatePayload.vector_type = data.vector_type;
if (data.stage !== undefined) updatePayload.stage = data.stage;
if (data.name_description !== undefined) updatePayload.name_description = data.name_description;
if (data.base_points !== undefined) updatePayload.base_points = data.base_points;
if (data.stage_multiplier !== undefined) updatePayload.stage_multiplier = data.stage_multiplier;
if (data.computed_points !== undefined) updatePayload.computed_points = data.computed_points;
updatePayload.updatedById = currentUser.id;
await external_value_vectors.update(updatePayload, {transaction});
if (data.analysis !== undefined) {
await external_value_vectors.setAnalysis(
data.analysis,
{ transaction }
);
}
if (data.organizations !== undefined) {
await external_value_vectors.setOrganizations(
data.organizations,
{ transaction }
);
}
return external_value_vectors;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const external_value_vectors = await db.external_value_vectors.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of external_value_vectors) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of external_value_vectors) {
await record.destroy({transaction});
}
});
return external_value_vectors;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const external_value_vectors = await db.external_value_vectors.findByPk(id, options);
await external_value_vectors.update({
deletedBy: currentUser.id
}, {
transaction,
});
await external_value_vectors.destroy({
transaction
});
return external_value_vectors;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const external_value_vectors = await db.external_value_vectors.findOne(
{ where },
{ transaction },
);
if (!external_value_vectors) {
return external_value_vectors;
}
const output = external_value_vectors.get({plain: true});
output.analysis = await external_value_vectors.getAnalysis({
transaction
});
output.organizations = await external_value_vectors.getOrganizations({
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 userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.analyses,
as: 'analysis',
where: filter.analysis ? {
[Op.or]: [
{ id: { [Op.in]: filter.analysis.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.analysis.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name_description) {
where = {
...where,
[Op.and]: Utils.ilike(
'external_value_vectors',
'name_description',
filter.name_description,
),
};
}
if (filter.base_pointsRange) {
const [start, end] = filter.base_pointsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
base_points: {
...where.base_points,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
base_points: {
...where.base_points,
[Op.lte]: end,
},
};
}
}
if (filter.stage_multiplierRange) {
const [start, end] = filter.stage_multiplierRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
stage_multiplier: {
...where.stage_multiplier,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
stage_multiplier: {
...where.stage_multiplier,
[Op.lte]: end,
},
};
}
}
if (filter.computed_pointsRange) {
const [start, end] = filter.computed_pointsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
computed_points: {
...where.computed_points,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
computed_points: {
...where.computed_points,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.vector_type) {
where = {
...where,
vector_type: filter.vector_type,
};
}
if (filter.stage) {
where = {
...where,
stage: filter.stage,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[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.organizationsId;
}
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.external_value_vectors.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(
'external_value_vectors',
'name_description',
query,
),
],
};
}
const records = await db.external_value_vectors.findAll({
attributes: [ 'id', 'name_description' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['name_description', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.name_description,
}));
}
};

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,637 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Holding_costsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const holding_costs = await db.holding_costs.create(
{
id: data.id || undefined,
iptu_annual: data.iptu_annual
||
null
,
security_monthly: data.security_monthly
||
null
,
maintenance_monthly: data.maintenance_monthly
||
null
,
other_monthly: data.other_monthly
||
null
,
total_annual: data.total_annual
||
null
,
total_monthly: data.total_monthly
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await holding_costs.setAnalysis( data.analysis || null, {
transaction,
});
await holding_costs.setOrganizations( data.organizations || null, {
transaction,
});
return holding_costs;
}
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 holding_costsData = data.map((item, index) => ({
id: item.id || undefined,
iptu_annual: item.iptu_annual
||
null
,
security_monthly: item.security_monthly
||
null
,
maintenance_monthly: item.maintenance_monthly
||
null
,
other_monthly: item.other_monthly
||
null
,
total_annual: item.total_annual
||
null
,
total_monthly: item.total_monthly
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const holding_costs = await db.holding_costs.bulkCreate(holding_costsData, { transaction });
// For each item created, replace relation files
return holding_costs;
}
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 holding_costs = await db.holding_costs.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.iptu_annual !== undefined) updatePayload.iptu_annual = data.iptu_annual;
if (data.security_monthly !== undefined) updatePayload.security_monthly = data.security_monthly;
if (data.maintenance_monthly !== undefined) updatePayload.maintenance_monthly = data.maintenance_monthly;
if (data.other_monthly !== undefined) updatePayload.other_monthly = data.other_monthly;
if (data.total_annual !== undefined) updatePayload.total_annual = data.total_annual;
if (data.total_monthly !== undefined) updatePayload.total_monthly = data.total_monthly;
updatePayload.updatedById = currentUser.id;
await holding_costs.update(updatePayload, {transaction});
if (data.analysis !== undefined) {
await holding_costs.setAnalysis(
data.analysis,
{ transaction }
);
}
if (data.organizations !== undefined) {
await holding_costs.setOrganizations(
data.organizations,
{ transaction }
);
}
return holding_costs;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const holding_costs = await db.holding_costs.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of holding_costs) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of holding_costs) {
await record.destroy({transaction});
}
});
return holding_costs;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const holding_costs = await db.holding_costs.findByPk(id, options);
await holding_costs.update({
deletedBy: currentUser.id
}, {
transaction,
});
await holding_costs.destroy({
transaction
});
return holding_costs;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const holding_costs = await db.holding_costs.findOne(
{ where },
{ transaction },
);
if (!holding_costs) {
return holding_costs;
}
const output = holding_costs.get({plain: true});
output.analysis = await holding_costs.getAnalysis({
transaction
});
output.organizations = await holding_costs.getOrganizations({
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 userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.analyses,
as: 'analysis',
where: filter.analysis ? {
[Op.or]: [
{ id: { [Op.in]: filter.analysis.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.analysis.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.iptu_annualRange) {
const [start, end] = filter.iptu_annualRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
iptu_annual: {
...where.iptu_annual,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
iptu_annual: {
...where.iptu_annual,
[Op.lte]: end,
},
};
}
}
if (filter.security_monthlyRange) {
const [start, end] = filter.security_monthlyRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
security_monthly: {
...where.security_monthly,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
security_monthly: {
...where.security_monthly,
[Op.lte]: end,
},
};
}
}
if (filter.maintenance_monthlyRange) {
const [start, end] = filter.maintenance_monthlyRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
maintenance_monthly: {
...where.maintenance_monthly,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
maintenance_monthly: {
...where.maintenance_monthly,
[Op.lte]: end,
},
};
}
}
if (filter.other_monthlyRange) {
const [start, end] = filter.other_monthlyRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
other_monthly: {
...where.other_monthly,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
other_monthly: {
...where.other_monthly,
[Op.lte]: end,
},
};
}
}
if (filter.total_annualRange) {
const [start, end] = filter.total_annualRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
total_annual: {
...where.total_annual,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
total_annual: {
...where.total_annual,
[Op.lte]: end,
},
};
}
}
if (filter.total_monthlyRange) {
const [start, end] = filter.total_monthlyRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
total_monthly: {
...where.total_monthly,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
total_monthly: {
...where.total_monthly,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[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.organizationsId;
}
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.holding_costs.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(
'holding_costs',
'total_annual',
query,
),
],
};
}
const records = await db.holding_costs.findAll({
attributes: [ 'id', 'total_annual' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['total_annual', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.total_annual,
}));
}
};

View File

@ -0,0 +1,452 @@
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 Housing_programsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const housing_programs = await db.housing_programs.create(
{
id: data.id || undefined,
code: data.code
||
null
,
label: data.label
||
null
,
is_default: data.is_default
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await housing_programs.setOrganizations( data.organizations || null, {
transaction,
});
return housing_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 housing_programsData = data.map((item, index) => ({
id: item.id || undefined,
code: item.code
||
null
,
label: item.label
||
null
,
is_default: item.is_default
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const housing_programs = await db.housing_programs.bulkCreate(housing_programsData, { transaction });
// For each item created, replace relation files
return housing_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 housing_programs = await db.housing_programs.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.code !== undefined) updatePayload.code = data.code;
if (data.label !== undefined) updatePayload.label = data.label;
if (data.is_default !== undefined) updatePayload.is_default = data.is_default;
updatePayload.updatedById = currentUser.id;
await housing_programs.update(updatePayload, {transaction});
if (data.organizations !== undefined) {
await housing_programs.setOrganizations(
data.organizations,
{ transaction }
);
}
return housing_programs;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const housing_programs = await db.housing_programs.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of housing_programs) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of housing_programs) {
await record.destroy({transaction});
}
});
return housing_programs;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const housing_programs = await db.housing_programs.findByPk(id, options);
await housing_programs.update({
deletedBy: currentUser.id
}, {
transaction,
});
await housing_programs.destroy({
transaction
});
return housing_programs;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const housing_programs = await db.housing_programs.findOne(
{ where },
{ transaction },
);
if (!housing_programs) {
return housing_programs;
}
const output = housing_programs.get({plain: true});
output.analysis_programs_housing_program = await housing_programs.getAnalysis_programs_housing_program({
transaction
});
output.organizations = await housing_programs.getOrganizations({
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 userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.code) {
where = {
...where,
[Op.and]: Utils.ilike(
'housing_programs',
'code',
filter.code,
),
};
}
if (filter.label) {
where = {
...where,
[Op.and]: Utils.ilike(
'housing_programs',
'label',
filter.label,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.is_default) {
where = {
...where,
is_default: filter.is_default,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[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.organizationsId;
}
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.housing_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(
'housing_programs',
'label',
query,
),
],
};
}
const records = await db.housing_programs.findAll({
attributes: [ 'id', 'label' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['label', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.label,
}));
}
};

View File

@ -0,0 +1,472 @@
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 Infrastructure_itemsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const infrastructure_items = await db.infrastructure_items.create(
{
id: data.id || undefined,
code: data.code
||
null
,
label: data.label
||
null
,
category: data.category
||
null
,
is_default: data.is_default
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await infrastructure_items.setOrganizations( data.organizations || null, {
transaction,
});
return infrastructure_items;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const infrastructure_itemsData = data.map((item, index) => ({
id: item.id || undefined,
code: item.code
||
null
,
label: item.label
||
null
,
category: item.category
||
null
,
is_default: item.is_default
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const infrastructure_items = await db.infrastructure_items.bulkCreate(infrastructure_itemsData, { transaction });
// For each item created, replace relation files
return infrastructure_items;
}
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 infrastructure_items = await db.infrastructure_items.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.code !== undefined) updatePayload.code = data.code;
if (data.label !== undefined) updatePayload.label = data.label;
if (data.category !== undefined) updatePayload.category = data.category;
if (data.is_default !== undefined) updatePayload.is_default = data.is_default;
updatePayload.updatedById = currentUser.id;
await infrastructure_items.update(updatePayload, {transaction});
if (data.organizations !== undefined) {
await infrastructure_items.setOrganizations(
data.organizations,
{ transaction }
);
}
return infrastructure_items;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const infrastructure_items = await db.infrastructure_items.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of infrastructure_items) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of infrastructure_items) {
await record.destroy({transaction});
}
});
return infrastructure_items;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const infrastructure_items = await db.infrastructure_items.findByPk(id, options);
await infrastructure_items.update({
deletedBy: currentUser.id
}, {
transaction,
});
await infrastructure_items.destroy({
transaction
});
return infrastructure_items;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const infrastructure_items = await db.infrastructure_items.findOne(
{ where },
{ transaction },
);
if (!infrastructure_items) {
return infrastructure_items;
}
const output = infrastructure_items.get({plain: true});
output.analysis_infrastructure_infrastructure_item = await infrastructure_items.getAnalysis_infrastructure_infrastructure_item({
transaction
});
output.organizations = await infrastructure_items.getOrganizations({
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 userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.code) {
where = {
...where,
[Op.and]: Utils.ilike(
'infrastructure_items',
'code',
filter.code,
),
};
}
if (filter.label) {
where = {
...where,
[Op.and]: Utils.ilike(
'infrastructure_items',
'label',
filter.label,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.category) {
where = {
...where,
category: filter.category,
};
}
if (filter.is_default) {
where = {
...where,
is_default: filter.is_default,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[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.organizationsId;
}
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.infrastructure_items.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'infrastructure_items',
'label',
query,
),
],
};
}
const records = await db.infrastructure_items.findAll({
attributes: [ 'id', 'label' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['label', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.label,
}));
}
};

View File

@ -0,0 +1,882 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Market_assessmentsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const market_assessments = await db.market_assessments.create(
{
id: data.id || undefined,
unit_price_min: data.unit_price_min
||
null
,
unit_price_avg: data.unit_price_avg
||
null
,
unit_price_max: data.unit_price_max
||
null
,
total_value_min: data.total_value_min
||
null
,
total_value_avg: data.total_value_avg
||
null
,
total_value_max: data.total_value_max
||
null
,
price_trend_3y: data.price_trend_3y
||
null
,
absorption_speed: data.absorption_speed
||
null
,
vacancy_level: data.vacancy_level
||
null
,
tma_pct: data.tma_pct
||
null
,
forced_liquidation_months: data.forced_liquidation_months
||
null
,
declared_liquidation_factor: data.declared_liquidation_factor
||
null
,
theoretical_liquidation_factor: data.theoretical_liquidation_factor
||
null
,
transaction_costs_pct: data.transaction_costs_pct
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await market_assessments.setAnalysis( data.analysis || null, {
transaction,
});
await market_assessments.setOrganizations( data.organizations || null, {
transaction,
});
return market_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 market_assessmentsData = data.map((item, index) => ({
id: item.id || undefined,
unit_price_min: item.unit_price_min
||
null
,
unit_price_avg: item.unit_price_avg
||
null
,
unit_price_max: item.unit_price_max
||
null
,
total_value_min: item.total_value_min
||
null
,
total_value_avg: item.total_value_avg
||
null
,
total_value_max: item.total_value_max
||
null
,
price_trend_3y: item.price_trend_3y
||
null
,
absorption_speed: item.absorption_speed
||
null
,
vacancy_level: item.vacancy_level
||
null
,
tma_pct: item.tma_pct
||
null
,
forced_liquidation_months: item.forced_liquidation_months
||
null
,
declared_liquidation_factor: item.declared_liquidation_factor
||
null
,
theoretical_liquidation_factor: item.theoretical_liquidation_factor
||
null
,
transaction_costs_pct: item.transaction_costs_pct
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const market_assessments = await db.market_assessments.bulkCreate(market_assessmentsData, { transaction });
// For each item created, replace relation files
return market_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 market_assessments = await db.market_assessments.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.unit_price_min !== undefined) updatePayload.unit_price_min = data.unit_price_min;
if (data.unit_price_avg !== undefined) updatePayload.unit_price_avg = data.unit_price_avg;
if (data.unit_price_max !== undefined) updatePayload.unit_price_max = data.unit_price_max;
if (data.total_value_min !== undefined) updatePayload.total_value_min = data.total_value_min;
if (data.total_value_avg !== undefined) updatePayload.total_value_avg = data.total_value_avg;
if (data.total_value_max !== undefined) updatePayload.total_value_max = data.total_value_max;
if (data.price_trend_3y !== undefined) updatePayload.price_trend_3y = data.price_trend_3y;
if (data.absorption_speed !== undefined) updatePayload.absorption_speed = data.absorption_speed;
if (data.vacancy_level !== undefined) updatePayload.vacancy_level = data.vacancy_level;
if (data.tma_pct !== undefined) updatePayload.tma_pct = data.tma_pct;
if (data.forced_liquidation_months !== undefined) updatePayload.forced_liquidation_months = data.forced_liquidation_months;
if (data.declared_liquidation_factor !== undefined) updatePayload.declared_liquidation_factor = data.declared_liquidation_factor;
if (data.theoretical_liquidation_factor !== undefined) updatePayload.theoretical_liquidation_factor = data.theoretical_liquidation_factor;
if (data.transaction_costs_pct !== undefined) updatePayload.transaction_costs_pct = data.transaction_costs_pct;
updatePayload.updatedById = currentUser.id;
await market_assessments.update(updatePayload, {transaction});
if (data.analysis !== undefined) {
await market_assessments.setAnalysis(
data.analysis,
{ transaction }
);
}
if (data.organizations !== undefined) {
await market_assessments.setOrganizations(
data.organizations,
{ transaction }
);
}
return market_assessments;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const market_assessments = await db.market_assessments.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of market_assessments) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of market_assessments) {
await record.destroy({transaction});
}
});
return market_assessments;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const market_assessments = await db.market_assessments.findByPk(id, options);
await market_assessments.update({
deletedBy: currentUser.id
}, {
transaction,
});
await market_assessments.destroy({
transaction
});
return market_assessments;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const market_assessments = await db.market_assessments.findOne(
{ where },
{ transaction },
);
if (!market_assessments) {
return market_assessments;
}
const output = market_assessments.get({plain: true});
output.analysis = await market_assessments.getAnalysis({
transaction
});
output.organizations = await market_assessments.getOrganizations({
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 userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.analyses,
as: 'analysis',
where: filter.analysis ? {
[Op.or]: [
{ id: { [Op.in]: filter.analysis.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.analysis.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.unit_price_minRange) {
const [start, end] = filter.unit_price_minRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
unit_price_min: {
...where.unit_price_min,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
unit_price_min: {
...where.unit_price_min,
[Op.lte]: end,
},
};
}
}
if (filter.unit_price_avgRange) {
const [start, end] = filter.unit_price_avgRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
unit_price_avg: {
...where.unit_price_avg,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
unit_price_avg: {
...where.unit_price_avg,
[Op.lte]: end,
},
};
}
}
if (filter.unit_price_maxRange) {
const [start, end] = filter.unit_price_maxRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
unit_price_max: {
...where.unit_price_max,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
unit_price_max: {
...where.unit_price_max,
[Op.lte]: end,
},
};
}
}
if (filter.total_value_minRange) {
const [start, end] = filter.total_value_minRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
total_value_min: {
...where.total_value_min,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
total_value_min: {
...where.total_value_min,
[Op.lte]: end,
},
};
}
}
if (filter.total_value_avgRange) {
const [start, end] = filter.total_value_avgRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
total_value_avg: {
...where.total_value_avg,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
total_value_avg: {
...where.total_value_avg,
[Op.lte]: end,
},
};
}
}
if (filter.total_value_maxRange) {
const [start, end] = filter.total_value_maxRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
total_value_max: {
...where.total_value_max,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
total_value_max: {
...where.total_value_max,
[Op.lte]: end,
},
};
}
}
if (filter.tma_pctRange) {
const [start, end] = filter.tma_pctRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
tma_pct: {
...where.tma_pct,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
tma_pct: {
...where.tma_pct,
[Op.lte]: end,
},
};
}
}
if (filter.forced_liquidation_monthsRange) {
const [start, end] = filter.forced_liquidation_monthsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
forced_liquidation_months: {
...where.forced_liquidation_months,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
forced_liquidation_months: {
...where.forced_liquidation_months,
[Op.lte]: end,
},
};
}
}
if (filter.declared_liquidation_factorRange) {
const [start, end] = filter.declared_liquidation_factorRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
declared_liquidation_factor: {
...where.declared_liquidation_factor,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
declared_liquidation_factor: {
...where.declared_liquidation_factor,
[Op.lte]: end,
},
};
}
}
if (filter.theoretical_liquidation_factorRange) {
const [start, end] = filter.theoretical_liquidation_factorRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
theoretical_liquidation_factor: {
...where.theoretical_liquidation_factor,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
theoretical_liquidation_factor: {
...where.theoretical_liquidation_factor,
[Op.lte]: end,
},
};
}
}
if (filter.transaction_costs_pctRange) {
const [start, end] = filter.transaction_costs_pctRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
transaction_costs_pct: {
...where.transaction_costs_pct,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
transaction_costs_pct: {
...where.transaction_costs_pct,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.price_trend_3y) {
where = {
...where,
price_trend_3y: filter.price_trend_3y,
};
}
if (filter.absorption_speed) {
where = {
...where,
absorption_speed: filter.absorption_speed,
};
}
if (filter.vacancy_level) {
where = {
...where,
vacancy_level: filter.vacancy_level,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[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.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.market_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(
'market_assessments',
'price_trend_3y',
query,
),
],
};
}
const records = await db.market_assessments.findAll({
attributes: [ 'id', 'price_trend_3y' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['price_trend_3y', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.price_trend_3y,
}));
}
};

View File

@ -0,0 +1,441 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class OrganizationsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const organizations = await db.organizations.create(
{
id: data.id || undefined,
name: data.name
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return organizations;
}
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 organizationsData = 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 organizations = await db.organizations.bulkCreate(organizationsData, { transaction });
// For each item created, replace relation files
return organizations;
}
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 organizations = await db.organizations.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
updatePayload.updatedById = currentUser.id;
await organizations.update(updatePayload, {transaction});
return organizations;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const organizations = await db.organizations.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of organizations) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of organizations) {
await record.destroy({transaction});
}
});
return organizations;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const organizations = await db.organizations.findByPk(id, options);
await organizations.update({
deletedBy: currentUser.id
}, {
transaction,
});
await organizations.destroy({
transaction
});
return organizations;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const organizations = await db.organizations.findOne(
{ where },
{ transaction },
);
if (!organizations) {
return organizations;
}
const output = organizations.get({plain: true});
output.users_organizations = await organizations.getUsers_organizations({
transaction
});
output.clients_organization = await organizations.getClients_organization({
transaction
});
output.assets_organizations = await organizations.getAssets_organizations({
transaction
});
output.analyses_organizations = await organizations.getAnalyses_organizations({
transaction
});
output.client_profiles_organizations = await organizations.getClient_profiles_organizations({
transaction
});
output.urbanistic_parameters_organizations = await organizations.getUrbanistic_parameters_organizations({
transaction
});
output.environmental_constraints_organizations = await organizations.getEnvironmental_constraints_organizations({
transaction
});
output.infrastructure_items_organizations = await organizations.getInfrastructure_items_organizations({
transaction
});
output.analysis_infrastructure_organizations = await organizations.getAnalysis_infrastructure_organizations({
transaction
});
output.socioeconomic_profiles_organizations = await organizations.getSocioeconomic_profiles_organizations({
transaction
});
output.housing_programs_organizations = await organizations.getHousing_programs_organizations({
transaction
});
output.analysis_programs_organizations = await organizations.getAnalysis_programs_organizations({
transaction
});
output.vocation_options_organizations = await organizations.getVocation_options_organizations({
transaction
});
output.analysis_vocation_results_organizations = await organizations.getAnalysis_vocation_results_organizations({
transaction
});
output.market_assessments_organizations = await organizations.getMarket_assessments_organizations({
transaction
});
output.holding_costs_organizations = await organizations.getHolding_costs_organizations({
transaction
});
output.external_value_vectors_organizations = await organizations.getExternal_value_vectors_organizations({
transaction
});
output.development_alternatives_organizations = await organizations.getDevelopment_alternatives_organizations({
transaction
});
output.dashboard_summaries_organizations = await organizations.getDashboard_summaries_organizations({
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 userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
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(
'organizations',
'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.organizationsId;
}
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.organizations.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(
'organizations',
'name',
query,
),
],
};
}
const records = await db.organizations.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,351 @@
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 userOrganizations = (user && user.organizations?.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,
}));
}
};

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

@ -0,0 +1,453 @@
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 userOrganizations = (user && user.organizations?.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,475 @@
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 Socioeconomic_profilesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const socioeconomic_profiles = await db.socioeconomic_profiles.create(
{
id: data.id || undefined,
income_band: data.income_band
||
null
,
demand_profile: data.demand_profile
||
null
,
population_dynamics: data.population_dynamics
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await socioeconomic_profiles.setAnalysis( data.analysis || null, {
transaction,
});
await socioeconomic_profiles.setOrganizations( data.organizations || null, {
transaction,
});
return socioeconomic_profiles;
}
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 socioeconomic_profilesData = data.map((item, index) => ({
id: item.id || undefined,
income_band: item.income_band
||
null
,
demand_profile: item.demand_profile
||
null
,
population_dynamics: item.population_dynamics
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const socioeconomic_profiles = await db.socioeconomic_profiles.bulkCreate(socioeconomic_profilesData, { transaction });
// For each item created, replace relation files
return socioeconomic_profiles;
}
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 socioeconomic_profiles = await db.socioeconomic_profiles.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.income_band !== undefined) updatePayload.income_band = data.income_band;
if (data.demand_profile !== undefined) updatePayload.demand_profile = data.demand_profile;
if (data.population_dynamics !== undefined) updatePayload.population_dynamics = data.population_dynamics;
updatePayload.updatedById = currentUser.id;
await socioeconomic_profiles.update(updatePayload, {transaction});
if (data.analysis !== undefined) {
await socioeconomic_profiles.setAnalysis(
data.analysis,
{ transaction }
);
}
if (data.organizations !== undefined) {
await socioeconomic_profiles.setOrganizations(
data.organizations,
{ transaction }
);
}
return socioeconomic_profiles;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const socioeconomic_profiles = await db.socioeconomic_profiles.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of socioeconomic_profiles) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of socioeconomic_profiles) {
await record.destroy({transaction});
}
});
return socioeconomic_profiles;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const socioeconomic_profiles = await db.socioeconomic_profiles.findByPk(id, options);
await socioeconomic_profiles.update({
deletedBy: currentUser.id
}, {
transaction,
});
await socioeconomic_profiles.destroy({
transaction
});
return socioeconomic_profiles;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const socioeconomic_profiles = await db.socioeconomic_profiles.findOne(
{ where },
{ transaction },
);
if (!socioeconomic_profiles) {
return socioeconomic_profiles;
}
const output = socioeconomic_profiles.get({plain: true});
output.analysis = await socioeconomic_profiles.getAnalysis({
transaction
});
output.organizations = await socioeconomic_profiles.getOrganizations({
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 userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.analyses,
as: 'analysis',
where: filter.analysis ? {
[Op.or]: [
{ id: { [Op.in]: filter.analysis.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.analysis.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.income_band) {
where = {
...where,
income_band: filter.income_band,
};
}
if (filter.demand_profile) {
where = {
...where,
demand_profile: filter.demand_profile,
};
}
if (filter.population_dynamics) {
where = {
...where,
population_dynamics: filter.population_dynamics,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[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.organizationsId;
}
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.socioeconomic_profiles.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(
'socioeconomic_profiles',
'demand_profile',
query,
),
],
};
}
const records = await db.socioeconomic_profiles.findAll({
attributes: [ 'id', 'demand_profile' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['demand_profile', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.demand_profile,
}));
}
};

View File

@ -0,0 +1,973 @@
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 Urbanistic_parametersDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const urbanistic_parameters = await db.urbanistic_parameters.create(
{
id: data.id || undefined,
zoning: data.zoning
||
null
,
main_access: data.main_access
||
null
,
ca_basic: data.ca_basic
||
null
,
ca_max: data.ca_max
||
null
,
occupancy_rate_pct: data.occupancy_rate_pct
||
null
,
permeability_rate_pct: data.permeability_rate_pct
||
null
,
height_limit_floors: data.height_limit_floors
||
null
,
height_limit_meters: data.height_limit_meters
||
null
,
front_setback_m: data.front_setback_m
||
null
,
side_setback_m: data.side_setback_m
||
null
,
rear_setback_m: data.rear_setback_m
||
null
,
between_blocks_setback_m: data.between_blocks_setback_m
||
null
,
buildable_area_basic_m2: data.buildable_area_basic_m2
||
null
,
buildable_area_max_m2: data.buildable_area_max_m2
||
null
,
ground_projection_max_m2: data.ground_projection_max_m2
||
null
,
permeable_area_min_m2: data.permeable_area_min_m2
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await urbanistic_parameters.setAnalysis( data.analysis || null, {
transaction,
});
await urbanistic_parameters.setOrganizations( data.organizations || null, {
transaction,
});
return urbanistic_parameters;
}
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 urbanistic_parametersData = data.map((item, index) => ({
id: item.id || undefined,
zoning: item.zoning
||
null
,
main_access: item.main_access
||
null
,
ca_basic: item.ca_basic
||
null
,
ca_max: item.ca_max
||
null
,
occupancy_rate_pct: item.occupancy_rate_pct
||
null
,
permeability_rate_pct: item.permeability_rate_pct
||
null
,
height_limit_floors: item.height_limit_floors
||
null
,
height_limit_meters: item.height_limit_meters
||
null
,
front_setback_m: item.front_setback_m
||
null
,
side_setback_m: item.side_setback_m
||
null
,
rear_setback_m: item.rear_setback_m
||
null
,
between_blocks_setback_m: item.between_blocks_setback_m
||
null
,
buildable_area_basic_m2: item.buildable_area_basic_m2
||
null
,
buildable_area_max_m2: item.buildable_area_max_m2
||
null
,
ground_projection_max_m2: item.ground_projection_max_m2
||
null
,
permeable_area_min_m2: item.permeable_area_min_m2
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const urbanistic_parameters = await db.urbanistic_parameters.bulkCreate(urbanistic_parametersData, { transaction });
// For each item created, replace relation files
return urbanistic_parameters;
}
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 urbanistic_parameters = await db.urbanistic_parameters.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.zoning !== undefined) updatePayload.zoning = data.zoning;
if (data.main_access !== undefined) updatePayload.main_access = data.main_access;
if (data.ca_basic !== undefined) updatePayload.ca_basic = data.ca_basic;
if (data.ca_max !== undefined) updatePayload.ca_max = data.ca_max;
if (data.occupancy_rate_pct !== undefined) updatePayload.occupancy_rate_pct = data.occupancy_rate_pct;
if (data.permeability_rate_pct !== undefined) updatePayload.permeability_rate_pct = data.permeability_rate_pct;
if (data.height_limit_floors !== undefined) updatePayload.height_limit_floors = data.height_limit_floors;
if (data.height_limit_meters !== undefined) updatePayload.height_limit_meters = data.height_limit_meters;
if (data.front_setback_m !== undefined) updatePayload.front_setback_m = data.front_setback_m;
if (data.side_setback_m !== undefined) updatePayload.side_setback_m = data.side_setback_m;
if (data.rear_setback_m !== undefined) updatePayload.rear_setback_m = data.rear_setback_m;
if (data.between_blocks_setback_m !== undefined) updatePayload.between_blocks_setback_m = data.between_blocks_setback_m;
if (data.buildable_area_basic_m2 !== undefined) updatePayload.buildable_area_basic_m2 = data.buildable_area_basic_m2;
if (data.buildable_area_max_m2 !== undefined) updatePayload.buildable_area_max_m2 = data.buildable_area_max_m2;
if (data.ground_projection_max_m2 !== undefined) updatePayload.ground_projection_max_m2 = data.ground_projection_max_m2;
if (data.permeable_area_min_m2 !== undefined) updatePayload.permeable_area_min_m2 = data.permeable_area_min_m2;
updatePayload.updatedById = currentUser.id;
await urbanistic_parameters.update(updatePayload, {transaction});
if (data.analysis !== undefined) {
await urbanistic_parameters.setAnalysis(
data.analysis,
{ transaction }
);
}
if (data.organizations !== undefined) {
await urbanistic_parameters.setOrganizations(
data.organizations,
{ transaction }
);
}
return urbanistic_parameters;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const urbanistic_parameters = await db.urbanistic_parameters.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of urbanistic_parameters) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of urbanistic_parameters) {
await record.destroy({transaction});
}
});
return urbanistic_parameters;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const urbanistic_parameters = await db.urbanistic_parameters.findByPk(id, options);
await urbanistic_parameters.update({
deletedBy: currentUser.id
}, {
transaction,
});
await urbanistic_parameters.destroy({
transaction
});
return urbanistic_parameters;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const urbanistic_parameters = await db.urbanistic_parameters.findOne(
{ where },
{ transaction },
);
if (!urbanistic_parameters) {
return urbanistic_parameters;
}
const output = urbanistic_parameters.get({plain: true});
output.analysis = await urbanistic_parameters.getAnalysis({
transaction
});
output.organizations = await urbanistic_parameters.getOrganizations({
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 userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.analyses,
as: 'analysis',
where: filter.analysis ? {
[Op.or]: [
{ id: { [Op.in]: filter.analysis.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.analysis.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.ca_basicRange) {
const [start, end] = filter.ca_basicRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
ca_basic: {
...where.ca_basic,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
ca_basic: {
...where.ca_basic,
[Op.lte]: end,
},
};
}
}
if (filter.ca_maxRange) {
const [start, end] = filter.ca_maxRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
ca_max: {
...where.ca_max,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
ca_max: {
...where.ca_max,
[Op.lte]: end,
},
};
}
}
if (filter.occupancy_rate_pctRange) {
const [start, end] = filter.occupancy_rate_pctRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
occupancy_rate_pct: {
...where.occupancy_rate_pct,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
occupancy_rate_pct: {
...where.occupancy_rate_pct,
[Op.lte]: end,
},
};
}
}
if (filter.permeability_rate_pctRange) {
const [start, end] = filter.permeability_rate_pctRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
permeability_rate_pct: {
...where.permeability_rate_pct,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
permeability_rate_pct: {
...where.permeability_rate_pct,
[Op.lte]: end,
},
};
}
}
if (filter.height_limit_floorsRange) {
const [start, end] = filter.height_limit_floorsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
height_limit_floors: {
...where.height_limit_floors,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
height_limit_floors: {
...where.height_limit_floors,
[Op.lte]: end,
},
};
}
}
if (filter.height_limit_metersRange) {
const [start, end] = filter.height_limit_metersRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
height_limit_meters: {
...where.height_limit_meters,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
height_limit_meters: {
...where.height_limit_meters,
[Op.lte]: end,
},
};
}
}
if (filter.front_setback_mRange) {
const [start, end] = filter.front_setback_mRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
front_setback_m: {
...where.front_setback_m,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
front_setback_m: {
...where.front_setback_m,
[Op.lte]: end,
},
};
}
}
if (filter.side_setback_mRange) {
const [start, end] = filter.side_setback_mRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
side_setback_m: {
...where.side_setback_m,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
side_setback_m: {
...where.side_setback_m,
[Op.lte]: end,
},
};
}
}
if (filter.rear_setback_mRange) {
const [start, end] = filter.rear_setback_mRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
rear_setback_m: {
...where.rear_setback_m,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
rear_setback_m: {
...where.rear_setback_m,
[Op.lte]: end,
},
};
}
}
if (filter.between_blocks_setback_mRange) {
const [start, end] = filter.between_blocks_setback_mRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
between_blocks_setback_m: {
...where.between_blocks_setback_m,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
between_blocks_setback_m: {
...where.between_blocks_setback_m,
[Op.lte]: end,
},
};
}
}
if (filter.buildable_area_basic_m2Range) {
const [start, end] = filter.buildable_area_basic_m2Range;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
buildable_area_basic_m2: {
...where.buildable_area_basic_m2,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
buildable_area_basic_m2: {
...where.buildable_area_basic_m2,
[Op.lte]: end,
},
};
}
}
if (filter.buildable_area_max_m2Range) {
const [start, end] = filter.buildable_area_max_m2Range;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
buildable_area_max_m2: {
...where.buildable_area_max_m2,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
buildable_area_max_m2: {
...where.buildable_area_max_m2,
[Op.lte]: end,
},
};
}
}
if (filter.ground_projection_max_m2Range) {
const [start, end] = filter.ground_projection_max_m2Range;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
ground_projection_max_m2: {
...where.ground_projection_max_m2,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
ground_projection_max_m2: {
...where.ground_projection_max_m2,
[Op.lte]: end,
},
};
}
}
if (filter.permeable_area_min_m2Range) {
const [start, end] = filter.permeable_area_min_m2Range;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
permeable_area_min_m2: {
...where.permeable_area_min_m2,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
permeable_area_min_m2: {
...where.permeable_area_min_m2,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.zoning) {
where = {
...where,
zoning: filter.zoning,
};
}
if (filter.main_access) {
where = {
...where,
main_access: filter.main_access,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[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.organizationsId;
}
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.urbanistic_parameters.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(
'urbanistic_parameters',
'zoning',
query,
),
],
};
}
const records = await db.urbanistic_parameters.findAll({
attributes: [ 'id', 'zoning' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['zoning', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.zoning,
}));
}
};

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

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,476 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Vocation_optionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const vocation_options = await db.vocation_options.create(
{
id: data.id || undefined,
code: data.code
||
null
,
name: data.name
||
null
,
subtitle: data.subtitle
||
null
,
is_default: data.is_default
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await vocation_options.setOrganizations( data.organizations || null, {
transaction,
});
return vocation_options;
}
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 vocation_optionsData = data.map((item, index) => ({
id: item.id || undefined,
code: item.code
||
null
,
name: item.name
||
null
,
subtitle: item.subtitle
||
null
,
is_default: item.is_default
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const vocation_options = await db.vocation_options.bulkCreate(vocation_optionsData, { transaction });
// For each item created, replace relation files
return vocation_options;
}
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 vocation_options = await db.vocation_options.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.code !== undefined) updatePayload.code = data.code;
if (data.name !== undefined) updatePayload.name = data.name;
if (data.subtitle !== undefined) updatePayload.subtitle = data.subtitle;
if (data.is_default !== undefined) updatePayload.is_default = data.is_default;
updatePayload.updatedById = currentUser.id;
await vocation_options.update(updatePayload, {transaction});
if (data.organizations !== undefined) {
await vocation_options.setOrganizations(
data.organizations,
{ transaction }
);
}
return vocation_options;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const vocation_options = await db.vocation_options.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of vocation_options) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of vocation_options) {
await record.destroy({transaction});
}
});
return vocation_options;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const vocation_options = await db.vocation_options.findByPk(id, options);
await vocation_options.update({
deletedBy: currentUser.id
}, {
transaction,
});
await vocation_options.destroy({
transaction
});
return vocation_options;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const vocation_options = await db.vocation_options.findOne(
{ where },
{ transaction },
);
if (!vocation_options) {
return vocation_options;
}
const output = vocation_options.get({plain: true});
output.analysis_vocation_results_vocation_option = await vocation_options.getAnalysis_vocation_results_vocation_option({
transaction
});
output.organizations = await vocation_options.getOrganizations({
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 userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.code) {
where = {
...where,
[Op.and]: Utils.ilike(
'vocation_options',
'code',
filter.code,
),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'vocation_options',
'name',
filter.name,
),
};
}
if (filter.subtitle) {
where = {
...where,
[Op.and]: Utils.ilike(
'vocation_options',
'subtitle',
filter.subtitle,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.is_default) {
where = {
...where,
is_default: filter.is_default,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[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.organizationsId;
}
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.vocation_options.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(
'vocation_options',
'name',
query,
),
],
};
}
const records = await db.vocation_options.findAll({
attributes: [ 'id', 'name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.name,
}));
}
};

View File

@ -0,0 +1,33 @@
module.exports = {
production: {
dialect: 'postgres',
username: process.env.DB_USER,
password: process.env.DB_PASS,
database: process.env.DB_NAME,
host: process.env.DB_HOST,
port: process.env.DB_PORT,
logging: console.log,
seederStorage: 'sequelize',
},
development: {
username: 'postgres',
dialect: 'postgres',
password: '',
database: 'db_epi_unified_vocacao_app',
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,296 @@
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 analyses = sequelize.define(
'analyses',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
title: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"draft",
"calculated",
"dashboard_generated",
"archived"
],
},
started_at: {
type: DataTypes.DATE,
},
calculated_at: {
type: DataTypes.DATE,
},
dashboard_generated_at: {
type: DataTypes.DATE,
},
classification: {
type: DataTypes.ENUM,
values: [
"OTIMA",
"TRANSITORIA",
"SUBOTIMA"
],
},
pending_data_notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
analyses.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.analyses.hasMany(db.client_profiles, {
as: 'client_profiles_analysis',
foreignKey: {
name: 'analysisId',
},
constraints: false,
});
db.analyses.hasMany(db.urbanistic_parameters, {
as: 'urbanistic_parameters_analysis',
foreignKey: {
name: 'analysisId',
},
constraints: false,
});
db.analyses.hasMany(db.environmental_constraints, {
as: 'environmental_constraints_analysis',
foreignKey: {
name: 'analysisId',
},
constraints: false,
});
db.analyses.hasMany(db.analysis_infrastructure, {
as: 'analysis_infrastructure_analysis',
foreignKey: {
name: 'analysisId',
},
constraints: false,
});
db.analyses.hasMany(db.socioeconomic_profiles, {
as: 'socioeconomic_profiles_analysis',
foreignKey: {
name: 'analysisId',
},
constraints: false,
});
db.analyses.hasMany(db.analysis_programs, {
as: 'analysis_programs_analysis',
foreignKey: {
name: 'analysisId',
},
constraints: false,
});
db.analyses.hasMany(db.analysis_vocation_results, {
as: 'analysis_vocation_results_analysis',
foreignKey: {
name: 'analysisId',
},
constraints: false,
});
db.analyses.hasMany(db.market_assessments, {
as: 'market_assessments_analysis',
foreignKey: {
name: 'analysisId',
},
constraints: false,
});
db.analyses.hasMany(db.holding_costs, {
as: 'holding_costs_analysis',
foreignKey: {
name: 'analysisId',
},
constraints: false,
});
db.analyses.hasMany(db.external_value_vectors, {
as: 'external_value_vectors_analysis',
foreignKey: {
name: 'analysisId',
},
constraints: false,
});
db.analyses.hasMany(db.development_alternatives, {
as: 'development_alternatives_analysis',
foreignKey: {
name: 'analysisId',
},
constraints: false,
});
db.analyses.hasMany(db.dashboard_summaries, {
as: 'dashboard_summaries_analysis',
foreignKey: {
name: 'analysisId',
},
constraints: false,
});
//end loop
db.analyses.belongsTo(db.assets, {
as: 'asset',
foreignKey: {
name: 'assetId',
},
constraints: false,
});
db.analyses.belongsTo(db.users, {
as: 'analyst',
foreignKey: {
name: 'analystId',
},
constraints: false,
});
db.analyses.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.analyses.hasMany(db.file, {
as: 'exported_json_file',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.analyses.getTableName(),
belongsToColumn: 'exported_json_file',
},
});
db.analyses.hasMany(db.file, {
as: 'exported_pdf_file',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.analyses.getTableName(),
belongsToColumn: 'exported_pdf_file',
},
});
db.analyses.belongsTo(db.users, {
as: 'createdBy',
});
db.analyses.belongsTo(db.users, {
as: 'updatedBy',
});
};
return analyses;
};

View File

@ -0,0 +1,121 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const analysis_infrastructure = sequelize.define(
'analysis_infrastructure',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
is_available: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
analysis_infrastructure.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.analysis_infrastructure.belongsTo(db.analyses, {
as: 'analysis',
foreignKey: {
name: 'analysisId',
},
constraints: false,
});
db.analysis_infrastructure.belongsTo(db.infrastructure_items, {
as: 'infrastructure_item',
foreignKey: {
name: 'infrastructure_itemId',
},
constraints: false,
});
db.analysis_infrastructure.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.analysis_infrastructure.belongsTo(db.users, {
as: 'createdBy',
});
db.analysis_infrastructure.belongsTo(db.users, {
as: 'updatedBy',
});
};
return analysis_infrastructure;
};

View File

@ -0,0 +1,121 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const analysis_programs = sequelize.define(
'analysis_programs',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
analysis_programs.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.analysis_programs.belongsTo(db.analyses, {
as: 'analysis',
foreignKey: {
name: 'analysisId',
},
constraints: false,
});
db.analysis_programs.belongsTo(db.housing_programs, {
as: 'housing_program',
foreignKey: {
name: 'housing_programId',
},
constraints: false,
});
db.analysis_programs.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.analysis_programs.belongsTo(db.users, {
as: 'createdBy',
});
db.analysis_programs.belongsTo(db.users, {
as: 'updatedBy',
});
};
return analysis_programs;
};

View File

@ -0,0 +1,142 @@
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 analysis_vocation_results = sequelize.define(
'analysis_vocation_results',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
raw_score: {
type: DataTypes.INTEGER,
},
normalized_score: {
type: DataTypes.INTEGER,
},
is_blocked: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
rank_position: {
type: DataTypes.INTEGER,
},
factors_json: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
analysis_vocation_results.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.analysis_vocation_results.belongsTo(db.analyses, {
as: 'analysis',
foreignKey: {
name: 'analysisId',
},
constraints: false,
});
db.analysis_vocation_results.belongsTo(db.vocation_options, {
as: 'vocation_option',
foreignKey: {
name: 'vocation_optionId',
},
constraints: false,
});
db.analysis_vocation_results.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.analysis_vocation_results.belongsTo(db.users, {
as: 'createdBy',
});
db.analysis_vocation_results.belongsTo(db.users, {
as: 'updatedBy',
});
};
return analysis_vocation_results;
};

View File

@ -0,0 +1,352 @@
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 assets = sequelize.define(
'assets',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
municipality_uf: {
type: DataTypes.TEXT,
},
owner_name: {
type: DataTypes.TEXT,
},
registry_number: {
type: DataTypes.TEXT,
},
appraisal_source: {
type: DataTypes.TEXT,
},
total_area_m2: {
type: DataTypes.DECIMAL,
},
total_area_ha: {
type: DataTypes.DECIMAL,
},
topography: {
type: DataTypes.ENUM,
values: [
"plana",
"suave",
"ondulada",
"forte",
"montanhosa"
],
},
shape: {
type: DataTypes.ENUM,
values: [
"regular",
"irregular",
"muito_irregular"
],
},
vegetation: {
type: DataTypes.ENUM,
values: [
"preservada",
"parcial",
"suprimida",
"sem"
],
},
current_occupation: {
type: DataTypes.ENUM,
values: [
"vago",
"parcial",
"edificado",
"irregular"
],
},
urban_distance_band: {
type: DataTypes.ENUM,
values: [
"dentro_malha_urbana",
"ate_10_km",
"km_10_30",
"km_30_60",
"acima_60_km"
],
},
logistics_distance_band: {
type: DataTypes.ENUM,
values: [
"adjacente_menos_5_km",
"proximo_5_20_km",
"moderado_20_50_km",
"distante_mais_50_km",
"nao_se_aplica"
],
},
biome_region: {
type: DataTypes.ENUM,
values: [
"amazonia",
"cerrado",
"mata_atlantica",
"caatinga",
"pantanal",
"pampa",
"costeiro",
"outro"
],
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
assets.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.assets.hasMany(db.analyses, {
as: 'analyses_asset',
foreignKey: {
name: 'assetId',
},
constraints: false,
});
//end loop
db.assets.belongsTo(db.clients, {
as: 'client',
foreignKey: {
name: 'clientId',
},
constraints: false,
});
db.assets.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.assets.hasMany(db.file, {
as: 'documents',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.assets.getTableName(),
belongsToColumn: 'documents',
},
});
db.assets.hasMany(db.file, {
as: 'images',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.assets.getTableName(),
belongsToColumn: 'images',
},
});
db.assets.belongsTo(db.users, {
as: 'createdBy',
});
db.assets.belongsTo(db.users, {
as: 'updatedBy',
});
};
return assets;
};

View File

@ -0,0 +1,172 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const client_profiles = sequelize.define(
'client_profiles',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
sale_motivation: {
type: DataTypes.ENUM,
values: [
"desinvest",
"urgencia",
"maxvalor",
"regulatorio"
],
},
fii_relationship: {
type: DataTypes.ENUM,
values: [
"estudo",
"fora",
"nd"
],
},
prazo_tolerance: {
type: DataTypes.INTEGER,
},
risco_tolerance: {
type: DataTypes.INTEGER,
},
capex_tolerance: {
type: DataTypes.INTEGER,
},
priority: {
type: DataTypes.INTEGER,
},
management_capacity: {
type: DataTypes.INTEGER,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
client_profiles.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.client_profiles.belongsTo(db.analyses, {
as: 'analysis',
foreignKey: {
name: 'analysisId',
},
constraints: false,
});
db.client_profiles.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.client_profiles.belongsTo(db.users, {
as: 'createdBy',
});
db.client_profiles.belongsTo(db.users, {
as: 'updatedBy',
});
};
return client_profiles;
};

View File

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

View File

@ -0,0 +1,159 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const dashboard_summaries = sequelize.define(
'dashboard_summaries',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
market_value_avg: {
type: DataTypes.DECIMAL,
},
npv_alienation_net: {
type: DataTypes.DECIMAL,
},
npv_forced_liquidation: {
type: DataTypes.DECIMAL,
},
npv_fractionated_sale: {
type: DataTypes.DECIMAL,
},
npv_development: {
type: DataTypes.DECIMAL,
},
optionality_score: {
type: DataTypes.INTEGER,
},
top_vocation_name: {
type: DataTypes.TEXT,
},
alerts_text: {
type: DataTypes.TEXT,
},
pendings_text: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
dashboard_summaries.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.dashboard_summaries.belongsTo(db.analyses, {
as: 'analysis',
foreignKey: {
name: 'analysisId',
},
constraints: false,
});
db.dashboard_summaries.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.dashboard_summaries.belongsTo(db.users, {
as: 'createdBy',
});
db.dashboard_summaries.belongsTo(db.users, {
as: 'updatedBy',
});
};
return dashboard_summaries;
};

View File

@ -0,0 +1,212 @@
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 development_alternatives = sequelize.define(
'development_alternatives',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
development_type: {
type: DataTypes.ENUM,
values: [
"nao_aplicavel",
"industrial",
"logistico",
"res_fechado",
"res_aberto",
"comercial",
"agroindustrial",
"rural",
"solar",
"carbono",
"mcmv",
"alto_padrao"
],
},
roads_public_area_pct: {
type: DataTypes.DECIMAL,
},
lot_sale_price_m2: {
type: DataTypes.DECIMAL,
},
infrastructure_cost_m2: {
type: DataTypes.DECIMAL,
},
projects_licenses_cost: {
type: DataTypes.DECIMAL,
},
total_term_years: {
type: DataTypes.DECIMAL,
},
fractionated_premium_pct: {
type: DataTypes.DECIMAL,
},
fractionated_absorption_years: {
type: DataTypes.DECIMAL,
},
subdivision_cost: {
type: DataTypes.DECIMAL,
},
computed_vpl_development: {
type: DataTypes.DECIMAL,
},
computed_vpl_fractionated: {
type: DataTypes.DECIMAL,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
development_alternatives.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.development_alternatives.belongsTo(db.analyses, {
as: 'analysis',
foreignKey: {
name: 'analysisId',
},
constraints: false,
});
db.development_alternatives.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.development_alternatives.belongsTo(db.users, {
as: 'createdBy',
});
db.development_alternatives.belongsTo(db.users, {
as: 'updatedBy',
});
};
return development_alternatives;
};

View File

@ -0,0 +1,185 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const environmental_constraints = sequelize.define(
'environmental_constraints',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
app_status: {
type: DataTypes.ENUM,
values: [
"sim_m2",
"sim_nd",
"nao",
"nd"
],
},
app_area_m2: {
type: DataTypes.DECIMAL,
},
rl_status: {
type: DataTypes.ENUM,
values: [
"sim_m2",
"sim_nd",
"nao",
"nd"
],
},
rl_area_m2: {
type: DataTypes.DECIMAL,
},
restricted_area_m2: {
type: DataTypes.DECIMAL,
},
restricted_area_pct: {
type: DataTypes.DECIMAL,
},
estimated_usable_area_m2: {
type: DataTypes.DECIMAL,
},
is_blocked_for_development: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
environmental_constraints.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.environmental_constraints.belongsTo(db.analyses, {
as: 'analysis',
foreignKey: {
name: 'analysisId',
},
constraints: false,
});
db.environmental_constraints.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.environmental_constraints.belongsTo(db.users, {
as: 'createdBy',
});
db.environmental_constraints.belongsTo(db.users, {
as: 'updatedBy',
});
};
return environmental_constraints;
};

View File

@ -0,0 +1,177 @@
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 external_value_vectors = sequelize.define(
'external_value_vectors',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
vector_type: {
type: DataTypes.ENUM,
values: [
"revital",
"infra",
"zoning",
"fiscal",
"hab",
"ancora",
"outro"
],
},
stage: {
type: DataTypes.ENUM,
values: [
"planejado",
"aprovado",
"obras",
"concluido"
],
},
name_description: {
type: DataTypes.TEXT,
},
base_points: {
type: DataTypes.INTEGER,
},
stage_multiplier: {
type: DataTypes.DECIMAL,
},
computed_points: {
type: DataTypes.INTEGER,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
external_value_vectors.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.external_value_vectors.belongsTo(db.analyses, {
as: 'analysis',
foreignKey: {
name: 'analysisId',
},
constraints: false,
});
db.external_value_vectors.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.external_value_vectors.belongsTo(db.users, {
as: 'createdBy',
});
db.external_value_vectors.belongsTo(db.users, {
as: 'updatedBy',
});
};
return external_value_vectors;
};

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,138 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const holding_costs = sequelize.define(
'holding_costs',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
iptu_annual: {
type: DataTypes.DECIMAL,
},
security_monthly: {
type: DataTypes.DECIMAL,
},
maintenance_monthly: {
type: DataTypes.DECIMAL,
},
other_monthly: {
type: DataTypes.DECIMAL,
},
total_annual: {
type: DataTypes.DECIMAL,
},
total_monthly: {
type: DataTypes.DECIMAL,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
holding_costs.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.holding_costs.belongsTo(db.analyses, {
as: 'analysis',
foreignKey: {
name: 'analysisId',
},
constraints: false,
});
db.holding_costs.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.holding_costs.belongsTo(db.users, {
as: 'createdBy',
});
db.holding_costs.belongsTo(db.users, {
as: 'updatedBy',
});
};
return holding_costs;
};

View File

@ -0,0 +1,120 @@
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 housing_programs = sequelize.define(
'housing_programs',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
code: {
type: DataTypes.TEXT,
},
label: {
type: DataTypes.TEXT,
},
is_default: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
housing_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.housing_programs.hasMany(db.analysis_programs, {
as: 'analysis_programs_housing_program',
foreignKey: {
name: 'housing_programId',
},
constraints: false,
});
//end loop
db.housing_programs.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.housing_programs.belongsTo(db.users, {
as: 'createdBy',
});
db.housing_programs.belongsTo(db.users, {
as: 'updatedBy',
});
};
return housing_programs;
};

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,139 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const infrastructure_items = sequelize.define(
'infrastructure_items',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
code: {
type: DataTypes.TEXT,
},
label: {
type: DataTypes.TEXT,
},
category: {
type: DataTypes.ENUM,
values: [
"utility",
"mobility",
"services"
],
},
is_default: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
infrastructure_items.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.infrastructure_items.hasMany(db.analysis_infrastructure, {
as: 'analysis_infrastructure_infrastructure_item',
foreignKey: {
name: 'infrastructure_itemId',
},
constraints: false,
});
//end loop
db.infrastructure_items.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.infrastructure_items.belongsTo(db.users, {
as: 'createdBy',
});
db.infrastructure_items.belongsTo(db.users, {
as: 'updatedBy',
});
};
return infrastructure_items;
};

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 market_assessments = sequelize.define(
'market_assessments',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
unit_price_min: {
type: DataTypes.DECIMAL,
},
unit_price_avg: {
type: DataTypes.DECIMAL,
},
unit_price_max: {
type: DataTypes.DECIMAL,
},
total_value_min: {
type: DataTypes.DECIMAL,
},
total_value_avg: {
type: DataTypes.DECIMAL,
},
total_value_max: {
type: DataTypes.DECIMAL,
},
price_trend_3y: {
type: DataTypes.ENUM,
values: [
"val_forte",
"val_mod",
"estavel",
"desval",
"nd"
],
},
absorption_speed: {
type: DataTypes.ENUM,
values: [
"rapida",
"media",
"lenta",
"nd"
],
},
vacancy_level: {
type: DataTypes.ENUM,
values: [
"baixa",
"media",
"alta",
"nd"
],
},
tma_pct: {
type: DataTypes.DECIMAL,
},
forced_liquidation_months: {
type: DataTypes.INTEGER,
},
declared_liquidation_factor: {
type: DataTypes.DECIMAL,
},
theoretical_liquidation_factor: {
type: DataTypes.DECIMAL,
},
transaction_costs_pct: {
type: DataTypes.DECIMAL,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
market_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.market_assessments.belongsTo(db.analyses, {
as: 'analysis',
foreignKey: {
name: 'analysisId',
},
constraints: false,
});
db.market_assessments.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.market_assessments.belongsTo(db.users, {
as: 'createdBy',
});
db.market_assessments.belongsTo(db.users, {
as: 'updatedBy',
});
};
return market_assessments;
};

View File

@ -0,0 +1,239 @@
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 organizations = sequelize.define(
'organizations',
{
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,
},
);
organizations.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.organizations.hasMany(db.users, {
as: 'users_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.clients, {
as: 'clients_organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.organizations.hasMany(db.assets, {
as: 'assets_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.analyses, {
as: 'analyses_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.client_profiles, {
as: 'client_profiles_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.urbanistic_parameters, {
as: 'urbanistic_parameters_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.environmental_constraints, {
as: 'environmental_constraints_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.infrastructure_items, {
as: 'infrastructure_items_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.analysis_infrastructure, {
as: 'analysis_infrastructure_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.socioeconomic_profiles, {
as: 'socioeconomic_profiles_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.housing_programs, {
as: 'housing_programs_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.analysis_programs, {
as: 'analysis_programs_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.vocation_options, {
as: 'vocation_options_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.analysis_vocation_results, {
as: 'analysis_vocation_results_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.market_assessments, {
as: 'market_assessments_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.holding_costs, {
as: 'holding_costs_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.external_value_vectors, {
as: 'external_value_vectors_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.development_alternatives, {
as: 'development_alternatives_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.dashboard_summaries, {
as: 'dashboard_summaries_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
//end loop
db.organizations.belongsTo(db.users, {
as: 'createdBy',
});
db.organizations.belongsTo(db.users, {
as: 'updatedBy',
});
};
return organizations;
};

View File

@ -0,0 +1,87 @@
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,130 @@
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,183 @@
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 socioeconomic_profiles = sequelize.define(
'socioeconomic_profiles',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
income_band: {
type: DataTypes.ENUM,
values: [
"baixa",
"media_baixa",
"media",
"media_alta",
"alta",
"nd"
],
},
demand_profile: {
type: DataTypes.ENUM,
values: [
"mcmv1",
"mcmv2",
"mcmv3",
"medio",
"alto",
"misto",
"comercial",
"nd"
],
},
population_dynamics: {
type: DataTypes.ENUM,
values: [
"cresc_forte",
"cresc_mod",
"estavel",
"declinio",
"nd"
],
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
socioeconomic_profiles.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.socioeconomic_profiles.belongsTo(db.analyses, {
as: 'analysis',
foreignKey: {
name: 'analysisId',
},
constraints: false,
});
db.socioeconomic_profiles.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.socioeconomic_profiles.belongsTo(db.users, {
as: 'createdBy',
});
db.socioeconomic_profiles.belongsTo(db.users, {
as: 'updatedBy',
});
};
return socioeconomic_profiles;
};

View File

@ -0,0 +1,250 @@
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 urbanistic_parameters = sequelize.define(
'urbanistic_parameters',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
zoning: {
type: DataTypes.ENUM,
values: [
"industrial",
"urb_industrial",
"rural",
"mista",
"residencial",
"comercial",
"nd"
],
},
main_access: {
type: DataTypes.ENUM,
values: [
"fed_pav",
"est_pav",
"mun_pav",
"nao_pav",
"sem"
],
},
ca_basic: {
type: DataTypes.DECIMAL,
},
ca_max: {
type: DataTypes.DECIMAL,
},
occupancy_rate_pct: {
type: DataTypes.DECIMAL,
},
permeability_rate_pct: {
type: DataTypes.DECIMAL,
},
height_limit_floors: {
type: DataTypes.INTEGER,
},
height_limit_meters: {
type: DataTypes.DECIMAL,
},
front_setback_m: {
type: DataTypes.DECIMAL,
},
side_setback_m: {
type: DataTypes.DECIMAL,
},
rear_setback_m: {
type: DataTypes.DECIMAL,
},
between_blocks_setback_m: {
type: DataTypes.DECIMAL,
},
buildable_area_basic_m2: {
type: DataTypes.DECIMAL,
},
buildable_area_max_m2: {
type: DataTypes.DECIMAL,
},
ground_projection_max_m2: {
type: DataTypes.DECIMAL,
},
permeable_area_min_m2: {
type: DataTypes.DECIMAL,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
urbanistic_parameters.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.urbanistic_parameters.belongsTo(db.analyses, {
as: 'analysis',
foreignKey: {
name: 'analysisId',
},
constraints: false,
});
db.urbanistic_parameters.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.urbanistic_parameters.belongsTo(db.users, {
as: 'createdBy',
});
db.urbanistic_parameters.belongsTo(db.users, {
as: 'updatedBy',
});
};
return urbanistic_parameters;
};

View File

@ -0,0 +1,261 @@
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.analyses, {
as: 'analyses_analyst',
foreignKey: {
name: 'analystId',
},
constraints: false,
});
//end loop
db.users.belongsTo(db.roles, {
as: 'app_role',
foreignKey: {
name: 'app_roleId',
},
constraints: false,
});
db.users.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
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,127 @@
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 vocation_options = sequelize.define(
'vocation_options',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
code: {
type: DataTypes.TEXT,
},
name: {
type: DataTypes.TEXT,
},
subtitle: {
type: DataTypes.TEXT,
},
is_default: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
vocation_options.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.vocation_options.hasMany(db.analysis_vocation_results, {
as: 'analysis_vocation_results_vocation_option',
foreignKey: {
name: 'vocation_optionId',
},
constraints: false,
});
//end loop
db.vocation_options.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.vocation_options.belongsTo(db.users, {
as: 'createdBy',
});
db.vocation_options.belongsTo(db.users, {
as: 'updatedBy',
});
};
return vocation_options;
};

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

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

@ -0,0 +1,219 @@
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 organizationsRoutes = require('./routes/organizations');
const clientsRoutes = require('./routes/clients');
const assetsRoutes = require('./routes/assets');
const analysesRoutes = require('./routes/analyses');
const client_profilesRoutes = require('./routes/client_profiles');
const urbanistic_parametersRoutes = require('./routes/urbanistic_parameters');
const environmental_constraintsRoutes = require('./routes/environmental_constraints');
const infrastructure_itemsRoutes = require('./routes/infrastructure_items');
const analysis_infrastructureRoutes = require('./routes/analysis_infrastructure');
const socioeconomic_profilesRoutes = require('./routes/socioeconomic_profiles');
const housing_programsRoutes = require('./routes/housing_programs');
const analysis_programsRoutes = require('./routes/analysis_programs');
const vocation_optionsRoutes = require('./routes/vocation_options');
const analysis_vocation_resultsRoutes = require('./routes/analysis_vocation_results');
const market_assessmentsRoutes = require('./routes/market_assessments');
const holding_costsRoutes = require('./routes/holding_costs');
const external_value_vectorsRoutes = require('./routes/external_value_vectors');
const development_alternativesRoutes = require('./routes/development_alternatives');
const dashboard_summariesRoutes = require('./routes/dashboard_summaries');
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: "EPI Unified Vocacao App",
description: "EPI Unified Vocacao App 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/organizations', passport.authenticate('jwt', {session: false}), organizationsRoutes);
app.use('/api/clients', passport.authenticate('jwt', {session: false}), clientsRoutes);
app.use('/api/assets', passport.authenticate('jwt', {session: false}), assetsRoutes);
app.use('/api/analyses', passport.authenticate('jwt', {session: false}), analysesRoutes);
app.use('/api/client_profiles', passport.authenticate('jwt', {session: false}), client_profilesRoutes);
app.use('/api/urbanistic_parameters', passport.authenticate('jwt', {session: false}), urbanistic_parametersRoutes);
app.use('/api/environmental_constraints', passport.authenticate('jwt', {session: false}), environmental_constraintsRoutes);
app.use('/api/infrastructure_items', passport.authenticate('jwt', {session: false}), infrastructure_itemsRoutes);
app.use('/api/analysis_infrastructure', passport.authenticate('jwt', {session: false}), analysis_infrastructureRoutes);
app.use('/api/socioeconomic_profiles', passport.authenticate('jwt', {session: false}), socioeconomic_profilesRoutes);
app.use('/api/housing_programs', passport.authenticate('jwt', {session: false}), housing_programsRoutes);
app.use('/api/analysis_programs', passport.authenticate('jwt', {session: false}), analysis_programsRoutes);
app.use('/api/vocation_options', passport.authenticate('jwt', {session: false}), vocation_optionsRoutes);
app.use('/api/analysis_vocation_results', passport.authenticate('jwt', {session: false}), analysis_vocation_resultsRoutes);
app.use('/api/market_assessments', passport.authenticate('jwt', {session: false}), market_assessmentsRoutes);
app.use('/api/holding_costs', passport.authenticate('jwt', {session: false}), holding_costsRoutes);
app.use('/api/external_value_vectors', passport.authenticate('jwt', {session: false}), external_value_vectorsRoutes);
app.use('/api/development_alternatives', passport.authenticate('jwt', {session: false}), development_alternativesRoutes);
app.use('/api/dashboard_summaries', passport.authenticate('jwt', {session: false}), dashboard_summariesRoutes);
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,445 @@
const express = require('express');
const AnalysesService = require('../services/analyses');
const AnalysesDBApi = require('../db/api/analyses');
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('analyses'));
/**
* @swagger
* components:
* schemas:
* Analyses:
* type: object
* properties:
* title:
* type: string
* default: title
* pending_data_notes:
* type: string
* default: pending_data_notes
*
*
*/
/**
* @swagger
* tags:
* name: Analyses
* description: The Analyses managing API
*/
/**
* @swagger
* /api/analyses:
* post:
* security:
* - bearerAuth: []
* tags: [Analyses]
* summary: Add new item
* description: Add new item
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Analyses"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Analyses"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*/
router.post('/', wrapAsync(async (req, res) => {
const referer = req.headers.referer || `${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await AnalysesService.create(req.body.data, req.currentUser, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/budgets/bulk-import:
* post:
* security:
* - bearerAuth: []
* tags: [Analyses]
* summary: Bulk import items
* description: Bulk import items
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated items
* type: array
* items:
* $ref: "#/components/schemas/Analyses"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Analyses"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*
*/
router.post('/bulk-import', wrapAsync(async (req, res) => {
const referer = req.headers.referer || `${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await AnalysesService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/analyses/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Analyses]
* summary: Update the data of the selected item
* description: Update the data of the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to update
* required: true
* schema:
* type: string
* requestBody:
* description: Set new item data
* required: true
* content:
* application/json:
* schema:
* properties:
* id:
* description: ID of the updated item
* type: string
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Analyses"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Analyses"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.put('/:id', wrapAsync(async (req, res) => {
await AnalysesService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/analyses/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Analyses]
* summary: Delete the selected item
* description: Delete the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to delete
* required: true
* schema:
* type: string
* responses:
* 200:
* description: The item was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Analyses"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.delete('/:id', wrapAsync(async (req, res) => {
await AnalysesService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/analyses/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Analyses]
* summary: Delete the selected item list
* description: Delete the selected item list
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* ids:
* description: IDs of the updated items
* type: array
* responses:
* 200:
* description: The items was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Analyses"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await AnalysesService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/analyses:
* get:
* security:
* - bearerAuth: []
* tags: [Analyses]
* summary: Get all analyses
* description: Get all analyses
* responses:
* 200:
* description: Analyses list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Analyses"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/', wrapAsync(async (req, res) => {
const filetype = req.query.filetype
const globalAccess = req.currentUser.app_role.globalAccess;
const currentUser = req.currentUser;
const payload = await AnalysesDBApi.findAll(
req.query, globalAccess, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','title','pending_data_notes',
'started_at','calculated_at','dashboard_generated_at',
];
const opts = { fields };
try {
const csv = parse(payload.rows, opts);
res.status(200).attachment(csv);
res.send(csv)
} catch (err) {
console.error(err);
}
} else {
res.status(200).send(payload);
}
}));
/**
* @swagger
* /api/analyses/count:
* get:
* security:
* - bearerAuth: []
* tags: [Analyses]
* summary: Count all analyses
* description: Count all analyses
* responses:
* 200:
* description: Analyses count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Analyses"
* 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 AnalysesDBApi.findAll(
req.query,
globalAccess,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/analyses/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Analyses]
* summary: Find all analyses that match search criteria
* description: Find all analyses that match search criteria
* responses:
* 200:
* description: Analyses list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Analyses"
* 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 AnalysesDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
globalAccess, organizationId,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/analyses/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Analyses]
* summary: Get selected item
* description: Get selected item
* parameters:
* - in: path
* name: id
* description: ID of item to get
* required: true
* schema:
* type: string
* responses:
* 200:
* description: Selected item successfully received
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Analyses"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.get('/:id', wrapAsync(async (req, res) => {
const payload = await AnalysesDBApi.findBy(
{ id: req.params.id },
);
res.status(200).send(payload);
}));
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

View File

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

View File

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

View File

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

View File

@ -0,0 +1,468 @@
const express = require('express');
const AssetsService = require('../services/assets');
const AssetsDBApi = require('../db/api/assets');
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('assets'));
/**
* @swagger
* components:
* schemas:
* Assets:
* type: object
* properties:
* name:
* type: string
* default: name
* municipality_uf:
* type: string
* default: municipality_uf
* owner_name:
* type: string
* default: owner_name
* registry_number:
* type: string
* default: registry_number
* appraisal_source:
* type: string
* default: appraisal_source
* notes:
* type: string
* default: notes
* total_area_m2:
* type: integer
* format: int64
* total_area_ha:
* type: integer
* format: int64
*
*
*
*
*
*
*
*/
/**
* @swagger
* tags:
* name: Assets
* description: The Assets managing API
*/
/**
* @swagger
* /api/assets:
* post:
* security:
* - bearerAuth: []
* tags: [Assets]
* 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/Assets"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Assets"
* 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 AssetsService.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: [Assets]
* 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/Assets"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Assets"
* 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 AssetsService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/assets/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Assets]
* 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/Assets"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Assets"
* 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 AssetsService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/assets/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Assets]
* 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/Assets"
* 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 AssetsService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/assets/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Assets]
* 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/Assets"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await AssetsService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/assets:
* get:
* security:
* - bearerAuth: []
* tags: [Assets]
* summary: Get all assets
* description: Get all assets
* responses:
* 200:
* description: Assets list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Assets"
* 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 AssetsDBApi.findAll(
req.query, globalAccess, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','name','municipality_uf','owner_name','registry_number','appraisal_source','notes',
'total_area_m2','total_area_ha',
];
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/assets/count:
* get:
* security:
* - bearerAuth: []
* tags: [Assets]
* summary: Count all assets
* description: Count all assets
* responses:
* 200:
* description: Assets count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Assets"
* 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 AssetsDBApi.findAll(
req.query,
globalAccess,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/assets/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Assets]
* summary: Find all assets that match search criteria
* description: Find all assets that match search criteria
* responses:
* 200:
* description: Assets list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Assets"
* 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 AssetsDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
globalAccess, organizationId,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/assets/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Assets]
* 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/Assets"
* 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 AssetsDBApi.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,454 @@
const express = require('express');
const Client_profilesService = require('../services/client_profiles');
const Client_profilesDBApi = require('../db/api/client_profiles');
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('client_profiles'));
/**
* @swagger
* components:
* schemas:
* Client_profiles:
* type: object
* properties:
* prazo_tolerance:
* type: integer
* format: int64
* risco_tolerance:
* type: integer
* format: int64
* capex_tolerance:
* type: integer
* format: int64
* priority:
* type: integer
* format: int64
* management_capacity:
* type: integer
* format: int64
*
*
*/
/**
* @swagger
* tags:
* name: Client_profiles
* description: The Client_profiles managing API
*/
/**
* @swagger
* /api/client_profiles:
* post:
* security:
* - bearerAuth: []
* tags: [Client_profiles]
* 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/Client_profiles"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Client_profiles"
* 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 Client_profilesService.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: [Client_profiles]
* 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/Client_profiles"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Client_profiles"
* 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 Client_profilesService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/client_profiles/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Client_profiles]
* 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/Client_profiles"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Client_profiles"
* 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 Client_profilesService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/client_profiles/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Client_profiles]
* 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/Client_profiles"
* 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 Client_profilesService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/client_profiles/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Client_profiles]
* 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/Client_profiles"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await Client_profilesService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/client_profiles:
* get:
* security:
* - bearerAuth: []
* tags: [Client_profiles]
* summary: Get all client_profiles
* description: Get all client_profiles
* responses:
* 200:
* description: Client_profiles list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Client_profiles"
* 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 Client_profilesDBApi.findAll(
req.query, globalAccess, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id',
'prazo_tolerance','risco_tolerance','capex_tolerance','priority','management_capacity',
];
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/client_profiles/count:
* get:
* security:
* - bearerAuth: []
* tags: [Client_profiles]
* summary: Count all client_profiles
* description: Count all client_profiles
* responses:
* 200:
* description: Client_profiles count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Client_profiles"
* 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 Client_profilesDBApi.findAll(
req.query,
globalAccess,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/client_profiles/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Client_profiles]
* summary: Find all client_profiles that match search criteria
* description: Find all client_profiles that match search criteria
* responses:
* 200:
* description: Client_profiles list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Client_profiles"
* 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 Client_profilesDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
globalAccess, organizationId,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/client_profiles/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Client_profiles]
* 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/Client_profiles"
* 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 Client_profilesDBApi.findBy(
{ id: req.params.id },
);
res.status(200).send(payload);
}));
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

View File

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

View File

View File

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

View File

@ -0,0 +1,468 @@
const express = require('express');
const Development_alternativesService = require('../services/development_alternatives');
const Development_alternativesDBApi = require('../db/api/development_alternatives');
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('development_alternatives'));
/**
* @swagger
* components:
* schemas:
* Development_alternatives:
* type: object
* properties:
* roads_public_area_pct:
* type: integer
* format: int64
* lot_sale_price_m2:
* type: integer
* format: int64
* infrastructure_cost_m2:
* type: integer
* format: int64
* projects_licenses_cost:
* type: integer
* format: int64
* total_term_years:
* type: integer
* format: int64
* fractionated_premium_pct:
* type: integer
* format: int64
* fractionated_absorption_years:
* type: integer
* format: int64
* subdivision_cost:
* type: integer
* format: int64
* computed_vpl_development:
* type: integer
* format: int64
* computed_vpl_fractionated:
* type: integer
* format: int64
*
*/
/**
* @swagger
* tags:
* name: Development_alternatives
* description: The Development_alternatives managing API
*/
/**
* @swagger
* /api/development_alternatives:
* post:
* security:
* - bearerAuth: []
* tags: [Development_alternatives]
* 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/Development_alternatives"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Development_alternatives"
* 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 Development_alternativesService.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: [Development_alternatives]
* 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/Development_alternatives"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Development_alternatives"
* 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 Development_alternativesService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/development_alternatives/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Development_alternatives]
* 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/Development_alternatives"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Development_alternatives"
* 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 Development_alternativesService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/development_alternatives/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Development_alternatives]
* 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/Development_alternatives"
* 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 Development_alternativesService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/development_alternatives/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Development_alternatives]
* 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/Development_alternatives"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await Development_alternativesService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/development_alternatives:
* get:
* security:
* - bearerAuth: []
* tags: [Development_alternatives]
* summary: Get all development_alternatives
* description: Get all development_alternatives
* responses:
* 200:
* description: Development_alternatives list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Development_alternatives"
* 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 Development_alternativesDBApi.findAll(
req.query, globalAccess, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id',
'roads_public_area_pct','lot_sale_price_m2','infrastructure_cost_m2','projects_licenses_cost','total_term_years','fractionated_premium_pct','fractionated_absorption_years','subdivision_cost','computed_vpl_development','computed_vpl_fractionated',
];
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/development_alternatives/count:
* get:
* security:
* - bearerAuth: []
* tags: [Development_alternatives]
* summary: Count all development_alternatives
* description: Count all development_alternatives
* responses:
* 200:
* description: Development_alternatives count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Development_alternatives"
* 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 Development_alternativesDBApi.findAll(
req.query,
globalAccess,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/development_alternatives/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Development_alternatives]
* summary: Find all development_alternatives that match search criteria
* description: Find all development_alternatives that match search criteria
* responses:
* 200:
* description: Development_alternatives list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Development_alternatives"
* 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 Development_alternativesDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
globalAccess, organizationId,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/development_alternatives/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Development_alternatives]
* 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/Development_alternatives"
* 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 Development_alternativesDBApi.findBy(
{ id: req.params.id },
);
res.status(200).send(payload);
}));
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,473 @@
const express = require('express');
const Market_assessmentsService = require('../services/market_assessments');
const Market_assessmentsDBApi = require('../db/api/market_assessments');
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('market_assessments'));
/**
* @swagger
* components:
* schemas:
* Market_assessments:
* type: object
* properties:
* forced_liquidation_months:
* type: integer
* format: int64
* unit_price_min:
* type: integer
* format: int64
* unit_price_avg:
* type: integer
* format: int64
* unit_price_max:
* type: integer
* format: int64
* total_value_min:
* type: integer
* format: int64
* total_value_avg:
* type: integer
* format: int64
* total_value_max:
* type: integer
* format: int64
* tma_pct:
* type: integer
* format: int64
* declared_liquidation_factor:
* type: integer
* format: int64
* theoretical_liquidation_factor:
* type: integer
* format: int64
* transaction_costs_pct:
* type: integer
* format: int64
*
*
*
*/
/**
* @swagger
* tags:
* name: Market_assessments
* description: The Market_assessments managing API
*/
/**
* @swagger
* /api/market_assessments:
* post:
* security:
* - bearerAuth: []
* tags: [Market_assessments]
* 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/Market_assessments"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Market_assessments"
* 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 Market_assessmentsService.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: [Market_assessments]
* 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/Market_assessments"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Market_assessments"
* 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 Market_assessmentsService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/market_assessments/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Market_assessments]
* 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/Market_assessments"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Market_assessments"
* 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 Market_assessmentsService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/market_assessments/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Market_assessments]
* 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/Market_assessments"
* 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 Market_assessmentsService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/market_assessments/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Market_assessments]
* 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/Market_assessments"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await Market_assessmentsService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/market_assessments:
* get:
* security:
* - bearerAuth: []
* tags: [Market_assessments]
* summary: Get all market_assessments
* description: Get all market_assessments
* responses:
* 200:
* description: Market_assessments list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Market_assessments"
* 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 Market_assessmentsDBApi.findAll(
req.query, globalAccess, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id',
'forced_liquidation_months',
'unit_price_min','unit_price_avg','unit_price_max','total_value_min','total_value_avg','total_value_max','tma_pct','declared_liquidation_factor','theoretical_liquidation_factor','transaction_costs_pct',
];
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/market_assessments/count:
* get:
* security:
* - bearerAuth: []
* tags: [Market_assessments]
* summary: Count all market_assessments
* description: Count all market_assessments
* responses:
* 200:
* description: Market_assessments count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Market_assessments"
* 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 Market_assessmentsDBApi.findAll(
req.query,
globalAccess,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/market_assessments/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Market_assessments]
* summary: Find all market_assessments that match search criteria
* description: Find all market_assessments that match search criteria
* responses:
* 200:
* description: Market_assessments list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Market_assessments"
* 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 Market_assessmentsDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
globalAccess, organizationId,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/market_assessments/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Market_assessments]
* 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/Market_assessments"
* 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 Market_assessmentsDBApi.findBy(
{ id: req.params.id },
);
res.status(200).send(payload);
}));
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

View File

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

View File

@ -0,0 +1,55 @@
const express = require('express');
const OrganizationsDBApi = require('../db/api/organizations');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
/**
* @swagger
* /api/organizations:
* get:
* security:
* - bearerAuth: []
* tags: [Organizations]
* summary: Get all organizations
* description: Get all organizations
* responses:
* 200:
* description: Organizations list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Organizations"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get(
'/',
wrapAsync(async (req, res) => {
const payload = await OrganizationsDBApi.findAll(req.query);
const simplifiedPayload = payload.rows.map(org => ({
id: org.id,
name: org.name
}));
res.status(200).send(simplifiedPayload);
}),
);
module.exports = router;

View File

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

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