Initial version

This commit is contained in:
Flatlogic Bot 2026-04-03 04:54:27 +00:00
commit 67559d5582
661 changed files with 249978 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>Gracey Corporate Stay Portal</h2>
<p>Multi-tenant portal for corporate apartment bookings, approvals, concierge services, and invoicing.</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 @@
# Gracey Corporate Stay Portal
## 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_39443
DB_USER=app_39443
DB_PASS=946cafba-a21f-40cd-bb6a-bc40952c93f4
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 @@
#Gracey Corporate Stay Portal - 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_gracey_corporate_stay_portal;`
- Then give that new user privileges to the new database then quit the `psql`.
- `postgres=> GRANT ALL PRIVILEGES ON DATABASE db_gracey_corporate_stay_portal 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": "graceycorporatestayportal",
"description": "Gracey Corporate Stay Portal - 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: "946cafba",
user_pass: "bc40952c93f4",
admin_email: "admin@flatlogic.com",
providers: {
LOCAL: 'local',
GOOGLE: 'google',
MICROSOFT: 'microsoft'
},
secret_key: process.env.SECRET_KEY || '946cafba-a21f-40cd-bb6a-bc40952c93f4',
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: 'Gracey Corporate Stay Portal <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: 'Concierge Coordinator',
},
project_uuid: '946cafba-a21f-40cd-bb6a-bc40952c93f4',
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 = 'Minimalist city skyline at dusk';
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,688 @@
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 Activity_commentsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const activity_comments = await db.activity_comments.create(
{
id: data.id || undefined,
visibility: data.visibility
||
null
,
body: data.body
||
null
,
posted_at: data.posted_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await activity_comments.setTenant( data.tenant || null, {
transaction,
});
await activity_comments.setOrganization(currentUser.organization.id || null, {
transaction,
});
await activity_comments.setAuthor( data.author || null, {
transaction,
});
await activity_comments.setBooking_request( data.booking_request || null, {
transaction,
});
await activity_comments.setReservation( data.reservation || null, {
transaction,
});
await activity_comments.setService_request( data.service_request || null, {
transaction,
});
await activity_comments.setInvoice( data.invoice || null, {
transaction,
});
return activity_comments;
}
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 activity_commentsData = data.map((item, index) => ({
id: item.id || undefined,
visibility: item.visibility
||
null
,
body: item.body
||
null
,
posted_at: item.posted_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const activity_comments = await db.activity_comments.bulkCreate(activity_commentsData, { transaction });
// For each item created, replace relation files
return activity_comments;
}
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 activity_comments = await db.activity_comments.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.visibility !== undefined) updatePayload.visibility = data.visibility;
if (data.body !== undefined) updatePayload.body = data.body;
if (data.posted_at !== undefined) updatePayload.posted_at = data.posted_at;
updatePayload.updatedById = currentUser.id;
await activity_comments.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await activity_comments.setTenant(
data.tenant,
{ transaction }
);
}
if (data.organization !== undefined) {
await activity_comments.setOrganization(
(globalAccess ? data.organization : currentUser.organization.id),
{ transaction }
);
}
if (data.author !== undefined) {
await activity_comments.setAuthor(
data.author,
{ transaction }
);
}
if (data.booking_request !== undefined) {
await activity_comments.setBooking_request(
data.booking_request,
{ transaction }
);
}
if (data.reservation !== undefined) {
await activity_comments.setReservation(
data.reservation,
{ transaction }
);
}
if (data.service_request !== undefined) {
await activity_comments.setService_request(
data.service_request,
{ transaction }
);
}
if (data.invoice !== undefined) {
await activity_comments.setInvoice(
data.invoice,
{ transaction }
);
}
return activity_comments;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const activity_comments = await db.activity_comments.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of activity_comments) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of activity_comments) {
await record.destroy({transaction});
}
});
return activity_comments;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const activity_comments = await db.activity_comments.findByPk(id, options);
await activity_comments.update({
deletedBy: currentUser.id
}, {
transaction,
});
await activity_comments.destroy({
transaction
});
return activity_comments;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const activity_comments = await db.activity_comments.findOne(
{ where },
{ transaction },
);
if (!activity_comments) {
return activity_comments;
}
const output = activity_comments.get({plain: true});
output.tenant = await activity_comments.getTenant({
transaction
});
output.organization = await activity_comments.getOrganization({
transaction
});
output.author = await activity_comments.getAuthor({
transaction
});
output.booking_request = await activity_comments.getBooking_request({
transaction
});
output.reservation = await activity_comments.getReservation({
transaction
});
output.service_request = await activity_comments.getService_request({
transaction
});
output.invoice = await activity_comments.getInvoice({
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.tenants,
as: 'tenant',
where: filter.tenant ? {
[Op.or]: [
{ id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organization',
},
{
model: db.users,
as: 'author',
where: filter.author ? {
[Op.or]: [
{ id: { [Op.in]: filter.author.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.author.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.booking_requests,
as: 'booking_request',
where: filter.booking_request ? {
[Op.or]: [
{ id: { [Op.in]: filter.booking_request.split('|').map(term => Utils.uuid(term)) } },
{
request_code: {
[Op.or]: filter.booking_request.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.reservations,
as: 'reservation',
where: filter.reservation ? {
[Op.or]: [
{ id: { [Op.in]: filter.reservation.split('|').map(term => Utils.uuid(term)) } },
{
reservation_code: {
[Op.or]: filter.reservation.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.service_requests,
as: 'service_request',
where: filter.service_request ? {
[Op.or]: [
{ id: { [Op.in]: filter.service_request.split('|').map(term => Utils.uuid(term)) } },
{
summary: {
[Op.or]: filter.service_request.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.invoices,
as: 'invoice',
where: filter.invoice ? {
[Op.or]: [
{ id: { [Op.in]: filter.invoice.split('|').map(term => Utils.uuid(term)) } },
{
invoice_number: {
[Op.or]: filter.invoice.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.body) {
where = {
...where,
[Op.and]: Utils.ilike(
'activity_comments',
'body',
filter.body,
),
};
}
if (filter.posted_atRange) {
const [start, end] = filter.posted_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
posted_at: {
...where.posted_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
posted_at: {
...where.posted_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.visibility) {
where = {
...where,
visibility: filter.visibility,
};
}
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.activity_comments.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(
'activity_comments',
'body',
query,
),
],
};
}
const records = await db.activity_comments.findAll({
attributes: [ 'id', 'body' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['body', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.body,
}));
}
};

View File

@ -0,0 +1,470 @@
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 AmenitiesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const amenities = await db.amenities.create(
{
id: data.id || undefined,
name: data.name
||
null
,
description: data.description
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await amenities.setProperty( data.property || null, {
transaction,
});
await amenities.setOrganizations( data.organizations || null, {
transaction,
});
return amenities;
}
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 amenitiesData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
description: item.description
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const amenities = await db.amenities.bulkCreate(amenitiesData, { transaction });
// For each item created, replace relation files
return amenities;
}
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 amenities = await db.amenities.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.description !== undefined) updatePayload.description = data.description;
updatePayload.updatedById = currentUser.id;
await amenities.update(updatePayload, {transaction});
if (data.property !== undefined) {
await amenities.setProperty(
data.property,
{ transaction }
);
}
if (data.organizations !== undefined) {
await amenities.setOrganizations(
data.organizations,
{ transaction }
);
}
return amenities;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const amenities = await db.amenities.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of amenities) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of amenities) {
await record.destroy({transaction});
}
});
return amenities;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const amenities = await db.amenities.findByPk(id, options);
await amenities.update({
deletedBy: currentUser.id
}, {
transaction,
});
await amenities.destroy({
transaction
});
return amenities;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const amenities = await db.amenities.findOne(
{ where },
{ transaction },
);
if (!amenities) {
return amenities;
}
const output = amenities.get({plain: true});
output.property = await amenities.getProperty({
transaction
});
output.organizations = await amenities.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.properties,
as: 'property',
where: filter.property ? {
[Op.or]: [
{ id: { [Op.in]: filter.property.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.property.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) {
where = {
...where,
[Op.and]: Utils.ilike(
'amenities',
'name',
filter.name,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'amenities',
'description',
filter.description,
),
};
}
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.amenities.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(
'amenities',
'name',
query,
),
],
};
}
const records = await db.amenities.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,577 @@
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 Approval_stepsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const approval_steps = await db.approval_steps.create(
{
id: data.id || undefined,
step_order: data.step_order
||
null
,
decision: data.decision
||
null
,
decided_at: data.decided_at
||
null
,
decision_notes: data.decision_notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await approval_steps.setBooking_request( data.booking_request || null, {
transaction,
});
await approval_steps.setApprover( data.approver || null, {
transaction,
});
await approval_steps.setOrganizations( data.organizations || null, {
transaction,
});
return approval_steps;
}
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 approval_stepsData = data.map((item, index) => ({
id: item.id || undefined,
step_order: item.step_order
||
null
,
decision: item.decision
||
null
,
decided_at: item.decided_at
||
null
,
decision_notes: item.decision_notes
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const approval_steps = await db.approval_steps.bulkCreate(approval_stepsData, { transaction });
// For each item created, replace relation files
return approval_steps;
}
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 approval_steps = await db.approval_steps.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.step_order !== undefined) updatePayload.step_order = data.step_order;
if (data.decision !== undefined) updatePayload.decision = data.decision;
if (data.decided_at !== undefined) updatePayload.decided_at = data.decided_at;
if (data.decision_notes !== undefined) updatePayload.decision_notes = data.decision_notes;
updatePayload.updatedById = currentUser.id;
await approval_steps.update(updatePayload, {transaction});
if (data.booking_request !== undefined) {
await approval_steps.setBooking_request(
data.booking_request,
{ transaction }
);
}
if (data.approver !== undefined) {
await approval_steps.setApprover(
data.approver,
{ transaction }
);
}
if (data.organizations !== undefined) {
await approval_steps.setOrganizations(
data.organizations,
{ transaction }
);
}
return approval_steps;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const approval_steps = await db.approval_steps.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of approval_steps) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of approval_steps) {
await record.destroy({transaction});
}
});
return approval_steps;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const approval_steps = await db.approval_steps.findByPk(id, options);
await approval_steps.update({
deletedBy: currentUser.id
}, {
transaction,
});
await approval_steps.destroy({
transaction
});
return approval_steps;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const approval_steps = await db.approval_steps.findOne(
{ where },
{ transaction },
);
if (!approval_steps) {
return approval_steps;
}
const output = approval_steps.get({plain: true});
output.booking_request = await approval_steps.getBooking_request({
transaction
});
output.approver = await approval_steps.getApprover({
transaction
});
output.organizations = await approval_steps.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.booking_requests,
as: 'booking_request',
where: filter.booking_request ? {
[Op.or]: [
{ id: { [Op.in]: filter.booking_request.split('|').map(term => Utils.uuid(term)) } },
{
request_code: {
[Op.or]: filter.booking_request.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'approver',
where: filter.approver ? {
[Op.or]: [
{ id: { [Op.in]: filter.approver.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.approver.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.decision_notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'approval_steps',
'decision_notes',
filter.decision_notes,
),
};
}
if (filter.step_orderRange) {
const [start, end] = filter.step_orderRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
step_order: {
...where.step_order,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
step_order: {
...where.step_order,
[Op.lte]: end,
},
};
}
}
if (filter.decided_atRange) {
const [start, end] = filter.decided_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
decided_at: {
...where.decided_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
decided_at: {
...where.decided_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.decision) {
where = {
...where,
decision: filter.decision,
};
}
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.approval_steps.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(
'approval_steps',
'decision_notes',
query,
),
],
};
}
const records = await db.approval_steps.findAll({
attributes: [ 'id', 'decision_notes' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['decision_notes', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.decision_notes,
}));
}
};

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 Audit_logsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const audit_logs = await db.audit_logs.create(
{
id: data.id || undefined,
action: data.action
||
null
,
entity_name: data.entity_name
||
null
,
entity_reference: data.entity_reference
||
null
,
ip_address: data.ip_address
||
null
,
user_agent: data.user_agent
||
null
,
occurred_at: data.occurred_at
||
null
,
metadata_json: data.metadata_json
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await audit_logs.setTenant( data.tenant || null, {
transaction,
});
await audit_logs.setActor( data.actor || null, {
transaction,
});
await audit_logs.setOrganizations( data.organizations || null, {
transaction,
});
return audit_logs;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const audit_logsData = data.map((item, index) => ({
id: item.id || undefined,
action: item.action
||
null
,
entity_name: item.entity_name
||
null
,
entity_reference: item.entity_reference
||
null
,
ip_address: item.ip_address
||
null
,
user_agent: item.user_agent
||
null
,
occurred_at: item.occurred_at
||
null
,
metadata_json: item.metadata_json
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const audit_logs = await db.audit_logs.bulkCreate(audit_logsData, { transaction });
// For each item created, replace relation files
return audit_logs;
}
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 audit_logs = await db.audit_logs.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.action !== undefined) updatePayload.action = data.action;
if (data.entity_name !== undefined) updatePayload.entity_name = data.entity_name;
if (data.entity_reference !== undefined) updatePayload.entity_reference = data.entity_reference;
if (data.ip_address !== undefined) updatePayload.ip_address = data.ip_address;
if (data.user_agent !== undefined) updatePayload.user_agent = data.user_agent;
if (data.occurred_at !== undefined) updatePayload.occurred_at = data.occurred_at;
if (data.metadata_json !== undefined) updatePayload.metadata_json = data.metadata_json;
updatePayload.updatedById = currentUser.id;
await audit_logs.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await audit_logs.setTenant(
data.tenant,
{ transaction }
);
}
if (data.actor !== undefined) {
await audit_logs.setActor(
data.actor,
{ transaction }
);
}
if (data.organizations !== undefined) {
await audit_logs.setOrganizations(
data.organizations,
{ transaction }
);
}
return audit_logs;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const audit_logs = await db.audit_logs.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of audit_logs) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of audit_logs) {
await record.destroy({transaction});
}
});
return audit_logs;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const audit_logs = await db.audit_logs.findByPk(id, options);
await audit_logs.update({
deletedBy: currentUser.id
}, {
transaction,
});
await audit_logs.destroy({
transaction
});
return audit_logs;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const audit_logs = await db.audit_logs.findOne(
{ where },
{ transaction },
);
if (!audit_logs) {
return audit_logs;
}
const output = audit_logs.get({plain: true});
output.tenant = await audit_logs.getTenant({
transaction
});
output.actor = await audit_logs.getActor({
transaction
});
output.organizations = await audit_logs.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.tenants,
as: 'tenant',
where: filter.tenant ? {
[Op.or]: [
{ id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'actor',
where: filter.actor ? {
[Op.or]: [
{ id: { [Op.in]: filter.actor.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.actor.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.action) {
where = {
...where,
[Op.and]: Utils.ilike(
'audit_logs',
'action',
filter.action,
),
};
}
if (filter.entity_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'audit_logs',
'entity_name',
filter.entity_name,
),
};
}
if (filter.entity_reference) {
where = {
...where,
[Op.and]: Utils.ilike(
'audit_logs',
'entity_reference',
filter.entity_reference,
),
};
}
if (filter.ip_address) {
where = {
...where,
[Op.and]: Utils.ilike(
'audit_logs',
'ip_address',
filter.ip_address,
),
};
}
if (filter.user_agent) {
where = {
...where,
[Op.and]: Utils.ilike(
'audit_logs',
'user_agent',
filter.user_agent,
),
};
}
if (filter.metadata_json) {
where = {
...where,
[Op.and]: Utils.ilike(
'audit_logs',
'metadata_json',
filter.metadata_json,
),
};
}
if (filter.occurred_atRange) {
const [start, end] = filter.occurred_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
occurred_at: {
...where.occurred_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
occurred_at: {
...where.occurred_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.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.audit_logs.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(
'audit_logs',
'action',
query,
),
],
};
}
const records = await db.audit_logs.findAll({
attributes: [ 'id', 'action' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['action', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.action,
}));
}
};

View File

@ -0,0 +1,625 @@
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 Booking_request_travelersDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const booking_request_travelers = await db.booking_request_travelers.create(
{
id: data.id || undefined,
full_name: data.full_name
||
null
,
email: data.email
||
null
,
phone: data.phone
||
null
,
nationality: data.nationality
||
null
,
passport_number: data.passport_number
||
null
,
date_of_birth: data.date_of_birth
||
null
,
primary_traveler: data.primary_traveler
||
false
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await booking_request_travelers.setBooking_request( data.booking_request || null, {
transaction,
});
await booking_request_travelers.setOrganizations( data.organizations || null, {
transaction,
});
return booking_request_travelers;
}
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 booking_request_travelersData = data.map((item, index) => ({
id: item.id || undefined,
full_name: item.full_name
||
null
,
email: item.email
||
null
,
phone: item.phone
||
null
,
nationality: item.nationality
||
null
,
passport_number: item.passport_number
||
null
,
date_of_birth: item.date_of_birth
||
null
,
primary_traveler: item.primary_traveler
||
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 booking_request_travelers = await db.booking_request_travelers.bulkCreate(booking_request_travelersData, { transaction });
// For each item created, replace relation files
return booking_request_travelers;
}
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 booking_request_travelers = await db.booking_request_travelers.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.full_name !== undefined) updatePayload.full_name = data.full_name;
if (data.email !== undefined) updatePayload.email = data.email;
if (data.phone !== undefined) updatePayload.phone = data.phone;
if (data.nationality !== undefined) updatePayload.nationality = data.nationality;
if (data.passport_number !== undefined) updatePayload.passport_number = data.passport_number;
if (data.date_of_birth !== undefined) updatePayload.date_of_birth = data.date_of_birth;
if (data.primary_traveler !== undefined) updatePayload.primary_traveler = data.primary_traveler;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await booking_request_travelers.update(updatePayload, {transaction});
if (data.booking_request !== undefined) {
await booking_request_travelers.setBooking_request(
data.booking_request,
{ transaction }
);
}
if (data.organizations !== undefined) {
await booking_request_travelers.setOrganizations(
data.organizations,
{ transaction }
);
}
return booking_request_travelers;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const booking_request_travelers = await db.booking_request_travelers.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of booking_request_travelers) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of booking_request_travelers) {
await record.destroy({transaction});
}
});
return booking_request_travelers;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const booking_request_travelers = await db.booking_request_travelers.findByPk(id, options);
await booking_request_travelers.update({
deletedBy: currentUser.id
}, {
transaction,
});
await booking_request_travelers.destroy({
transaction
});
return booking_request_travelers;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const booking_request_travelers = await db.booking_request_travelers.findOne(
{ where },
{ transaction },
);
if (!booking_request_travelers) {
return booking_request_travelers;
}
const output = booking_request_travelers.get({plain: true});
output.booking_request = await booking_request_travelers.getBooking_request({
transaction
});
output.organizations = await booking_request_travelers.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.booking_requests,
as: 'booking_request',
where: filter.booking_request ? {
[Op.or]: [
{ id: { [Op.in]: filter.booking_request.split('|').map(term => Utils.uuid(term)) } },
{
request_code: {
[Op.or]: filter.booking_request.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.full_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'booking_request_travelers',
'full_name',
filter.full_name,
),
};
}
if (filter.email) {
where = {
...where,
[Op.and]: Utils.ilike(
'booking_request_travelers',
'email',
filter.email,
),
};
}
if (filter.phone) {
where = {
...where,
[Op.and]: Utils.ilike(
'booking_request_travelers',
'phone',
filter.phone,
),
};
}
if (filter.nationality) {
where = {
...where,
[Op.and]: Utils.ilike(
'booking_request_travelers',
'nationality',
filter.nationality,
),
};
}
if (filter.passport_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'booking_request_travelers',
'passport_number',
filter.passport_number,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'booking_request_travelers',
'notes',
filter.notes,
),
};
}
if (filter.date_of_birthRange) {
const [start, end] = filter.date_of_birthRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
date_of_birth: {
...where.date_of_birth,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
date_of_birth: {
...where.date_of_birth,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.primary_traveler) {
where = {
...where,
primary_traveler: filter.primary_traveler,
};
}
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.booking_request_travelers.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(
'booking_request_travelers',
'full_name',
query,
),
],
};
}
const records = await db.booking_request_travelers.findAll({
attributes: [ 'id', 'full_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['full_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.full_name,
}));
}
};

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,603 @@
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 Checklist_itemsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const checklist_items = await db.checklist_items.create(
{
id: data.id || undefined,
title: data.title
||
null
,
is_done: data.is_done
||
false
,
done_at: data.done_at
||
null
,
sort_order: data.sort_order
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await checklist_items.setChecklist( data.checklist || null, {
transaction,
});
await checklist_items.setDone_by( data.done_by || null, {
transaction,
});
await checklist_items.setOrganizations( data.organizations || null, {
transaction,
});
return checklist_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 checklist_itemsData = data.map((item, index) => ({
id: item.id || undefined,
title: item.title
||
null
,
is_done: item.is_done
||
false
,
done_at: item.done_at
||
null
,
sort_order: item.sort_order
||
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 checklist_items = await db.checklist_items.bulkCreate(checklist_itemsData, { transaction });
// For each item created, replace relation files
return checklist_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 checklist_items = await db.checklist_items.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.title !== undefined) updatePayload.title = data.title;
if (data.is_done !== undefined) updatePayload.is_done = data.is_done;
if (data.done_at !== undefined) updatePayload.done_at = data.done_at;
if (data.sort_order !== undefined) updatePayload.sort_order = data.sort_order;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await checklist_items.update(updatePayload, {transaction});
if (data.checklist !== undefined) {
await checklist_items.setChecklist(
data.checklist,
{ transaction }
);
}
if (data.done_by !== undefined) {
await checklist_items.setDone_by(
data.done_by,
{ transaction }
);
}
if (data.organizations !== undefined) {
await checklist_items.setOrganizations(
data.organizations,
{ transaction }
);
}
return checklist_items;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const checklist_items = await db.checklist_items.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of checklist_items) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of checklist_items) {
await record.destroy({transaction});
}
});
return checklist_items;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const checklist_items = await db.checklist_items.findByPk(id, options);
await checklist_items.update({
deletedBy: currentUser.id
}, {
transaction,
});
await checklist_items.destroy({
transaction
});
return checklist_items;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const checklist_items = await db.checklist_items.findOne(
{ where },
{ transaction },
);
if (!checklist_items) {
return checklist_items;
}
const output = checklist_items.get({plain: true});
output.checklist = await checklist_items.getChecklist({
transaction
});
output.done_by = await checklist_items.getDone_by({
transaction
});
output.organizations = await checklist_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.checklists,
as: 'checklist',
where: filter.checklist ? {
[Op.or]: [
{ id: { [Op.in]: filter.checklist.split('|').map(term => Utils.uuid(term)) } },
{
notes: {
[Op.or]: filter.checklist.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'done_by',
where: filter.done_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.done_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.done_by.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.title) {
where = {
...where,
[Op.and]: Utils.ilike(
'checklist_items',
'title',
filter.title,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'checklist_items',
'notes',
filter.notes,
),
};
}
if (filter.done_atRange) {
const [start, end] = filter.done_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
done_at: {
...where.done_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
done_at: {
...where.done_at,
[Op.lte]: end,
},
};
}
}
if (filter.sort_orderRange) {
const [start, end] = filter.sort_orderRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sort_order: {
...where.sort_order,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sort_order: {
...where.sort_order,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.is_done) {
where = {
...where,
is_done: filter.is_done,
};
}
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.checklist_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(
'checklist_items',
'title',
query,
),
],
};
}
const records = await db.checklist_items.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,680 @@
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 ChecklistsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const checklists = await db.checklists.create(
{
id: data.id || undefined,
checklist_type: data.checklist_type
||
null
,
status: data.status
||
null
,
due_at: data.due_at
||
null
,
completed_at: data.completed_at
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await checklists.setTenant( data.tenant || null, {
transaction,
});
await checklists.setReservation( data.reservation || null, {
transaction,
});
await checklists.setAssigned_to( data.assigned_to || null, {
transaction,
});
await checklists.setOrganizations( data.organizations || null, {
transaction,
});
await checklists.setItems(data.items || [], {
transaction,
});
return checklists;
}
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 checklistsData = data.map((item, index) => ({
id: item.id || undefined,
checklist_type: item.checklist_type
||
null
,
status: item.status
||
null
,
due_at: item.due_at
||
null
,
completed_at: item.completed_at
||
null
,
notes: item.notes
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const checklists = await db.checklists.bulkCreate(checklistsData, { transaction });
// For each item created, replace relation files
return checklists;
}
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 checklists = await db.checklists.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.checklist_type !== undefined) updatePayload.checklist_type = data.checklist_type;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.due_at !== undefined) updatePayload.due_at = data.due_at;
if (data.completed_at !== undefined) updatePayload.completed_at = data.completed_at;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await checklists.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await checklists.setTenant(
data.tenant,
{ transaction }
);
}
if (data.reservation !== undefined) {
await checklists.setReservation(
data.reservation,
{ transaction }
);
}
if (data.assigned_to !== undefined) {
await checklists.setAssigned_to(
data.assigned_to,
{ transaction }
);
}
if (data.organizations !== undefined) {
await checklists.setOrganizations(
data.organizations,
{ transaction }
);
}
if (data.items !== undefined) {
await checklists.setItems(data.items, { transaction });
}
return checklists;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const checklists = await db.checklists.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of checklists) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of checklists) {
await record.destroy({transaction});
}
});
return checklists;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const checklists = await db.checklists.findByPk(id, options);
await checklists.update({
deletedBy: currentUser.id
}, {
transaction,
});
await checklists.destroy({
transaction
});
return checklists;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const checklists = await db.checklists.findOne(
{ where },
{ transaction },
);
if (!checklists) {
return checklists;
}
const output = checklists.get({plain: true});
output.checklist_items_checklist = await checklists.getChecklist_items_checklist({
transaction
});
output.tenant = await checklists.getTenant({
transaction
});
output.reservation = await checklists.getReservation({
transaction
});
output.assigned_to = await checklists.getAssigned_to({
transaction
});
output.items = await checklists.getItems({
transaction
});
output.organizations = await checklists.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.tenants,
as: 'tenant',
where: filter.tenant ? {
[Op.or]: [
{ id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.reservations,
as: 'reservation',
where: filter.reservation ? {
[Op.or]: [
{ id: { [Op.in]: filter.reservation.split('|').map(term => Utils.uuid(term)) } },
{
reservation_code: {
[Op.or]: filter.reservation.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'assigned_to',
where: filter.assigned_to ? {
[Op.or]: [
{ id: { [Op.in]: filter.assigned_to.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.assigned_to.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.checklist_items,
as: 'items',
required: false,
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'checklists',
'notes',
filter.notes,
),
};
}
if (filter.due_atRange) {
const [start, end] = filter.due_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
due_at: {
...where.due_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
due_at: {
...where.due_at,
[Op.lte]: end,
},
};
}
}
if (filter.completed_atRange) {
const [start, end] = filter.completed_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
completed_at: {
...where.completed_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
completed_at: {
...where.completed_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.checklist_type) {
where = {
...where,
checklist_type: filter.checklist_type,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.items) {
const searchTerms = filter.items.split('|');
include = [
{
model: db.checklist_items,
as: 'items_filter',
required: searchTerms.length > 0,
where: searchTerms.length > 0 ? {
[Op.or]: [
{ id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
{
title: {
[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) {
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.checklists.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(
'checklists',
'notes',
query,
),
],
};
}
const records = await db.checklists.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,806 @@
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 DocumentsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const documents = await db.documents.create(
{
id: data.id || undefined,
document_type: data.document_type
||
null
,
file_name: data.file_name
||
null
,
mime_type: data.mime_type
||
null
,
file_size_bytes: data.file_size_bytes
||
null
,
storage_key: data.storage_key
||
null
,
public_url: data.public_url
||
null
,
notes: data.notes
||
null
,
is_private: data.is_private
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await documents.setTenant( data.tenant || null, {
transaction,
});
await documents.setUploaded_by( data.uploaded_by || null, {
transaction,
});
await documents.setOrganization(currentUser.organization.id || null, {
transaction,
});
await documents.setBooking_request( data.booking_request || null, {
transaction,
});
await documents.setReservation( data.reservation || null, {
transaction,
});
await documents.setService_request( data.service_request || null, {
transaction,
});
await documents.setInvoice( data.invoice || null, {
transaction,
});
return documents;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const documentsData = data.map((item, index) => ({
id: item.id || undefined,
document_type: item.document_type
||
null
,
file_name: item.file_name
||
null
,
mime_type: item.mime_type
||
null
,
file_size_bytes: item.file_size_bytes
||
null
,
storage_key: item.storage_key
||
null
,
public_url: item.public_url
||
null
,
notes: item.notes
||
null
,
is_private: item.is_private
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const documents = await db.documents.bulkCreate(documentsData, { transaction });
// For each item created, replace relation files
return documents;
}
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 documents = await db.documents.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.document_type !== undefined) updatePayload.document_type = data.document_type;
if (data.file_name !== undefined) updatePayload.file_name = data.file_name;
if (data.mime_type !== undefined) updatePayload.mime_type = data.mime_type;
if (data.file_size_bytes !== undefined) updatePayload.file_size_bytes = data.file_size_bytes;
if (data.storage_key !== undefined) updatePayload.storage_key = data.storage_key;
if (data.public_url !== undefined) updatePayload.public_url = data.public_url;
if (data.notes !== undefined) updatePayload.notes = data.notes;
if (data.is_private !== undefined) updatePayload.is_private = data.is_private;
updatePayload.updatedById = currentUser.id;
await documents.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await documents.setTenant(
data.tenant,
{ transaction }
);
}
if (data.uploaded_by !== undefined) {
await documents.setUploaded_by(
data.uploaded_by,
{ transaction }
);
}
if (data.organization !== undefined) {
await documents.setOrganization(
(globalAccess ? data.organization : currentUser.organization.id),
{ transaction }
);
}
if (data.booking_request !== undefined) {
await documents.setBooking_request(
data.booking_request,
{ transaction }
);
}
if (data.reservation !== undefined) {
await documents.setReservation(
data.reservation,
{ transaction }
);
}
if (data.service_request !== undefined) {
await documents.setService_request(
data.service_request,
{ transaction }
);
}
if (data.invoice !== undefined) {
await documents.setInvoice(
data.invoice,
{ transaction }
);
}
return documents;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const documents = await db.documents.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of documents) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of documents) {
await record.destroy({transaction});
}
});
return documents;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const documents = await db.documents.findByPk(id, options);
await documents.update({
deletedBy: currentUser.id
}, {
transaction,
});
await documents.destroy({
transaction
});
return documents;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const documents = await db.documents.findOne(
{ where },
{ transaction },
);
if (!documents) {
return documents;
}
const output = documents.get({plain: true});
output.tenant = await documents.getTenant({
transaction
});
output.uploaded_by = await documents.getUploaded_by({
transaction
});
output.organization = await documents.getOrganization({
transaction
});
output.booking_request = await documents.getBooking_request({
transaction
});
output.reservation = await documents.getReservation({
transaction
});
output.service_request = await documents.getService_request({
transaction
});
output.invoice = await documents.getInvoice({
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.tenants,
as: 'tenant',
where: filter.tenant ? {
[Op.or]: [
{ id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'uploaded_by',
where: filter.uploaded_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.uploaded_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.uploaded_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organization',
},
{
model: db.booking_requests,
as: 'booking_request',
where: filter.booking_request ? {
[Op.or]: [
{ id: { [Op.in]: filter.booking_request.split('|').map(term => Utils.uuid(term)) } },
{
request_code: {
[Op.or]: filter.booking_request.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.reservations,
as: 'reservation',
where: filter.reservation ? {
[Op.or]: [
{ id: { [Op.in]: filter.reservation.split('|').map(term => Utils.uuid(term)) } },
{
reservation_code: {
[Op.or]: filter.reservation.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.service_requests,
as: 'service_request',
where: filter.service_request ? {
[Op.or]: [
{ id: { [Op.in]: filter.service_request.split('|').map(term => Utils.uuid(term)) } },
{
summary: {
[Op.or]: filter.service_request.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.invoices,
as: 'invoice',
where: filter.invoice ? {
[Op.or]: [
{ id: { [Op.in]: filter.invoice.split('|').map(term => Utils.uuid(term)) } },
{
invoice_number: {
[Op.or]: filter.invoice.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.file_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'documents',
'file_name',
filter.file_name,
),
};
}
if (filter.mime_type) {
where = {
...where,
[Op.and]: Utils.ilike(
'documents',
'mime_type',
filter.mime_type,
),
};
}
if (filter.storage_key) {
where = {
...where,
[Op.and]: Utils.ilike(
'documents',
'storage_key',
filter.storage_key,
),
};
}
if (filter.public_url) {
where = {
...where,
[Op.and]: Utils.ilike(
'documents',
'public_url',
filter.public_url,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'documents',
'notes',
filter.notes,
),
};
}
if (filter.file_size_bytesRange) {
const [start, end] = filter.file_size_bytesRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
file_size_bytes: {
...where.file_size_bytes,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
file_size_bytes: {
...where.file_size_bytes,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.document_type) {
where = {
...where,
document_type: filter.document_type,
};
}
if (filter.is_private) {
where = {
...where,
is_private: filter.is_private,
};
}
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.documents.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'documents',
'file_name',
query,
),
],
};
}
const records = await db.documents.findAll({
attributes: [ 'id', 'file_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['file_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.file_name,
}));
}
};

View File

@ -0,0 +1,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,601 @@
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 Invoice_line_itemsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const invoice_line_items = await db.invoice_line_items.create(
{
id: data.id || undefined,
line_type: data.line_type
||
null
,
description: data.description
||
null
,
quantity: data.quantity
||
null
,
unit_price: data.unit_price
||
null
,
amount: data.amount
||
null
,
service_period: data.service_period
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await invoice_line_items.setInvoice( data.invoice || null, {
transaction,
});
await invoice_line_items.setOrganizations( data.organizations || null, {
transaction,
});
return invoice_line_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 invoice_line_itemsData = data.map((item, index) => ({
id: item.id || undefined,
line_type: item.line_type
||
null
,
description: item.description
||
null
,
quantity: item.quantity
||
null
,
unit_price: item.unit_price
||
null
,
amount: item.amount
||
null
,
service_period: item.service_period
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const invoice_line_items = await db.invoice_line_items.bulkCreate(invoice_line_itemsData, { transaction });
// For each item created, replace relation files
return invoice_line_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 invoice_line_items = await db.invoice_line_items.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.line_type !== undefined) updatePayload.line_type = data.line_type;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.quantity !== undefined) updatePayload.quantity = data.quantity;
if (data.unit_price !== undefined) updatePayload.unit_price = data.unit_price;
if (data.amount !== undefined) updatePayload.amount = data.amount;
if (data.service_period !== undefined) updatePayload.service_period = data.service_period;
updatePayload.updatedById = currentUser.id;
await invoice_line_items.update(updatePayload, {transaction});
if (data.invoice !== undefined) {
await invoice_line_items.setInvoice(
data.invoice,
{ transaction }
);
}
if (data.organizations !== undefined) {
await invoice_line_items.setOrganizations(
data.organizations,
{ transaction }
);
}
return invoice_line_items;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const invoice_line_items = await db.invoice_line_items.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of invoice_line_items) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of invoice_line_items) {
await record.destroy({transaction});
}
});
return invoice_line_items;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const invoice_line_items = await db.invoice_line_items.findByPk(id, options);
await invoice_line_items.update({
deletedBy: currentUser.id
}, {
transaction,
});
await invoice_line_items.destroy({
transaction
});
return invoice_line_items;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const invoice_line_items = await db.invoice_line_items.findOne(
{ where },
{ transaction },
);
if (!invoice_line_items) {
return invoice_line_items;
}
const output = invoice_line_items.get({plain: true});
output.invoice = await invoice_line_items.getInvoice({
transaction
});
output.organizations = await invoice_line_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.invoices,
as: 'invoice',
where: filter.invoice ? {
[Op.or]: [
{ id: { [Op.in]: filter.invoice.split('|').map(term => Utils.uuid(term)) } },
{
invoice_number: {
[Op.or]: filter.invoice.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.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'invoice_line_items',
'description',
filter.description,
),
};
}
if (filter.service_period) {
where = {
...where,
[Op.and]: Utils.ilike(
'invoice_line_items',
'service_period',
filter.service_period,
),
};
}
if (filter.quantityRange) {
const [start, end] = filter.quantityRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
quantity: {
...where.quantity,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
quantity: {
...where.quantity,
[Op.lte]: end,
},
};
}
}
if (filter.unit_priceRange) {
const [start, end] = filter.unit_priceRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
unit_price: {
...where.unit_price,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
unit_price: {
...where.unit_price,
[Op.lte]: end,
},
};
}
}
if (filter.amountRange) {
const [start, end] = filter.amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
amount: {
...where.amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
amount: {
...where.amount,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.line_type) {
where = {
...where,
line_type: filter.line_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.invoice_line_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(
'invoice_line_items',
'description',
query,
),
],
};
}
const records = await db.invoice_line_items.findAll({
attributes: [ 'id', 'description' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['description', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.description,
}));
}
};

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,658 @@
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 Job_runsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const job_runs = await db.job_runs.create(
{
id: data.id || undefined,
job_type: data.job_type
||
null
,
status: data.status
||
null
,
scheduled_for: data.scheduled_for
||
null
,
started_at: data.started_at
||
null
,
finished_at: data.finished_at
||
null
,
attempt_count: data.attempt_count
||
null
,
last_error: data.last_error
||
null
,
payload_json: data.payload_json
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await job_runs.setTenant( data.tenant || null, {
transaction,
});
await job_runs.setOrganizations( data.organizations || null, {
transaction,
});
return job_runs;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const job_runsData = data.map((item, index) => ({
id: item.id || undefined,
job_type: item.job_type
||
null
,
status: item.status
||
null
,
scheduled_for: item.scheduled_for
||
null
,
started_at: item.started_at
||
null
,
finished_at: item.finished_at
||
null
,
attempt_count: item.attempt_count
||
null
,
last_error: item.last_error
||
null
,
payload_json: item.payload_json
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const job_runs = await db.job_runs.bulkCreate(job_runsData, { transaction });
// For each item created, replace relation files
return job_runs;
}
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 job_runs = await db.job_runs.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.job_type !== undefined) updatePayload.job_type = data.job_type;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.scheduled_for !== undefined) updatePayload.scheduled_for = data.scheduled_for;
if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
if (data.finished_at !== undefined) updatePayload.finished_at = data.finished_at;
if (data.attempt_count !== undefined) updatePayload.attempt_count = data.attempt_count;
if (data.last_error !== undefined) updatePayload.last_error = data.last_error;
if (data.payload_json !== undefined) updatePayload.payload_json = data.payload_json;
updatePayload.updatedById = currentUser.id;
await job_runs.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await job_runs.setTenant(
data.tenant,
{ transaction }
);
}
if (data.organizations !== undefined) {
await job_runs.setOrganizations(
data.organizations,
{ transaction }
);
}
return job_runs;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const job_runs = await db.job_runs.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of job_runs) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of job_runs) {
await record.destroy({transaction});
}
});
return job_runs;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const job_runs = await db.job_runs.findByPk(id, options);
await job_runs.update({
deletedBy: currentUser.id
}, {
transaction,
});
await job_runs.destroy({
transaction
});
return job_runs;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const job_runs = await db.job_runs.findOne(
{ where },
{ transaction },
);
if (!job_runs) {
return job_runs;
}
const output = job_runs.get({plain: true});
output.tenant = await job_runs.getTenant({
transaction
});
output.organizations = await job_runs.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.tenants,
as: 'tenant',
where: filter.tenant ? {
[Op.or]: [
{ id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.tenant.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.last_error) {
where = {
...where,
[Op.and]: Utils.ilike(
'job_runs',
'last_error',
filter.last_error,
),
};
}
if (filter.payload_json) {
where = {
...where,
[Op.and]: Utils.ilike(
'job_runs',
'payload_json',
filter.payload_json,
),
};
}
if (filter.scheduled_forRange) {
const [start, end] = filter.scheduled_forRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
scheduled_for: {
...where.scheduled_for,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
scheduled_for: {
...where.scheduled_for,
[Op.lte]: end,
},
};
}
}
if (filter.started_atRange) {
const [start, end] = filter.started_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
started_at: {
...where.started_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
started_at: {
...where.started_at,
[Op.lte]: end,
},
};
}
}
if (filter.finished_atRange) {
const [start, end] = filter.finished_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
finished_at: {
...where.finished_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
finished_at: {
...where.finished_at,
[Op.lte]: end,
},
};
}
}
if (filter.attempt_countRange) {
const [start, end] = filter.attempt_countRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
attempt_count: {
...where.attempt_count,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
attempt_count: {
...where.attempt_count,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.job_type) {
where = {
...where,
job_type: filter.job_type,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.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.job_runs.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'job_runs',
'job_type',
query,
),
],
};
}
const records = await db.job_runs.findAll({
attributes: [ 'id', 'job_type' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['job_type', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.job_type,
}));
}
};

View File

@ -0,0 +1,673 @@
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 Negotiated_ratesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const negotiated_rates = await db.negotiated_rates.create(
{
id: data.id || undefined,
rate_type: data.rate_type
||
null
,
rate_amount: data.rate_amount
||
null
,
valid_from: data.valid_from
||
null
,
valid_until: data.valid_until
||
null
,
minimum_stay_nights: data.minimum_stay_nights
||
null
,
is_active: data.is_active
||
false
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await negotiated_rates.setOrganization(currentUser.organization.id || null, {
transaction,
});
await negotiated_rates.setProperty( data.property || null, {
transaction,
});
await negotiated_rates.setUnit_type( data.unit_type || null, {
transaction,
});
return negotiated_rates;
}
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 negotiated_ratesData = data.map((item, index) => ({
id: item.id || undefined,
rate_type: item.rate_type
||
null
,
rate_amount: item.rate_amount
||
null
,
valid_from: item.valid_from
||
null
,
valid_until: item.valid_until
||
null
,
minimum_stay_nights: item.minimum_stay_nights
||
null
,
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 negotiated_rates = await db.negotiated_rates.bulkCreate(negotiated_ratesData, { transaction });
// For each item created, replace relation files
return negotiated_rates;
}
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 negotiated_rates = await db.negotiated_rates.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.rate_type !== undefined) updatePayload.rate_type = data.rate_type;
if (data.rate_amount !== undefined) updatePayload.rate_amount = data.rate_amount;
if (data.valid_from !== undefined) updatePayload.valid_from = data.valid_from;
if (data.valid_until !== undefined) updatePayload.valid_until = data.valid_until;
if (data.minimum_stay_nights !== undefined) updatePayload.minimum_stay_nights = data.minimum_stay_nights;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await negotiated_rates.update(updatePayload, {transaction});
if (data.organization !== undefined) {
await negotiated_rates.setOrganization(
(globalAccess ? data.organization : currentUser.organization.id),
{ transaction }
);
}
if (data.property !== undefined) {
await negotiated_rates.setProperty(
data.property,
{ transaction }
);
}
if (data.unit_type !== undefined) {
await negotiated_rates.setUnit_type(
data.unit_type,
{ transaction }
);
}
return negotiated_rates;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const negotiated_rates = await db.negotiated_rates.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of negotiated_rates) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of negotiated_rates) {
await record.destroy({transaction});
}
});
return negotiated_rates;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const negotiated_rates = await db.negotiated_rates.findByPk(id, options);
await negotiated_rates.update({
deletedBy: currentUser.id
}, {
transaction,
});
await negotiated_rates.destroy({
transaction
});
return negotiated_rates;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const negotiated_rates = await db.negotiated_rates.findOne(
{ where },
{ transaction },
);
if (!negotiated_rates) {
return negotiated_rates;
}
const output = negotiated_rates.get({plain: true});
output.organization = await negotiated_rates.getOrganization({
transaction
});
output.property = await negotiated_rates.getProperty({
transaction
});
output.unit_type = await negotiated_rates.getUnit_type({
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',
},
{
model: db.properties,
as: 'property',
where: filter.property ? {
[Op.or]: [
{ id: { [Op.in]: filter.property.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.property.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.unit_types,
as: 'unit_type',
where: filter.unit_type ? {
[Op.or]: [
{ id: { [Op.in]: filter.unit_type.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.unit_type.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'negotiated_rates',
'notes',
filter.notes,
),
};
}
if (filter.rate_amountRange) {
const [start, end] = filter.rate_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
rate_amount: {
...where.rate_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
rate_amount: {
...where.rate_amount,
[Op.lte]: end,
},
};
}
}
if (filter.valid_fromRange) {
const [start, end] = filter.valid_fromRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
valid_from: {
...where.valid_from,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
valid_from: {
...where.valid_from,
[Op.lte]: end,
},
};
}
}
if (filter.valid_untilRange) {
const [start, end] = filter.valid_untilRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
valid_until: {
...where.valid_until,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
valid_until: {
...where.valid_until,
[Op.lte]: end,
},
};
}
}
if (filter.minimum_stay_nightsRange) {
const [start, end] = filter.minimum_stay_nightsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
minimum_stay_nights: {
...where.minimum_stay_nights,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
minimum_stay_nights: {
...where.minimum_stay_nights,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.rate_type) {
where = {
...where,
rate_type: filter.rate_type,
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
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.negotiated_rates.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(
'negotiated_rates',
'notes',
query,
),
],
};
}
const records = await db.negotiated_rates.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,667 @@
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 NotificationsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const notifications = await db.notifications.create(
{
id: data.id || undefined,
channel: data.channel
||
null
,
type: data.type
||
null
,
title: data.title
||
null
,
body: data.body
||
null
,
link_url: data.link_url
||
null
,
sent_at: data.sent_at
||
null
,
read_at: data.read_at
||
null
,
is_read: data.is_read
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await notifications.setTenant( data.tenant || null, {
transaction,
});
await notifications.setUser( data.user || null, {
transaction,
});
await notifications.setOrganizations( data.organizations || null, {
transaction,
});
return notifications;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const notificationsData = data.map((item, index) => ({
id: item.id || undefined,
channel: item.channel
||
null
,
type: item.type
||
null
,
title: item.title
||
null
,
body: item.body
||
null
,
link_url: item.link_url
||
null
,
sent_at: item.sent_at
||
null
,
read_at: item.read_at
||
null
,
is_read: item.is_read
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const notifications = await db.notifications.bulkCreate(notificationsData, { transaction });
// For each item created, replace relation files
return notifications;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const notifications = await db.notifications.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.channel !== undefined) updatePayload.channel = data.channel;
if (data.type !== undefined) updatePayload.type = data.type;
if (data.title !== undefined) updatePayload.title = data.title;
if (data.body !== undefined) updatePayload.body = data.body;
if (data.link_url !== undefined) updatePayload.link_url = data.link_url;
if (data.sent_at !== undefined) updatePayload.sent_at = data.sent_at;
if (data.read_at !== undefined) updatePayload.read_at = data.read_at;
if (data.is_read !== undefined) updatePayload.is_read = data.is_read;
updatePayload.updatedById = currentUser.id;
await notifications.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await notifications.setTenant(
data.tenant,
{ transaction }
);
}
if (data.user !== undefined) {
await notifications.setUser(
data.user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await notifications.setOrganizations(
data.organizations,
{ transaction }
);
}
return notifications;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const notifications = await db.notifications.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of notifications) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of notifications) {
await record.destroy({transaction});
}
});
return notifications;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const notifications = await db.notifications.findByPk(id, options);
await notifications.update({
deletedBy: currentUser.id
}, {
transaction,
});
await notifications.destroy({
transaction
});
return notifications;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const notifications = await db.notifications.findOne(
{ where },
{ transaction },
);
if (!notifications) {
return notifications;
}
const output = notifications.get({plain: true});
output.tenant = await notifications.getTenant({
transaction
});
output.user = await notifications.getUser({
transaction
});
output.organizations = await notifications.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.tenants,
as: 'tenant',
where: filter.tenant ? {
[Op.or]: [
{ id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'user',
where: filter.user ? {
[Op.or]: [
{ id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.title) {
where = {
...where,
[Op.and]: Utils.ilike(
'notifications',
'title',
filter.title,
),
};
}
if (filter.body) {
where = {
...where,
[Op.and]: Utils.ilike(
'notifications',
'body',
filter.body,
),
};
}
if (filter.link_url) {
where = {
...where,
[Op.and]: Utils.ilike(
'notifications',
'link_url',
filter.link_url,
),
};
}
if (filter.sent_atRange) {
const [start, end] = filter.sent_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sent_at: {
...where.sent_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sent_at: {
...where.sent_at,
[Op.lte]: end,
},
};
}
}
if (filter.read_atRange) {
const [start, end] = filter.read_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
read_at: {
...where.read_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
read_at: {
...where.read_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.channel) {
where = {
...where,
channel: filter.channel,
};
}
if (filter.type) {
where = {
...where,
type: filter.type,
};
}
if (filter.is_read) {
where = {
...where,
is_read: filter.is_read,
};
}
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.notifications.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'notifications',
'title',
query,
),
],
};
}
const records = await db.notifications.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,534 @@
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 Organization_membershipsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const organization_memberships = await db.organization_memberships.create(
{
id: data.id || undefined,
member_role: data.member_role
||
null
,
is_primary: data.is_primary
||
false
,
is_active: data.is_active
||
false
,
job_title: data.job_title
||
null
,
phone: data.phone
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await organization_memberships.setOrganization(currentUser.organization.id || null, {
transaction,
});
await organization_memberships.setUser( data.user || null, {
transaction,
});
return organization_memberships;
}
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 organization_membershipsData = data.map((item, index) => ({
id: item.id || undefined,
member_role: item.member_role
||
null
,
is_primary: item.is_primary
||
false
,
is_active: item.is_active
||
false
,
job_title: item.job_title
||
null
,
phone: item.phone
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const organization_memberships = await db.organization_memberships.bulkCreate(organization_membershipsData, { transaction });
// For each item created, replace relation files
return organization_memberships;
}
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 organization_memberships = await db.organization_memberships.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.member_role !== undefined) updatePayload.member_role = data.member_role;
if (data.is_primary !== undefined) updatePayload.is_primary = data.is_primary;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
if (data.job_title !== undefined) updatePayload.job_title = data.job_title;
if (data.phone !== undefined) updatePayload.phone = data.phone;
updatePayload.updatedById = currentUser.id;
await organization_memberships.update(updatePayload, {transaction});
if (data.organization !== undefined) {
await organization_memberships.setOrganization(
(globalAccess ? data.organization : currentUser.organization.id),
{ transaction }
);
}
if (data.user !== undefined) {
await organization_memberships.setUser(
data.user,
{ transaction }
);
}
return organization_memberships;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const organization_memberships = await db.organization_memberships.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of organization_memberships) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of organization_memberships) {
await record.destroy({transaction});
}
});
return organization_memberships;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const organization_memberships = await db.organization_memberships.findByPk(id, options);
await organization_memberships.update({
deletedBy: currentUser.id
}, {
transaction,
});
await organization_memberships.destroy({
transaction
});
return organization_memberships;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const organization_memberships = await db.organization_memberships.findOne(
{ where },
{ transaction },
);
if (!organization_memberships) {
return organization_memberships;
}
const output = organization_memberships.get({plain: true});
output.organization = await organization_memberships.getOrganization({
transaction
});
output.user = await organization_memberships.getUser({
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',
},
{
model: db.users,
as: 'user',
where: filter.user ? {
[Op.or]: [
{ id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.job_title) {
where = {
...where,
[Op.and]: Utils.ilike(
'organization_memberships',
'job_title',
filter.job_title,
),
};
}
if (filter.phone) {
where = {
...where,
[Op.and]: Utils.ilike(
'organization_memberships',
'phone',
filter.phone,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.member_role) {
where = {
...where,
member_role: filter.member_role,
};
}
if (filter.is_primary) {
where = {
...where,
is_primary: filter.is_primary,
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
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.organization_memberships.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(
'organization_memberships',
'job_title',
query,
),
],
};
}
const records = await db.organization_memberships.findAll({
attributes: [ 'id', 'job_title' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['job_title', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.job_title,
}));
}
};

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 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.role_assignments_organization = await organizations.getRole_assignments_organization({
transaction
});
output.organization_memberships_organization = await organizations.getOrganization_memberships_organization({
transaction
});
output.properties_organizations = await organizations.getProperties_organizations({
transaction
});
output.amenities_organizations = await organizations.getAmenities_organizations({
transaction
});
output.unit_types_organizations = await organizations.getUnit_types_organizations({
transaction
});
output.units_organizations = await organizations.getUnits_organizations({
transaction
});
output.unit_availability_blocks_organizations = await organizations.getUnit_availability_blocks_organizations({
transaction
});
output.negotiated_rates_organization = await organizations.getNegotiated_rates_organization({
transaction
});
output.booking_requests_organization = await organizations.getBooking_requests_organization({
transaction
});
output.booking_request_travelers_organizations = await organizations.getBooking_request_travelers_organizations({
transaction
});
output.approval_steps_organizations = await organizations.getApproval_steps_organizations({
transaction
});
output.reservations_organization = await organizations.getReservations_organization({
transaction
});
output.reservation_guests_organizations = await organizations.getReservation_guests_organizations({
transaction
});
output.service_requests_organizations = await organizations.getService_requests_organizations({
transaction
});
output.invoices_organization = await organizations.getInvoices_organization({
transaction
});
output.invoice_line_items_organizations = await organizations.getInvoice_line_items_organizations({
transaction
});
output.payments_organizations = await organizations.getPayments_organizations({
transaction
});
output.documents_organization = await organizations.getDocuments_organization({
transaction
});
output.audit_logs_organizations = await organizations.getAudit_logs_organizations({
transaction
});
output.notifications_organizations = await organizations.getNotifications_organizations({
transaction
});
output.activity_comments_organization = await organizations.getActivity_comments_organization({
transaction
});
output.checklists_organizations = await organizations.getChecklists_organizations({
transaction
});
output.checklist_items_organizations = await organizations.getChecklist_items_organizations({
transaction
});
output.job_runs_organizations = await organizations.getJob_runs_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,650 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class PaymentsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const payments = await db.payments.create(
{
id: data.id || undefined,
payment_method: data.payment_method
||
null
,
status: data.status
||
null
,
amount: data.amount
||
null
,
currency: data.currency
||
null
,
paid_at: data.paid_at
||
null
,
reference: data.reference
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await payments.setInvoice( data.invoice || null, {
transaction,
});
await payments.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.payments.getTableName(),
belongsToColumn: 'receipt_file',
belongsToId: payments.id,
},
data.receipt_file,
options,
);
return payments;
}
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 paymentsData = data.map((item, index) => ({
id: item.id || undefined,
payment_method: item.payment_method
||
null
,
status: item.status
||
null
,
amount: item.amount
||
null
,
currency: item.currency
||
null
,
paid_at: item.paid_at
||
null
,
reference: item.reference
||
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 payments = await db.payments.bulkCreate(paymentsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < payments.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.payments.getTableName(),
belongsToColumn: 'receipt_file',
belongsToId: payments[i].id,
},
data[i].receipt_file,
options,
);
}
return payments;
}
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 payments = await db.payments.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.payment_method !== undefined) updatePayload.payment_method = data.payment_method;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.amount !== undefined) updatePayload.amount = data.amount;
if (data.currency !== undefined) updatePayload.currency = data.currency;
if (data.paid_at !== undefined) updatePayload.paid_at = data.paid_at;
if (data.reference !== undefined) updatePayload.reference = data.reference;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await payments.update(updatePayload, {transaction});
if (data.invoice !== undefined) {
await payments.setInvoice(
data.invoice,
{ transaction }
);
}
if (data.organizations !== undefined) {
await payments.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.payments.getTableName(),
belongsToColumn: 'receipt_file',
belongsToId: payments.id,
},
data.receipt_file,
options,
);
return payments;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const payments = await db.payments.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of payments) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of payments) {
await record.destroy({transaction});
}
});
return payments;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const payments = await db.payments.findByPk(id, options);
await payments.update({
deletedBy: currentUser.id
}, {
transaction,
});
await payments.destroy({
transaction
});
return payments;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const payments = await db.payments.findOne(
{ where },
{ transaction },
);
if (!payments) {
return payments;
}
const output = payments.get({plain: true});
output.invoice = await payments.getInvoice({
transaction
});
output.receipt_file = await payments.getReceipt_file({
transaction
});
output.organizations = await payments.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.invoices,
as: 'invoice',
where: filter.invoice ? {
[Op.or]: [
{ id: { [Op.in]: filter.invoice.split('|').map(term => Utils.uuid(term)) } },
{
invoice_number: {
[Op.or]: filter.invoice.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'receipt_file',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.currency) {
where = {
...where,
[Op.and]: Utils.ilike(
'payments',
'currency',
filter.currency,
),
};
}
if (filter.reference) {
where = {
...where,
[Op.and]: Utils.ilike(
'payments',
'reference',
filter.reference,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'payments',
'notes',
filter.notes,
),
};
}
if (filter.amountRange) {
const [start, end] = filter.amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
amount: {
...where.amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
amount: {
...where.amount,
[Op.lte]: end,
},
};
}
}
if (filter.paid_atRange) {
const [start, end] = filter.paid_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
paid_at: {
...where.paid_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
paid_at: {
...where.paid_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.payment_method) {
where = {
...where,
payment_method: filter.payment_method,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
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.payments.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(
'payments',
'reference',
query,
),
],
};
}
const records = await db.payments.findAll({
attributes: [ 'id', 'reference' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['reference', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.reference,
}));
}
};

View File

@ -0,0 +1,358 @@
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,
}));
}
};

View File

@ -0,0 +1,804 @@
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 PropertiesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const properties = await db.properties.create(
{
id: data.id || undefined,
name: data.name
||
null
,
code: data.code
||
null
,
address: data.address
||
null
,
city: data.city
||
null
,
country: data.country
||
null
,
timezone: data.timezone
||
null
,
description: data.description
||
null
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await properties.setTenant( data.tenant || null, {
transaction,
});
await properties.setOrganizations( data.organizations || null, {
transaction,
});
await properties.setUnit_types(data.unit_types || [], {
transaction,
});
await properties.setUnits(data.units || [], {
transaction,
});
await properties.setAmenities(data.amenities || [], {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.properties.getTableName(),
belongsToColumn: 'images',
belongsToId: properties.id,
},
data.images,
options,
);
return properties;
}
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 propertiesData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
code: item.code
||
null
,
address: item.address
||
null
,
city: item.city
||
null
,
country: item.country
||
null
,
timezone: item.timezone
||
null
,
description: item.description
||
null
,
is_active: item.is_active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const properties = await db.properties.bulkCreate(propertiesData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < properties.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.properties.getTableName(),
belongsToColumn: 'images',
belongsToId: properties[i].id,
},
data[i].images,
options,
);
}
return properties;
}
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 properties = await db.properties.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.code !== undefined) updatePayload.code = data.code;
if (data.address !== undefined) updatePayload.address = data.address;
if (data.city !== undefined) updatePayload.city = data.city;
if (data.country !== undefined) updatePayload.country = data.country;
if (data.timezone !== undefined) updatePayload.timezone = data.timezone;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await properties.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await properties.setTenant(
data.tenant,
{ transaction }
);
}
if (data.organizations !== undefined) {
await properties.setOrganizations(
data.organizations,
{ transaction }
);
}
if (data.unit_types !== undefined) {
await properties.setUnit_types(data.unit_types, { transaction });
}
if (data.units !== undefined) {
await properties.setUnits(data.units, { transaction });
}
if (data.amenities !== undefined) {
await properties.setAmenities(data.amenities, { transaction });
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.properties.getTableName(),
belongsToColumn: 'images',
belongsToId: properties.id,
},
data.images,
options,
);
return properties;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const properties = await db.properties.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of properties) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of properties) {
await record.destroy({transaction});
}
});
return properties;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const properties = await db.properties.findByPk(id, options);
await properties.update({
deletedBy: currentUser.id
}, {
transaction,
});
await properties.destroy({
transaction
});
return properties;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const properties = await db.properties.findOne(
{ where },
{ transaction },
);
if (!properties) {
return properties;
}
const output = properties.get({plain: true});
output.amenities_property = await properties.getAmenities_property({
transaction
});
output.unit_types_property = await properties.getUnit_types_property({
transaction
});
output.units_property = await properties.getUnits_property({
transaction
});
output.negotiated_rates_property = await properties.getNegotiated_rates_property({
transaction
});
output.booking_requests_preferred_property = await properties.getBooking_requests_preferred_property({
transaction
});
output.reservations_property = await properties.getReservations_property({
transaction
});
output.tenant = await properties.getTenant({
transaction
});
output.images = await properties.getImages({
transaction
});
output.unit_types = await properties.getUnit_types({
transaction
});
output.units = await properties.getUnits({
transaction
});
output.amenities = await properties.getAmenities({
transaction
});
output.organizations = await properties.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.tenants,
as: 'tenant',
where: filter.tenant ? {
[Op.or]: [
{ id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.unit_types,
as: 'unit_types',
required: false,
},
{
model: db.units,
as: 'units',
required: false,
},
{
model: db.amenities,
as: 'amenities',
required: false,
},
{
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(
'properties',
'name',
filter.name,
),
};
}
if (filter.code) {
where = {
...where,
[Op.and]: Utils.ilike(
'properties',
'code',
filter.code,
),
};
}
if (filter.address) {
where = {
...where,
[Op.and]: Utils.ilike(
'properties',
'address',
filter.address,
),
};
}
if (filter.city) {
where = {
...where,
[Op.and]: Utils.ilike(
'properties',
'city',
filter.city,
),
};
}
if (filter.country) {
where = {
...where,
[Op.and]: Utils.ilike(
'properties',
'country',
filter.country,
),
};
}
if (filter.timezone) {
where = {
...where,
[Op.and]: Utils.ilike(
'properties',
'timezone',
filter.timezone,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'properties',
'description',
filter.description,
),
};
}
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.unit_types) {
const searchTerms = filter.unit_types.split('|');
include = [
{
model: db.unit_types,
as: 'unit_types_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.units) {
const searchTerms = filter.units.split('|');
include = [
{
model: db.units,
as: 'units_filter',
required: searchTerms.length > 0,
where: searchTerms.length > 0 ? {
[Op.or]: [
{ id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
{
unit_number: {
[Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
}
}
]
} : undefined
},
...include,
]
}
if (filter.amenities) {
const searchTerms = filter.amenities.split('|');
include = [
{
model: db.amenities,
as: 'amenities_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) {
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.properties.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(
'properties',
'name',
query,
),
],
};
}
const records = await db.properties.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,560 @@
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 Reservation_guestsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const reservation_guests = await db.reservation_guests.create(
{
id: data.id || undefined,
full_name: data.full_name
||
null
,
email: data.email
||
null
,
phone: data.phone
||
null
,
guest_type: data.guest_type
||
null
,
primary_guest: data.primary_guest
||
false
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await reservation_guests.setReservation( data.reservation || null, {
transaction,
});
await reservation_guests.setOrganizations( data.organizations || null, {
transaction,
});
return reservation_guests;
}
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 reservation_guestsData = data.map((item, index) => ({
id: item.id || undefined,
full_name: item.full_name
||
null
,
email: item.email
||
null
,
phone: item.phone
||
null
,
guest_type: item.guest_type
||
null
,
primary_guest: item.primary_guest
||
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 reservation_guests = await db.reservation_guests.bulkCreate(reservation_guestsData, { transaction });
// For each item created, replace relation files
return reservation_guests;
}
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 reservation_guests = await db.reservation_guests.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.full_name !== undefined) updatePayload.full_name = data.full_name;
if (data.email !== undefined) updatePayload.email = data.email;
if (data.phone !== undefined) updatePayload.phone = data.phone;
if (data.guest_type !== undefined) updatePayload.guest_type = data.guest_type;
if (data.primary_guest !== undefined) updatePayload.primary_guest = data.primary_guest;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await reservation_guests.update(updatePayload, {transaction});
if (data.reservation !== undefined) {
await reservation_guests.setReservation(
data.reservation,
{ transaction }
);
}
if (data.organizations !== undefined) {
await reservation_guests.setOrganizations(
data.organizations,
{ transaction }
);
}
return reservation_guests;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const reservation_guests = await db.reservation_guests.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of reservation_guests) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of reservation_guests) {
await record.destroy({transaction});
}
});
return reservation_guests;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const reservation_guests = await db.reservation_guests.findByPk(id, options);
await reservation_guests.update({
deletedBy: currentUser.id
}, {
transaction,
});
await reservation_guests.destroy({
transaction
});
return reservation_guests;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const reservation_guests = await db.reservation_guests.findOne(
{ where },
{ transaction },
);
if (!reservation_guests) {
return reservation_guests;
}
const output = reservation_guests.get({plain: true});
output.reservation = await reservation_guests.getReservation({
transaction
});
output.organizations = await reservation_guests.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.reservations,
as: 'reservation',
where: filter.reservation ? {
[Op.or]: [
{ id: { [Op.in]: filter.reservation.split('|').map(term => Utils.uuid(term)) } },
{
reservation_code: {
[Op.or]: filter.reservation.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.full_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'reservation_guests',
'full_name',
filter.full_name,
),
};
}
if (filter.email) {
where = {
...where,
[Op.and]: Utils.ilike(
'reservation_guests',
'email',
filter.email,
),
};
}
if (filter.phone) {
where = {
...where,
[Op.and]: Utils.ilike(
'reservation_guests',
'phone',
filter.phone,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'reservation_guests',
'notes',
filter.notes,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.guest_type) {
where = {
...where,
guest_type: filter.guest_type,
};
}
if (filter.primary_guest) {
where = {
...where,
primary_guest: filter.primary_guest,
};
}
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.reservation_guests.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(
'reservation_guests',
'full_name',
query,
),
],
};
}
const records = await db.reservation_guests.findAll({
attributes: [ 'id', 'full_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['full_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.full_name,
}));
}
};

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,592 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Role_assignmentsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const role_assignments = await db.role_assignments.create(
{
id: data.id || undefined,
is_active: data.is_active
||
false
,
effective_from: data.effective_from
||
null
,
effective_until: data.effective_until
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await role_assignments.setUser( data.user || null, {
transaction,
});
await role_assignments.setRole( data.role || null, {
transaction,
});
await role_assignments.setTenant( data.tenant || null, {
transaction,
});
await role_assignments.setOrganization(currentUser.organization.id || null, {
transaction,
});
return role_assignments;
}
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 role_assignmentsData = data.map((item, index) => ({
id: item.id || undefined,
is_active: item.is_active
||
false
,
effective_from: item.effective_from
||
null
,
effective_until: item.effective_until
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const role_assignments = await db.role_assignments.bulkCreate(role_assignmentsData, { transaction });
// For each item created, replace relation files
return role_assignments;
}
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 role_assignments = await db.role_assignments.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
if (data.effective_from !== undefined) updatePayload.effective_from = data.effective_from;
if (data.effective_until !== undefined) updatePayload.effective_until = data.effective_until;
updatePayload.updatedById = currentUser.id;
await role_assignments.update(updatePayload, {transaction});
if (data.user !== undefined) {
await role_assignments.setUser(
data.user,
{ transaction }
);
}
if (data.role !== undefined) {
await role_assignments.setRole(
data.role,
{ transaction }
);
}
if (data.tenant !== undefined) {
await role_assignments.setTenant(
data.tenant,
{ transaction }
);
}
if (data.organization !== undefined) {
await role_assignments.setOrganization(
(globalAccess ? data.organization : currentUser.organization.id),
{ transaction }
);
}
return role_assignments;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const role_assignments = await db.role_assignments.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of role_assignments) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of role_assignments) {
await record.destroy({transaction});
}
});
return role_assignments;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const role_assignments = await db.role_assignments.findByPk(id, options);
await role_assignments.update({
deletedBy: currentUser.id
}, {
transaction,
});
await role_assignments.destroy({
transaction
});
return role_assignments;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const role_assignments = await db.role_assignments.findOne(
{ where },
{ transaction },
);
if (!role_assignments) {
return role_assignments;
}
const output = role_assignments.get({plain: true});
output.user = await role_assignments.getUser({
transaction
});
output.role = await role_assignments.getRole({
transaction
});
output.tenant = await role_assignments.getTenant({
transaction
});
output.organization = await role_assignments.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.users,
as: 'user',
where: filter.user ? {
[Op.or]: [
{ id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.roles,
as: 'role',
where: filter.role ? {
[Op.or]: [
{ id: { [Op.in]: filter.role.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.role.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.tenants,
as: 'tenant',
where: filter.tenant ? {
[Op.or]: [
{ id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organization',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.effective_fromRange) {
const [start, end] = filter.effective_fromRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
effective_from: {
...where.effective_from,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
effective_from: {
...where.effective_from,
[Op.lte]: end,
},
};
}
}
if (filter.effective_untilRange) {
const [start, end] = filter.effective_untilRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
effective_until: {
...where.effective_until,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
effective_until: {
...where.effective_until,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
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.role_assignments.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(
'role_assignments',
'effective_from',
query,
),
],
};
}
const records = await db.role_assignments.findAll({
attributes: [ 'id', 'effective_from' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['effective_from', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.effective_from,
}));
}
};

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

@ -0,0 +1,464 @@
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.role_assignments_role = await roles.getRole_assignments_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,942 @@
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 Service_requestsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const service_requests = await db.service_requests.create(
{
id: data.id || undefined,
request_type: data.request_type
||
null
,
status: data.status
||
null
,
priority: data.priority
||
null
,
requested_at: data.requested_at
||
null
,
due_at: data.due_at
||
null
,
completed_at: data.completed_at
||
null
,
summary: data.summary
||
null
,
details: data.details
||
null
,
estimated_cost: data.estimated_cost
||
null
,
actual_cost: data.actual_cost
||
null
,
currency: data.currency
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await service_requests.setTenant( data.tenant || null, {
transaction,
});
await service_requests.setReservation( data.reservation || null, {
transaction,
});
await service_requests.setRequested_by( data.requested_by || null, {
transaction,
});
await service_requests.setAssigned_to( data.assigned_to || null, {
transaction,
});
await service_requests.setOrganizations( data.organizations || null, {
transaction,
});
await service_requests.setDocuments(data.documents || [], {
transaction,
});
await service_requests.setComments(data.comments || [], {
transaction,
});
return service_requests;
}
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 service_requestsData = data.map((item, index) => ({
id: item.id || undefined,
request_type: item.request_type
||
null
,
status: item.status
||
null
,
priority: item.priority
||
null
,
requested_at: item.requested_at
||
null
,
due_at: item.due_at
||
null
,
completed_at: item.completed_at
||
null
,
summary: item.summary
||
null
,
details: item.details
||
null
,
estimated_cost: item.estimated_cost
||
null
,
actual_cost: item.actual_cost
||
null
,
currency: item.currency
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const service_requests = await db.service_requests.bulkCreate(service_requestsData, { transaction });
// For each item created, replace relation files
return service_requests;
}
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 service_requests = await db.service_requests.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.request_type !== undefined) updatePayload.request_type = data.request_type;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.priority !== undefined) updatePayload.priority = data.priority;
if (data.requested_at !== undefined) updatePayload.requested_at = data.requested_at;
if (data.due_at !== undefined) updatePayload.due_at = data.due_at;
if (data.completed_at !== undefined) updatePayload.completed_at = data.completed_at;
if (data.summary !== undefined) updatePayload.summary = data.summary;
if (data.details !== undefined) updatePayload.details = data.details;
if (data.estimated_cost !== undefined) updatePayload.estimated_cost = data.estimated_cost;
if (data.actual_cost !== undefined) updatePayload.actual_cost = data.actual_cost;
if (data.currency !== undefined) updatePayload.currency = data.currency;
updatePayload.updatedById = currentUser.id;
await service_requests.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await service_requests.setTenant(
data.tenant,
{ transaction }
);
}
if (data.reservation !== undefined) {
await service_requests.setReservation(
data.reservation,
{ transaction }
);
}
if (data.requested_by !== undefined) {
await service_requests.setRequested_by(
data.requested_by,
{ transaction }
);
}
if (data.assigned_to !== undefined) {
await service_requests.setAssigned_to(
data.assigned_to,
{ transaction }
);
}
if (data.organizations !== undefined) {
await service_requests.setOrganizations(
data.organizations,
{ transaction }
);
}
if (data.documents !== undefined) {
await service_requests.setDocuments(data.documents, { transaction });
}
if (data.comments !== undefined) {
await service_requests.setComments(data.comments, { transaction });
}
return service_requests;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const service_requests = await db.service_requests.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of service_requests) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of service_requests) {
await record.destroy({transaction});
}
});
return service_requests;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const service_requests = await db.service_requests.findByPk(id, options);
await service_requests.update({
deletedBy: currentUser.id
}, {
transaction,
});
await service_requests.destroy({
transaction
});
return service_requests;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const service_requests = await db.service_requests.findOne(
{ where },
{ transaction },
);
if (!service_requests) {
return service_requests;
}
const output = service_requests.get({plain: true});
output.documents_service_request = await service_requests.getDocuments_service_request({
transaction
});
output.activity_comments_service_request = await service_requests.getActivity_comments_service_request({
transaction
});
output.tenant = await service_requests.getTenant({
transaction
});
output.reservation = await service_requests.getReservation({
transaction
});
output.requested_by = await service_requests.getRequested_by({
transaction
});
output.assigned_to = await service_requests.getAssigned_to({
transaction
});
output.documents = await service_requests.getDocuments({
transaction
});
output.comments = await service_requests.getComments({
transaction
});
output.organizations = await service_requests.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.tenants,
as: 'tenant',
where: filter.tenant ? {
[Op.or]: [
{ id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.reservations,
as: 'reservation',
where: filter.reservation ? {
[Op.or]: [
{ id: { [Op.in]: filter.reservation.split('|').map(term => Utils.uuid(term)) } },
{
reservation_code: {
[Op.or]: filter.reservation.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'requested_by',
where: filter.requested_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.requested_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.requested_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'assigned_to',
where: filter.assigned_to ? {
[Op.or]: [
{ id: { [Op.in]: filter.assigned_to.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.assigned_to.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.documents,
as: 'documents',
required: false,
},
{
model: db.activity_comments,
as: 'comments',
required: false,
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.summary) {
where = {
...where,
[Op.and]: Utils.ilike(
'service_requests',
'summary',
filter.summary,
),
};
}
if (filter.details) {
where = {
...where,
[Op.and]: Utils.ilike(
'service_requests',
'details',
filter.details,
),
};
}
if (filter.currency) {
where = {
...where,
[Op.and]: Utils.ilike(
'service_requests',
'currency',
filter.currency,
),
};
}
if (filter.requested_atRange) {
const [start, end] = filter.requested_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
requested_at: {
...where.requested_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
requested_at: {
...where.requested_at,
[Op.lte]: end,
},
};
}
}
if (filter.due_atRange) {
const [start, end] = filter.due_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
due_at: {
...where.due_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
due_at: {
...where.due_at,
[Op.lte]: end,
},
};
}
}
if (filter.completed_atRange) {
const [start, end] = filter.completed_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
completed_at: {
...where.completed_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
completed_at: {
...where.completed_at,
[Op.lte]: end,
},
};
}
}
if (filter.estimated_costRange) {
const [start, end] = filter.estimated_costRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
estimated_cost: {
...where.estimated_cost,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
estimated_cost: {
...where.estimated_cost,
[Op.lte]: end,
},
};
}
}
if (filter.actual_costRange) {
const [start, end] = filter.actual_costRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
actual_cost: {
...where.actual_cost,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
actual_cost: {
...where.actual_cost,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.request_type) {
where = {
...where,
request_type: filter.request_type,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.priority) {
where = {
...where,
priority: filter.priority,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.documents) {
const searchTerms = filter.documents.split('|');
include = [
{
model: db.documents,
as: 'documents_filter',
required: searchTerms.length > 0,
where: searchTerms.length > 0 ? {
[Op.or]: [
{ id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
{
file_name: {
[Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
}
}
]
} : undefined
},
...include,
]
}
if (filter.comments) {
const searchTerms = filter.comments.split('|');
include = [
{
model: db.activity_comments,
as: 'comments_filter',
required: searchTerms.length > 0,
where: searchTerms.length > 0 ? {
[Op.or]: [
{ id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
{
body: {
[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) {
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.service_requests.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(
'service_requests',
'summary',
query,
),
],
};
}
const records = await db.service_requests.findAll({
attributes: [ 'id', 'summary' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['summary', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.summary,
}));
}
};

View File

@ -0,0 +1,688 @@
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 TenantsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const tenants = await db.tenants.create(
{
id: data.id || undefined,
name: data.name
||
null
,
slug: data.slug
||
null
,
legal_name: data.legal_name
||
null
,
primary_domain: data.primary_domain
||
null
,
timezone: data.timezone
||
null
,
default_currency: data.default_currency
||
null
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await tenants.setOrganizations(data.organizations || [], {
transaction,
});
await tenants.setProperties(data.properties || [], {
transaction,
});
await tenants.setAudit_logs(data.audit_logs || [], {
transaction,
});
return tenants;
}
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 tenantsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
slug: item.slug
||
null
,
legal_name: item.legal_name
||
null
,
primary_domain: item.primary_domain
||
null
,
timezone: item.timezone
||
null
,
default_currency: item.default_currency
||
null
,
is_active: item.is_active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const tenants = await db.tenants.bulkCreate(tenantsData, { transaction });
// For each item created, replace relation files
return tenants;
}
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 tenants = await db.tenants.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.slug !== undefined) updatePayload.slug = data.slug;
if (data.legal_name !== undefined) updatePayload.legal_name = data.legal_name;
if (data.primary_domain !== undefined) updatePayload.primary_domain = data.primary_domain;
if (data.timezone !== undefined) updatePayload.timezone = data.timezone;
if (data.default_currency !== undefined) updatePayload.default_currency = data.default_currency;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await tenants.update(updatePayload, {transaction});
if (data.organizations !== undefined) {
await tenants.setOrganizations(data.organizations, { transaction });
}
if (data.properties !== undefined) {
await tenants.setProperties(data.properties, { transaction });
}
if (data.audit_logs !== undefined) {
await tenants.setAudit_logs(data.audit_logs, { transaction });
}
return tenants;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const tenants = await db.tenants.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of tenants) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of tenants) {
await record.destroy({transaction});
}
});
return tenants;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const tenants = await db.tenants.findByPk(id, options);
await tenants.update({
deletedBy: currentUser.id
}, {
transaction,
});
await tenants.destroy({
transaction
});
return tenants;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const tenants = await db.tenants.findOne(
{ where },
{ transaction },
);
if (!tenants) {
return tenants;
}
const output = tenants.get({plain: true});
output.role_assignments_tenant = await tenants.getRole_assignments_tenant({
transaction
});
output.properties_tenant = await tenants.getProperties_tenant({
transaction
});
output.booking_requests_tenant = await tenants.getBooking_requests_tenant({
transaction
});
output.reservations_tenant = await tenants.getReservations_tenant({
transaction
});
output.service_requests_tenant = await tenants.getService_requests_tenant({
transaction
});
output.invoices_tenant = await tenants.getInvoices_tenant({
transaction
});
output.documents_tenant = await tenants.getDocuments_tenant({
transaction
});
output.audit_logs_tenant = await tenants.getAudit_logs_tenant({
transaction
});
output.notifications_tenant = await tenants.getNotifications_tenant({
transaction
});
output.activity_comments_tenant = await tenants.getActivity_comments_tenant({
transaction
});
output.checklists_tenant = await tenants.getChecklists_tenant({
transaction
});
output.job_runs_tenant = await tenants.getJob_runs_tenant({
transaction
});
output.organizations = await tenants.getOrganizations({
transaction
});
output.properties = await tenants.getProperties({
transaction
});
output.audit_logs = await tenants.getAudit_logs({
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',
required: false,
},
{
model: db.properties,
as: 'properties',
required: false,
},
{
model: db.audit_logs,
as: 'audit_logs',
required: false,
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'tenants',
'name',
filter.name,
),
};
}
if (filter.slug) {
where = {
...where,
[Op.and]: Utils.ilike(
'tenants',
'slug',
filter.slug,
),
};
}
if (filter.legal_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'tenants',
'legal_name',
filter.legal_name,
),
};
}
if (filter.primary_domain) {
where = {
...where,
[Op.and]: Utils.ilike(
'tenants',
'primary_domain',
filter.primary_domain,
),
};
}
if (filter.timezone) {
where = {
...where,
[Op.and]: Utils.ilike(
'tenants',
'timezone',
filter.timezone,
),
};
}
if (filter.default_currency) {
where = {
...where,
[Op.and]: Utils.ilike(
'tenants',
'default_currency',
filter.default_currency,
),
};
}
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 searchTerms = filter.organizations.split('|');
include = [
{
model: db.organizations,
as: 'organizations_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.properties) {
const searchTerms = filter.properties.split('|');
include = [
{
model: db.properties,
as: 'properties_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.audit_logs) {
const searchTerms = filter.audit_logs.split('|');
include = [
{
model: db.audit_logs,
as: 'audit_logs_filter',
required: searchTerms.length > 0,
where: searchTerms.length > 0 ? {
[Op.or]: [
{ id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
{
action: {
[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) {
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.tenants.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(
'tenants',
'name',
query,
),
],
};
}
const records = await db.tenants.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,595 @@
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 Unit_availability_blocksDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const unit_availability_blocks = await db.unit_availability_blocks.create(
{
id: data.id || undefined,
block_type: data.block_type
||
null
,
start_at: data.start_at
||
null
,
end_at: data.end_at
||
null
,
reason: data.reason
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await unit_availability_blocks.setUnit( data.unit || null, {
transaction,
});
await unit_availability_blocks.setReservation( data.reservation || null, {
transaction,
});
await unit_availability_blocks.setOrganizations( data.organizations || null, {
transaction,
});
return unit_availability_blocks;
}
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 unit_availability_blocksData = data.map((item, index) => ({
id: item.id || undefined,
block_type: item.block_type
||
null
,
start_at: item.start_at
||
null
,
end_at: item.end_at
||
null
,
reason: item.reason
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const unit_availability_blocks = await db.unit_availability_blocks.bulkCreate(unit_availability_blocksData, { transaction });
// For each item created, replace relation files
return unit_availability_blocks;
}
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 unit_availability_blocks = await db.unit_availability_blocks.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.block_type !== undefined) updatePayload.block_type = data.block_type;
if (data.start_at !== undefined) updatePayload.start_at = data.start_at;
if (data.end_at !== undefined) updatePayload.end_at = data.end_at;
if (data.reason !== undefined) updatePayload.reason = data.reason;
updatePayload.updatedById = currentUser.id;
await unit_availability_blocks.update(updatePayload, {transaction});
if (data.unit !== undefined) {
await unit_availability_blocks.setUnit(
data.unit,
{ transaction }
);
}
if (data.reservation !== undefined) {
await unit_availability_blocks.setReservation(
data.reservation,
{ transaction }
);
}
if (data.organizations !== undefined) {
await unit_availability_blocks.setOrganizations(
data.organizations,
{ transaction }
);
}
return unit_availability_blocks;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const unit_availability_blocks = await db.unit_availability_blocks.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of unit_availability_blocks) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of unit_availability_blocks) {
await record.destroy({transaction});
}
});
return unit_availability_blocks;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const unit_availability_blocks = await db.unit_availability_blocks.findByPk(id, options);
await unit_availability_blocks.update({
deletedBy: currentUser.id
}, {
transaction,
});
await unit_availability_blocks.destroy({
transaction
});
return unit_availability_blocks;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const unit_availability_blocks = await db.unit_availability_blocks.findOne(
{ where },
{ transaction },
);
if (!unit_availability_blocks) {
return unit_availability_blocks;
}
const output = unit_availability_blocks.get({plain: true});
output.unit = await unit_availability_blocks.getUnit({
transaction
});
output.reservation = await unit_availability_blocks.getReservation({
transaction
});
output.organizations = await unit_availability_blocks.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.units,
as: 'unit',
where: filter.unit ? {
[Op.or]: [
{ id: { [Op.in]: filter.unit.split('|').map(term => Utils.uuid(term)) } },
{
unit_number: {
[Op.or]: filter.unit.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.reservations,
as: 'reservation',
where: filter.reservation ? {
[Op.or]: [
{ id: { [Op.in]: filter.reservation.split('|').map(term => Utils.uuid(term)) } },
{
reservation_code: {
[Op.or]: filter.reservation.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.reason) {
where = {
...where,
[Op.and]: Utils.ilike(
'unit_availability_blocks',
'reason',
filter.reason,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
start_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
end_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.start_atRange) {
const [start, end] = filter.start_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
start_at: {
...where.start_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
start_at: {
...where.start_at,
[Op.lte]: end,
},
};
}
}
if (filter.end_atRange) {
const [start, end] = filter.end_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
end_at: {
...where.end_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
end_at: {
...where.end_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.block_type) {
where = {
...where,
block_type: filter.block_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.unit_availability_blocks.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(
'unit_availability_blocks',
'reason',
query,
),
],
};
}
const records = await db.unit_availability_blocks.findAll({
attributes: [ 'id', 'reason' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['reason', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.reason,
}));
}
};

View File

@ -0,0 +1,811 @@
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 Unit_typesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const unit_types = await db.unit_types.create(
{
id: data.id || undefined,
name: data.name
||
null
,
code: data.code
||
null
,
max_occupancy: data.max_occupancy
||
null
,
bedrooms: data.bedrooms
||
null
,
bathrooms: data.bathrooms
||
null
,
size_sqm: data.size_sqm
||
null
,
description: data.description
||
null
,
base_nightly_rate: data.base_nightly_rate
||
null
,
base_monthly_rate: data.base_monthly_rate
||
null
,
minimum_stay_nights: data.minimum_stay_nights
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await unit_types.setProperty( data.property || null, {
transaction,
});
await unit_types.setOrganizations( data.organizations || null, {
transaction,
});
await unit_types.setUnits(data.units || [], {
transaction,
});
return unit_types;
}
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 unit_typesData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
code: item.code
||
null
,
max_occupancy: item.max_occupancy
||
null
,
bedrooms: item.bedrooms
||
null
,
bathrooms: item.bathrooms
||
null
,
size_sqm: item.size_sqm
||
null
,
description: item.description
||
null
,
base_nightly_rate: item.base_nightly_rate
||
null
,
base_monthly_rate: item.base_monthly_rate
||
null
,
minimum_stay_nights: item.minimum_stay_nights
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const unit_types = await db.unit_types.bulkCreate(unit_typesData, { transaction });
// For each item created, replace relation files
return unit_types;
}
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 unit_types = await db.unit_types.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.code !== undefined) updatePayload.code = data.code;
if (data.max_occupancy !== undefined) updatePayload.max_occupancy = data.max_occupancy;
if (data.bedrooms !== undefined) updatePayload.bedrooms = data.bedrooms;
if (data.bathrooms !== undefined) updatePayload.bathrooms = data.bathrooms;
if (data.size_sqm !== undefined) updatePayload.size_sqm = data.size_sqm;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.base_nightly_rate !== undefined) updatePayload.base_nightly_rate = data.base_nightly_rate;
if (data.base_monthly_rate !== undefined) updatePayload.base_monthly_rate = data.base_monthly_rate;
if (data.minimum_stay_nights !== undefined) updatePayload.minimum_stay_nights = data.minimum_stay_nights;
updatePayload.updatedById = currentUser.id;
await unit_types.update(updatePayload, {transaction});
if (data.property !== undefined) {
await unit_types.setProperty(
data.property,
{ transaction }
);
}
if (data.organizations !== undefined) {
await unit_types.setOrganizations(
data.organizations,
{ transaction }
);
}
if (data.units !== undefined) {
await unit_types.setUnits(data.units, { transaction });
}
return unit_types;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const unit_types = await db.unit_types.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of unit_types) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of unit_types) {
await record.destroy({transaction});
}
});
return unit_types;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const unit_types = await db.unit_types.findByPk(id, options);
await unit_types.update({
deletedBy: currentUser.id
}, {
transaction,
});
await unit_types.destroy({
transaction
});
return unit_types;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const unit_types = await db.unit_types.findOne(
{ where },
{ transaction },
);
if (!unit_types) {
return unit_types;
}
const output = unit_types.get({plain: true});
output.units_unit_type = await unit_types.getUnits_unit_type({
transaction
});
output.negotiated_rates_unit_type = await unit_types.getNegotiated_rates_unit_type({
transaction
});
output.booking_requests_preferred_unit_type = await unit_types.getBooking_requests_preferred_unit_type({
transaction
});
output.reservations_unit_type = await unit_types.getReservations_unit_type({
transaction
});
output.property = await unit_types.getProperty({
transaction
});
output.units = await unit_types.getUnits({
transaction
});
output.organizations = await unit_types.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.properties,
as: 'property',
where: filter.property ? {
[Op.or]: [
{ id: { [Op.in]: filter.property.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.property.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.units,
as: 'units',
required: false,
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'unit_types',
'name',
filter.name,
),
};
}
if (filter.code) {
where = {
...where,
[Op.and]: Utils.ilike(
'unit_types',
'code',
filter.code,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'unit_types',
'description',
filter.description,
),
};
}
if (filter.max_occupancyRange) {
const [start, end] = filter.max_occupancyRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
max_occupancy: {
...where.max_occupancy,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
max_occupancy: {
...where.max_occupancy,
[Op.lte]: end,
},
};
}
}
if (filter.bedroomsRange) {
const [start, end] = filter.bedroomsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
bedrooms: {
...where.bedrooms,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
bedrooms: {
...where.bedrooms,
[Op.lte]: end,
},
};
}
}
if (filter.bathroomsRange) {
const [start, end] = filter.bathroomsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
bathrooms: {
...where.bathrooms,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
bathrooms: {
...where.bathrooms,
[Op.lte]: end,
},
};
}
}
if (filter.size_sqmRange) {
const [start, end] = filter.size_sqmRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
size_sqm: {
...where.size_sqm,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
size_sqm: {
...where.size_sqm,
[Op.lte]: end,
},
};
}
}
if (filter.base_nightly_rateRange) {
const [start, end] = filter.base_nightly_rateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
base_nightly_rate: {
...where.base_nightly_rate,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
base_nightly_rate: {
...where.base_nightly_rate,
[Op.lte]: end,
},
};
}
}
if (filter.base_monthly_rateRange) {
const [start, end] = filter.base_monthly_rateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
base_monthly_rate: {
...where.base_monthly_rate,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
base_monthly_rate: {
...where.base_monthly_rate,
[Op.lte]: end,
},
};
}
}
if (filter.minimum_stay_nightsRange) {
const [start, end] = filter.minimum_stay_nightsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
minimum_stay_nights: {
...where.minimum_stay_nights,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
minimum_stay_nights: {
...where.minimum_stay_nights,
[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.units) {
const searchTerms = filter.units.split('|');
include = [
{
model: db.units,
as: 'units_filter',
required: searchTerms.length > 0,
where: searchTerms.length > 0 ? {
[Op.or]: [
{ id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
{
unit_number: {
[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) {
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.unit_types.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(
'unit_types',
'name',
query,
),
],
};
}
const records = await db.unit_types.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,
}));
}
};

638
backend/src/db/api/units.js Normal file
View File

@ -0,0 +1,638 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class UnitsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const units = await db.units.create(
{
id: data.id || undefined,
unit_number: data.unit_number
||
null
,
floor: data.floor
||
null
,
status: data.status
||
null
,
max_occupancy_override: data.max_occupancy_override
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await units.setProperty( data.property || null, {
transaction,
});
await units.setUnit_type( data.unit_type || null, {
transaction,
});
await units.setOrganizations( data.organizations || null, {
transaction,
});
await units.setAvailability_blocks(data.availability_blocks || [], {
transaction,
});
return units;
}
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 unitsData = data.map((item, index) => ({
id: item.id || undefined,
unit_number: item.unit_number
||
null
,
floor: item.floor
||
null
,
status: item.status
||
null
,
max_occupancy_override: item.max_occupancy_override
||
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 units = await db.units.bulkCreate(unitsData, { transaction });
// For each item created, replace relation files
return units;
}
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 units = await db.units.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.unit_number !== undefined) updatePayload.unit_number = data.unit_number;
if (data.floor !== undefined) updatePayload.floor = data.floor;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.max_occupancy_override !== undefined) updatePayload.max_occupancy_override = data.max_occupancy_override;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await units.update(updatePayload, {transaction});
if (data.property !== undefined) {
await units.setProperty(
data.property,
{ transaction }
);
}
if (data.unit_type !== undefined) {
await units.setUnit_type(
data.unit_type,
{ transaction }
);
}
if (data.organizations !== undefined) {
await units.setOrganizations(
data.organizations,
{ transaction }
);
}
if (data.availability_blocks !== undefined) {
await units.setAvailability_blocks(data.availability_blocks, { transaction });
}
return units;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const units = await db.units.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of units) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of units) {
await record.destroy({transaction});
}
});
return units;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const units = await db.units.findByPk(id, options);
await units.update({
deletedBy: currentUser.id
}, {
transaction,
});
await units.destroy({
transaction
});
return units;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const units = await db.units.findOne(
{ where },
{ transaction },
);
if (!units) {
return units;
}
const output = units.get({plain: true});
output.unit_availability_blocks_unit = await units.getUnit_availability_blocks_unit({
transaction
});
output.reservations_unit = await units.getReservations_unit({
transaction
});
output.property = await units.getProperty({
transaction
});
output.unit_type = await units.getUnit_type({
transaction
});
output.availability_blocks = await units.getAvailability_blocks({
transaction
});
output.organizations = await units.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.properties,
as: 'property',
where: filter.property ? {
[Op.or]: [
{ id: { [Op.in]: filter.property.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.property.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.unit_types,
as: 'unit_type',
where: filter.unit_type ? {
[Op.or]: [
{ id: { [Op.in]: filter.unit_type.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.unit_type.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.unit_availability_blocks,
as: 'availability_blocks',
required: false,
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.unit_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'units',
'unit_number',
filter.unit_number,
),
};
}
if (filter.floor) {
where = {
...where,
[Op.and]: Utils.ilike(
'units',
'floor',
filter.floor,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'units',
'notes',
filter.notes,
),
};
}
if (filter.max_occupancy_overrideRange) {
const [start, end] = filter.max_occupancy_overrideRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
max_occupancy_override: {
...where.max_occupancy_override,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
max_occupancy_override: {
...where.max_occupancy_override,
[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.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.availability_blocks) {
const searchTerms = filter.availability_blocks.split('|');
include = [
{
model: db.unit_availability_blocks,
as: 'availability_blocks_filter',
required: searchTerms.length > 0,
where: searchTerms.length > 0 ? {
[Op.or]: [
{ id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
{
reason: {
[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) {
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.units.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(
'units',
'unit_number',
query,
),
],
};
}
const records = await db.units.findAll({
attributes: [ 'id', 'unit_number' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['unit_number', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.unit_number,
}));
}
};

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

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,33 @@
module.exports = {
production: {
dialect: 'postgres',
username: process.env.DB_USER,
password: process.env.DB_PASS,
database: process.env.DB_NAME,
host: process.env.DB_HOST,
port: process.env.DB_PORT,
logging: console.log,
seederStorage: 'sequelize',
},
development: {
username: 'postgres',
dialect: 'postgres',
password: '',
database: 'db_gracey_corporate_stay_portal',
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,173 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const activity_comments = sequelize.define(
'activity_comments',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
visibility: {
type: DataTypes.ENUM,
values: [
"internal",
"external"
],
},
body: {
type: DataTypes.TEXT,
},
posted_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
activity_comments.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.activity_comments.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.activity_comments.belongsTo(db.organizations, {
as: 'organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.activity_comments.belongsTo(db.users, {
as: 'author',
foreignKey: {
name: 'authorId',
},
constraints: false,
});
db.activity_comments.belongsTo(db.booking_requests, {
as: 'booking_request',
foreignKey: {
name: 'booking_requestId',
},
constraints: false,
});
db.activity_comments.belongsTo(db.reservations, {
as: 'reservation',
foreignKey: {
name: 'reservationId',
},
constraints: false,
});
db.activity_comments.belongsTo(db.service_requests, {
as: 'service_request',
foreignKey: {
name: 'service_requestId',
},
constraints: false,
});
db.activity_comments.belongsTo(db.invoices, {
as: 'invoice',
foreignKey: {
name: 'invoiceId',
},
constraints: false,
});
db.activity_comments.belongsTo(db.users, {
as: 'createdBy',
});
db.activity_comments.belongsTo(db.users, {
as: 'updatedBy',
});
};
return activity_comments;
};

View File

@ -0,0 +1,117 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const amenities = sequelize.define(
'amenities',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
description: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
amenities.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.amenities.belongsTo(db.properties, {
as: 'property',
foreignKey: {
name: 'propertyId',
},
constraints: false,
});
db.amenities.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.amenities.belongsTo(db.users, {
as: 'createdBy',
});
db.amenities.belongsTo(db.users, {
as: 'updatedBy',
});
};
return amenities;
};

View File

@ -0,0 +1,157 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const approval_steps = sequelize.define(
'approval_steps',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
step_order: {
type: DataTypes.INTEGER,
},
decision: {
type: DataTypes.ENUM,
values: [
"pending",
"approved",
"rejected",
"changes_requested",
"skipped"
],
},
decided_at: {
type: DataTypes.DATE,
},
decision_notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
approval_steps.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.approval_steps.belongsTo(db.booking_requests, {
as: 'booking_request',
foreignKey: {
name: 'booking_requestId',
},
constraints: false,
});
db.approval_steps.belongsTo(db.users, {
as: 'approver',
foreignKey: {
name: 'approverId',
},
constraints: false,
});
db.approval_steps.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.approval_steps.belongsTo(db.users, {
as: 'createdBy',
});
db.approval_steps.belongsTo(db.users, {
as: 'updatedBy',
});
};
return approval_steps;
};

View File

@ -0,0 +1,160 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const audit_logs = sequelize.define(
'audit_logs',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
action: {
type: DataTypes.TEXT,
},
entity_name: {
type: DataTypes.TEXT,
},
entity_reference: {
type: DataTypes.TEXT,
},
ip_address: {
type: DataTypes.TEXT,
},
user_agent: {
type: DataTypes.TEXT,
},
occurred_at: {
type: DataTypes.DATE,
},
metadata_json: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
audit_logs.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.audit_logs.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.audit_logs.belongsTo(db.users, {
as: 'actor',
foreignKey: {
name: 'actorId',
},
constraints: false,
});
db.audit_logs.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.audit_logs.belongsTo(db.users, {
as: 'createdBy',
});
db.audit_logs.belongsTo(db.users, {
as: 'updatedBy',
});
};
return audit_logs;
};

View File

@ -0,0 +1,162 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const booking_request_travelers = sequelize.define(
'booking_request_travelers',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
full_name: {
type: DataTypes.TEXT,
},
email: {
type: DataTypes.TEXT,
},
phone: {
type: DataTypes.TEXT,
},
nationality: {
type: DataTypes.TEXT,
},
passport_number: {
type: DataTypes.TEXT,
},
date_of_birth: {
type: DataTypes.DATE,
},
primary_traveler: {
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,
},
);
booking_request_travelers.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.booking_request_travelers.belongsTo(db.booking_requests, {
as: 'booking_request',
foreignKey: {
name: 'booking_requestId',
},
constraints: false,
});
db.booking_request_travelers.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.booking_request_travelers.belongsTo(db.users, {
as: 'createdBy',
});
db.booking_request_travelers.belongsTo(db.users, {
as: 'updatedBy',
});
};
return booking_request_travelers;
};

View File

@ -0,0 +1,346 @@
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 booking_requests = sequelize.define(
'booking_requests',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
request_code: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"draft",
"submitted",
"in_review",
"changes_requested",
"approved",
"rejected",
"expired",
"converted_to_reservation",
"canceled"
],
},
check_in_at: {
type: DataTypes.DATE,
},
check_out_at: {
type: DataTypes.DATE,
},
preferred_bedrooms: {
type: DataTypes.INTEGER,
},
guest_count: {
type: DataTypes.INTEGER,
},
purpose_of_stay: {
type: DataTypes.TEXT,
},
special_requirements: {
type: DataTypes.TEXT,
},
budget_code: {
type: DataTypes.TEXT,
},
max_budget_amount: {
type: DataTypes.DECIMAL,
},
currency: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
booking_requests.associate = (db) => {
db.booking_requests.belongsToMany(db.booking_request_travelers, {
as: 'travelers',
foreignKey: {
name: 'booking_requests_travelersId',
},
constraints: false,
through: 'booking_requestsTravelersBooking_request_travelers',
});
db.booking_requests.belongsToMany(db.booking_request_travelers, {
as: 'travelers_filter',
foreignKey: {
name: 'booking_requests_travelersId',
},
constraints: false,
through: 'booking_requestsTravelersBooking_request_travelers',
});
db.booking_requests.belongsToMany(db.approval_steps, {
as: 'approval_steps',
foreignKey: {
name: 'booking_requests_approval_stepsId',
},
constraints: false,
through: 'booking_requestsApproval_stepsApproval_steps',
});
db.booking_requests.belongsToMany(db.approval_steps, {
as: 'approval_steps_filter',
foreignKey: {
name: 'booking_requests_approval_stepsId',
},
constraints: false,
through: 'booking_requestsApproval_stepsApproval_steps',
});
db.booking_requests.belongsToMany(db.documents, {
as: 'documents',
foreignKey: {
name: 'booking_requests_documentsId',
},
constraints: false,
through: 'booking_requestsDocumentsDocuments',
});
db.booking_requests.belongsToMany(db.documents, {
as: 'documents_filter',
foreignKey: {
name: 'booking_requests_documentsId',
},
constraints: false,
through: 'booking_requestsDocumentsDocuments',
});
db.booking_requests.belongsToMany(db.activity_comments, {
as: 'comments',
foreignKey: {
name: 'booking_requests_commentsId',
},
constraints: false,
through: 'booking_requestsCommentsActivity_comments',
});
db.booking_requests.belongsToMany(db.activity_comments, {
as: 'comments_filter',
foreignKey: {
name: 'booking_requests_commentsId',
},
constraints: false,
through: 'booking_requestsCommentsActivity_comments',
});
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.booking_requests.hasMany(db.booking_request_travelers, {
as: 'booking_request_travelers_booking_request',
foreignKey: {
name: 'booking_requestId',
},
constraints: false,
});
db.booking_requests.hasMany(db.approval_steps, {
as: 'approval_steps_booking_request',
foreignKey: {
name: 'booking_requestId',
},
constraints: false,
});
db.booking_requests.hasMany(db.reservations, {
as: 'reservations_booking_request',
foreignKey: {
name: 'booking_requestId',
},
constraints: false,
});
db.booking_requests.hasMany(db.documents, {
as: 'documents_booking_request',
foreignKey: {
name: 'booking_requestId',
},
constraints: false,
});
db.booking_requests.hasMany(db.activity_comments, {
as: 'activity_comments_booking_request',
foreignKey: {
name: 'booking_requestId',
},
constraints: false,
});
//end loop
db.booking_requests.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.booking_requests.belongsTo(db.organizations, {
as: 'organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.booking_requests.belongsTo(db.users, {
as: 'requested_by',
foreignKey: {
name: 'requested_byId',
},
constraints: false,
});
db.booking_requests.belongsTo(db.properties, {
as: 'preferred_property',
foreignKey: {
name: 'preferred_propertyId',
},
constraints: false,
});
db.booking_requests.belongsTo(db.unit_types, {
as: 'preferred_unit_type',
foreignKey: {
name: 'preferred_unit_typeId',
},
constraints: false,
});
db.booking_requests.belongsTo(db.users, {
as: 'createdBy',
});
db.booking_requests.belongsTo(db.users, {
as: 'updatedBy',
});
};
return booking_requests;
};

View File

@ -0,0 +1,149 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const checklist_items = sequelize.define(
'checklist_items',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
title: {
type: DataTypes.TEXT,
},
is_done: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
done_at: {
type: DataTypes.DATE,
},
sort_order: {
type: DataTypes.INTEGER,
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
checklist_items.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.checklist_items.belongsTo(db.checklists, {
as: 'checklist',
foreignKey: {
name: 'checklistId',
},
constraints: false,
});
db.checklist_items.belongsTo(db.users, {
as: 'done_by',
foreignKey: {
name: 'done_byId',
},
constraints: false,
});
db.checklist_items.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.checklist_items.belongsTo(db.users, {
as: 'createdBy',
});
db.checklist_items.belongsTo(db.users, {
as: 'updatedBy',
});
};
return checklist_items;
};

View File

@ -0,0 +1,210 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const checklists = sequelize.define(
'checklists',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
checklist_type: {
type: DataTypes.ENUM,
values: [
"pre_arrival",
"check_in",
"check_out",
"turnover"
],
},
status: {
type: DataTypes.ENUM,
values: [
"not_started",
"in_progress",
"completed",
"blocked"
],
},
due_at: {
type: DataTypes.DATE,
},
completed_at: {
type: DataTypes.DATE,
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
checklists.associate = (db) => {
db.checklists.belongsToMany(db.checklist_items, {
as: 'items',
foreignKey: {
name: 'checklists_itemsId',
},
constraints: false,
through: 'checklistsItemsChecklist_items',
});
db.checklists.belongsToMany(db.checklist_items, {
as: 'items_filter',
foreignKey: {
name: 'checklists_itemsId',
},
constraints: false,
through: 'checklistsItemsChecklist_items',
});
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.checklists.hasMany(db.checklist_items, {
as: 'checklist_items_checklist',
foreignKey: {
name: 'checklistId',
},
constraints: false,
});
//end loop
db.checklists.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.checklists.belongsTo(db.reservations, {
as: 'reservation',
foreignKey: {
name: 'reservationId',
},
constraints: false,
});
db.checklists.belongsTo(db.users, {
as: 'assigned_to',
foreignKey: {
name: 'assigned_toId',
},
constraints: false,
});
db.checklists.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.checklists.belongsTo(db.users, {
as: 'createdBy',
});
db.checklists.belongsTo(db.users, {
as: 'updatedBy',
});
};
return checklists;
};

View File

@ -0,0 +1,229 @@
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 documents = sequelize.define(
'documents',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
document_type: {
type: DataTypes.ENUM,
values: [
"invoice_pdf",
"guest_id",
"contract",
"approval_attachment",
"arrival_instructions",
"checklist",
"inspection_report",
"other"
],
},
file_name: {
type: DataTypes.TEXT,
},
mime_type: {
type: DataTypes.TEXT,
},
file_size_bytes: {
type: DataTypes.INTEGER,
},
storage_key: {
type: DataTypes.TEXT,
},
public_url: {
type: DataTypes.TEXT,
},
notes: {
type: DataTypes.TEXT,
},
is_private: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
documents.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.documents.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.documents.belongsTo(db.users, {
as: 'uploaded_by',
foreignKey: {
name: 'uploaded_byId',
},
constraints: false,
});
db.documents.belongsTo(db.organizations, {
as: 'organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.documents.belongsTo(db.booking_requests, {
as: 'booking_request',
foreignKey: {
name: 'booking_requestId',
},
constraints: false,
});
db.documents.belongsTo(db.reservations, {
as: 'reservation',
foreignKey: {
name: 'reservationId',
},
constraints: false,
});
db.documents.belongsTo(db.service_requests, {
as: 'service_request',
foreignKey: {
name: 'service_requestId',
},
constraints: false,
});
db.documents.belongsTo(db.invoices, {
as: 'invoice',
foreignKey: {
name: 'invoiceId',
},
constraints: false,
});
db.documents.belongsTo(db.users, {
as: 'createdBy',
});
db.documents.belongsTo(db.users, {
as: 'updatedBy',
});
};
return documents;
};

View File

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

View File

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

View File

@ -0,0 +1,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 invoice_line_items = sequelize.define(
'invoice_line_items',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
line_type: {
type: DataTypes.ENUM,
values: [
"accommodation",
"transport",
"cleaning",
"add_on",
"damage",
"fee",
"discount",
"tax_adjustment"
],
},
description: {
type: DataTypes.TEXT,
},
quantity: {
type: DataTypes.INTEGER,
},
unit_price: {
type: DataTypes.DECIMAL,
},
amount: {
type: DataTypes.DECIMAL,
},
service_period: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
invoice_line_items.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.invoice_line_items.belongsTo(db.invoices, {
as: 'invoice',
foreignKey: {
name: 'invoiceId',
},
constraints: false,
});
db.invoice_line_items.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.invoice_line_items.belongsTo(db.users, {
as: 'createdBy',
});
db.invoice_line_items.belongsTo(db.users, {
as: 'updatedBy',
});
};
return invoice_line_items;
};

View File

@ -0,0 +1,312 @@
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 invoices = sequelize.define(
'invoices',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
invoice_number: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"draft",
"issued",
"overdue",
"paid",
"partially_paid",
"void"
],
},
issued_at: {
type: DataTypes.DATE,
},
due_at: {
type: DataTypes.DATE,
},
subtotal_amount: {
type: DataTypes.DECIMAL,
},
tax_amount: {
type: DataTypes.DECIMAL,
},
total_amount: {
type: DataTypes.DECIMAL,
},
balance_due: {
type: DataTypes.DECIMAL,
},
currency: {
type: DataTypes.TEXT,
},
bill_to_name: {
type: DataTypes.TEXT,
},
bill_to_address: {
type: DataTypes.TEXT,
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
invoices.associate = (db) => {
db.invoices.belongsToMany(db.invoice_line_items, {
as: 'line_items',
foreignKey: {
name: 'invoices_line_itemsId',
},
constraints: false,
through: 'invoicesLine_itemsInvoice_line_items',
});
db.invoices.belongsToMany(db.invoice_line_items, {
as: 'line_items_filter',
foreignKey: {
name: 'invoices_line_itemsId',
},
constraints: false,
through: 'invoicesLine_itemsInvoice_line_items',
});
db.invoices.belongsToMany(db.payments, {
as: 'payments',
foreignKey: {
name: 'invoices_paymentsId',
},
constraints: false,
through: 'invoicesPaymentsPayments',
});
db.invoices.belongsToMany(db.payments, {
as: 'payments_filter',
foreignKey: {
name: 'invoices_paymentsId',
},
constraints: false,
through: 'invoicesPaymentsPayments',
});
db.invoices.belongsToMany(db.documents, {
as: 'documents',
foreignKey: {
name: 'invoices_documentsId',
},
constraints: false,
through: 'invoicesDocumentsDocuments',
});
db.invoices.belongsToMany(db.documents, {
as: 'documents_filter',
foreignKey: {
name: 'invoices_documentsId',
},
constraints: false,
through: 'invoicesDocumentsDocuments',
});
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.invoices.hasMany(db.invoice_line_items, {
as: 'invoice_line_items_invoice',
foreignKey: {
name: 'invoiceId',
},
constraints: false,
});
db.invoices.hasMany(db.payments, {
as: 'payments_invoice',
foreignKey: {
name: 'invoiceId',
},
constraints: false,
});
db.invoices.hasMany(db.documents, {
as: 'documents_invoice',
foreignKey: {
name: 'invoiceId',
},
constraints: false,
});
db.invoices.hasMany(db.activity_comments, {
as: 'activity_comments_invoice',
foreignKey: {
name: 'invoiceId',
},
constraints: false,
});
//end loop
db.invoices.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.invoices.belongsTo(db.organizations, {
as: 'organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.invoices.belongsTo(db.reservations, {
as: 'reservation',
foreignKey: {
name: 'reservationId',
},
constraints: false,
});
db.invoices.hasMany(db.file, {
as: 'pdf_file',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.invoices.getTableName(),
belongsToColumn: 'pdf_file',
},
});
db.invoices.belongsTo(db.users, {
as: 'createdBy',
});
db.invoices.belongsTo(db.users, {
as: 'updatedBy',
});
};
return invoices;
};

View File

@ -0,0 +1,198 @@
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 job_runs = sequelize.define(
'job_runs',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
job_type: {
type: DataTypes.ENUM,
values: [
"approval_reminder",
"upcoming_check_in_reminder",
"overdue_invoice_notice",
"upcoming_check_out_reminder",
"daily_digest",
"system_cleanup"
],
},
status: {
type: DataTypes.ENUM,
values: [
"queued",
"running",
"succeeded",
"failed",
"canceled"
],
},
scheduled_for: {
type: DataTypes.DATE,
},
started_at: {
type: DataTypes.DATE,
},
finished_at: {
type: DataTypes.DATE,
},
attempt_count: {
type: DataTypes.INTEGER,
},
last_error: {
type: DataTypes.TEXT,
},
payload_json: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
job_runs.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.job_runs.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.job_runs.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.job_runs.belongsTo(db.users, {
as: 'createdBy',
});
db.job_runs.belongsTo(db.users, {
as: 'updatedBy',
});
};
return job_runs;
};

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 negotiated_rates = sequelize.define(
'negotiated_rates',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
rate_type: {
type: DataTypes.ENUM,
values: [
"nightly",
"monthly"
],
},
rate_amount: {
type: DataTypes.DECIMAL,
},
valid_from: {
type: DataTypes.DATE,
},
valid_until: {
type: DataTypes.DATE,
},
minimum_stay_nights: {
type: DataTypes.INTEGER,
},
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,
},
);
negotiated_rates.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.negotiated_rates.belongsTo(db.organizations, {
as: 'organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.negotiated_rates.belongsTo(db.properties, {
as: 'property',
foreignKey: {
name: 'propertyId',
},
constraints: false,
});
db.negotiated_rates.belongsTo(db.unit_types, {
as: 'unit_type',
foreignKey: {
name: 'unit_typeId',
},
constraints: false,
});
db.negotiated_rates.belongsTo(db.users, {
as: 'createdBy',
});
db.negotiated_rates.belongsTo(db.users, {
as: 'updatedBy',
});
};
return negotiated_rates;
};

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 notifications = sequelize.define(
'notifications',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
channel: {
type: DataTypes.ENUM,
values: [
"in_app",
"email"
],
},
type: {
type: DataTypes.ENUM,
values: [
"approval_required",
"approval_decision",
"reservation_confirmed",
"upcoming_check_in",
"upcoming_check_out",
"invoice_issued",
"invoice_overdue",
"service_request_update",
"comment_mention",
"system"
],
},
title: {
type: DataTypes.TEXT,
},
body: {
type: DataTypes.TEXT,
},
link_url: {
type: DataTypes.TEXT,
},
sent_at: {
type: DataTypes.DATE,
},
read_at: {
type: DataTypes.DATE,
},
is_read: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
notifications.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.notifications.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.notifications.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.notifications.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.notifications.belongsTo(db.users, {
as: 'createdBy',
});
db.notifications.belongsTo(db.users, {
as: 'updatedBy',
});
};
return notifications;
};

View File

@ -0,0 +1,171 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const organization_memberships = sequelize.define(
'organization_memberships',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
member_role: {
type: DataTypes.ENUM,
values: [
"corporate_admin",
"corporate_booker",
"approver",
"traveler",
"internal_reservations",
"internal_concierge",
"internal_finance",
"super_admin"
],
},
is_primary: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
job_title: {
type: DataTypes.TEXT,
},
phone: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
organization_memberships.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.organization_memberships.belongsTo(db.organizations, {
as: 'organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.organization_memberships.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.organization_memberships.belongsTo(db.users, {
as: 'createdBy',
});
db.organization_memberships.belongsTo(db.users, {
as: 'updatedBy',
});
};
return organization_memberships;
};

View File

@ -0,0 +1,294 @@
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.role_assignments, {
as: 'role_assignments_organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.organizations.hasMany(db.organization_memberships, {
as: 'organization_memberships_organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.organizations.hasMany(db.properties, {
as: 'properties_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.amenities, {
as: 'amenities_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.unit_types, {
as: 'unit_types_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.units, {
as: 'units_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.unit_availability_blocks, {
as: 'unit_availability_blocks_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.negotiated_rates, {
as: 'negotiated_rates_organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.organizations.hasMany(db.booking_requests, {
as: 'booking_requests_organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.organizations.hasMany(db.booking_request_travelers, {
as: 'booking_request_travelers_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.approval_steps, {
as: 'approval_steps_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.reservations, {
as: 'reservations_organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.organizations.hasMany(db.reservation_guests, {
as: 'reservation_guests_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.service_requests, {
as: 'service_requests_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.invoices, {
as: 'invoices_organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.organizations.hasMany(db.invoice_line_items, {
as: 'invoice_line_items_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.payments, {
as: 'payments_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.documents, {
as: 'documents_organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.organizations.hasMany(db.audit_logs, {
as: 'audit_logs_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.notifications, {
as: 'notifications_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.activity_comments, {
as: 'activity_comments_organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.organizations.hasMany(db.checklists, {
as: 'checklists_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.checklist_items, {
as: 'checklist_items_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.job_runs, {
as: 'job_runs_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,198 @@
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 payments = sequelize.define(
'payments',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
payment_method: {
type: DataTypes.ENUM,
values: [
"bank_transfer",
"card",
"cash",
"check",
"credit_note",
"other"
],
},
status: {
type: DataTypes.ENUM,
values: [
"pending",
"completed",
"failed",
"reversed"
],
},
amount: {
type: DataTypes.DECIMAL,
},
currency: {
type: DataTypes.TEXT,
},
paid_at: {
type: DataTypes.DATE,
},
reference: {
type: DataTypes.TEXT,
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
payments.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.payments.belongsTo(db.invoices, {
as: 'invoice',
foreignKey: {
name: 'invoiceId',
},
constraints: false,
});
db.payments.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.payments.hasMany(db.file, {
as: 'receipt_file',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.payments.getTableName(),
belongsToColumn: 'receipt_file',
},
});
db.payments.belongsTo(db.users, {
as: 'createdBy',
});
db.payments.belongsTo(db.users, {
as: 'updatedBy',
});
};
return payments;
};

View File

@ -0,0 +1,94 @@
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,274 @@
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 properties = sequelize.define(
'properties',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
code: {
type: DataTypes.TEXT,
},
address: {
type: DataTypes.TEXT,
},
city: {
type: DataTypes.TEXT,
},
country: {
type: DataTypes.TEXT,
},
timezone: {
type: DataTypes.TEXT,
},
description: {
type: DataTypes.TEXT,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
properties.associate = (db) => {
db.properties.belongsToMany(db.unit_types, {
as: 'unit_types',
foreignKey: {
name: 'properties_unit_typesId',
},
constraints: false,
through: 'propertiesUnit_typesUnit_types',
});
db.properties.belongsToMany(db.unit_types, {
as: 'unit_types_filter',
foreignKey: {
name: 'properties_unit_typesId',
},
constraints: false,
through: 'propertiesUnit_typesUnit_types',
});
db.properties.belongsToMany(db.units, {
as: 'units',
foreignKey: {
name: 'properties_unitsId',
},
constraints: false,
through: 'propertiesUnitsUnits',
});
db.properties.belongsToMany(db.units, {
as: 'units_filter',
foreignKey: {
name: 'properties_unitsId',
},
constraints: false,
through: 'propertiesUnitsUnits',
});
db.properties.belongsToMany(db.amenities, {
as: 'amenities',
foreignKey: {
name: 'properties_amenitiesId',
},
constraints: false,
through: 'propertiesAmenitiesAmenities',
});
db.properties.belongsToMany(db.amenities, {
as: 'amenities_filter',
foreignKey: {
name: 'properties_amenitiesId',
},
constraints: false,
through: 'propertiesAmenitiesAmenities',
});
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.properties.hasMany(db.amenities, {
as: 'amenities_property',
foreignKey: {
name: 'propertyId',
},
constraints: false,
});
db.properties.hasMany(db.unit_types, {
as: 'unit_types_property',
foreignKey: {
name: 'propertyId',
},
constraints: false,
});
db.properties.hasMany(db.units, {
as: 'units_property',
foreignKey: {
name: 'propertyId',
},
constraints: false,
});
db.properties.hasMany(db.negotiated_rates, {
as: 'negotiated_rates_property',
foreignKey: {
name: 'propertyId',
},
constraints: false,
});
db.properties.hasMany(db.booking_requests, {
as: 'booking_requests_preferred_property',
foreignKey: {
name: 'preferred_propertyId',
},
constraints: false,
});
db.properties.hasMany(db.reservations, {
as: 'reservations_property',
foreignKey: {
name: 'propertyId',
},
constraints: false,
});
//end loop
db.properties.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.properties.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.properties.hasMany(db.file, {
as: 'images',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.properties.getTableName(),
belongsToColumn: 'images',
},
});
db.properties.belongsTo(db.users, {
as: 'createdBy',
});
db.properties.belongsTo(db.users, {
as: 'updatedBy',
});
};
return properties;
};

View File

@ -0,0 +1,166 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const reservation_guests = sequelize.define(
'reservation_guests',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
full_name: {
type: DataTypes.TEXT,
},
email: {
type: DataTypes.TEXT,
},
phone: {
type: DataTypes.TEXT,
},
guest_type: {
type: DataTypes.ENUM,
values: [
"traveler",
"additional_guest",
"vip",
"driver",
"security"
],
},
primary_guest: {
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,
},
);
reservation_guests.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.reservation_guests.belongsTo(db.reservations, {
as: 'reservation',
foreignKey: {
name: 'reservationId',
},
constraints: false,
});
db.reservation_guests.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.reservation_guests.belongsTo(db.users, {
as: 'createdBy',
});
db.reservation_guests.belongsTo(db.users, {
as: 'updatedBy',
});
};
return reservation_guests;
};

View File

@ -0,0 +1,406 @@
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 reservations = sequelize.define(
'reservations',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
reservation_code: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"quoted",
"confirmed",
"checked_in",
"checked_out",
"canceled",
"no_show"
],
},
check_in_at: {
type: DataTypes.DATE,
},
check_out_at: {
type: DataTypes.DATE,
},
actual_check_in_at: {
type: DataTypes.DATE,
},
actual_check_out_at: {
type: DataTypes.DATE,
},
early_check_in: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
late_check_out: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
guest_count: {
type: DataTypes.INTEGER,
},
nightly_rate: {
type: DataTypes.DECIMAL,
},
monthly_rate: {
type: DataTypes.DECIMAL,
},
currency: {
type: DataTypes.TEXT,
},
internal_notes: {
type: DataTypes.TEXT,
},
external_notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
reservations.associate = (db) => {
db.reservations.belongsToMany(db.reservation_guests, {
as: 'guests',
foreignKey: {
name: 'reservations_guestsId',
},
constraints: false,
through: 'reservationsGuestsReservation_guests',
});
db.reservations.belongsToMany(db.reservation_guests, {
as: 'guests_filter',
foreignKey: {
name: 'reservations_guestsId',
},
constraints: false,
through: 'reservationsGuestsReservation_guests',
});
db.reservations.belongsToMany(db.service_requests, {
as: 'service_requests',
foreignKey: {
name: 'reservations_service_requestsId',
},
constraints: false,
through: 'reservationsService_requestsService_requests',
});
db.reservations.belongsToMany(db.service_requests, {
as: 'service_requests_filter',
foreignKey: {
name: 'reservations_service_requestsId',
},
constraints: false,
through: 'reservationsService_requestsService_requests',
});
db.reservations.belongsToMany(db.invoices, {
as: 'invoices',
foreignKey: {
name: 'reservations_invoicesId',
},
constraints: false,
through: 'reservationsInvoicesInvoices',
});
db.reservations.belongsToMany(db.invoices, {
as: 'invoices_filter',
foreignKey: {
name: 'reservations_invoicesId',
},
constraints: false,
through: 'reservationsInvoicesInvoices',
});
db.reservations.belongsToMany(db.documents, {
as: 'documents',
foreignKey: {
name: 'reservations_documentsId',
},
constraints: false,
through: 'reservationsDocumentsDocuments',
});
db.reservations.belongsToMany(db.documents, {
as: 'documents_filter',
foreignKey: {
name: 'reservations_documentsId',
},
constraints: false,
through: 'reservationsDocumentsDocuments',
});
db.reservations.belongsToMany(db.activity_comments, {
as: 'comments',
foreignKey: {
name: 'reservations_commentsId',
},
constraints: false,
through: 'reservationsCommentsActivity_comments',
});
db.reservations.belongsToMany(db.activity_comments, {
as: 'comments_filter',
foreignKey: {
name: 'reservations_commentsId',
},
constraints: false,
through: 'reservationsCommentsActivity_comments',
});
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.reservations.hasMany(db.unit_availability_blocks, {
as: 'unit_availability_blocks_reservation',
foreignKey: {
name: 'reservationId',
},
constraints: false,
});
db.reservations.hasMany(db.reservation_guests, {
as: 'reservation_guests_reservation',
foreignKey: {
name: 'reservationId',
},
constraints: false,
});
db.reservations.hasMany(db.service_requests, {
as: 'service_requests_reservation',
foreignKey: {
name: 'reservationId',
},
constraints: false,
});
db.reservations.hasMany(db.invoices, {
as: 'invoices_reservation',
foreignKey: {
name: 'reservationId',
},
constraints: false,
});
db.reservations.hasMany(db.documents, {
as: 'documents_reservation',
foreignKey: {
name: 'reservationId',
},
constraints: false,
});
db.reservations.hasMany(db.activity_comments, {
as: 'activity_comments_reservation',
foreignKey: {
name: 'reservationId',
},
constraints: false,
});
db.reservations.hasMany(db.checklists, {
as: 'checklists_reservation',
foreignKey: {
name: 'reservationId',
},
constraints: false,
});
//end loop
db.reservations.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.reservations.belongsTo(db.organizations, {
as: 'organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.reservations.belongsTo(db.booking_requests, {
as: 'booking_request',
foreignKey: {
name: 'booking_requestId',
},
constraints: false,
});
db.reservations.belongsTo(db.properties, {
as: 'property',
foreignKey: {
name: 'propertyId',
},
constraints: false,
});
db.reservations.belongsTo(db.units, {
as: 'unit',
foreignKey: {
name: 'unitId',
},
constraints: false,
});
db.reservations.belongsTo(db.unit_types, {
as: 'unit_type',
foreignKey: {
name: 'unit_typeId',
},
constraints: false,
});
db.reservations.belongsTo(db.users, {
as: 'createdBy',
});
db.reservations.belongsTo(db.users, {
as: 'updatedBy',
});
};
return reservations;
};

View File

@ -0,0 +1,143 @@
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 role_assignments = sequelize.define(
'role_assignments',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
effective_from: {
type: DataTypes.DATE,
},
effective_until: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
role_assignments.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.role_assignments.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.role_assignments.belongsTo(db.roles, {
as: 'role',
foreignKey: {
name: 'roleId',
},
constraints: false,
});
db.role_assignments.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.role_assignments.belongsTo(db.organizations, {
as: 'organization',
foreignKey: {
name: 'organizationId',
},
constraints: false,
});
db.role_assignments.belongsTo(db.users, {
as: 'createdBy',
});
db.role_assignments.belongsTo(db.users, {
as: 'updatedBy',
});
};
return role_assignments;
};

View File

@ -0,0 +1,145 @@
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,
});
db.roles.hasMany(db.role_assignments, {
as: 'role_assignments_role',
foreignKey: {
name: '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,322 @@
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 service_requests = sequelize.define(
'service_requests',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
request_type: {
type: DataTypes.ENUM,
values: [
"airport_pickup",
"housekeeping",
"maintenance",
"stocked_fridge",
"chauffeur",
"late_checkout",
"extension",
"custom_service"
],
},
status: {
type: DataTypes.ENUM,
values: [
"new",
"triaged",
"in_progress",
"scheduled",
"waiting_on_guest",
"completed",
"canceled"
],
},
priority: {
type: DataTypes.ENUM,
values: [
"low",
"normal",
"high",
"urgent"
],
},
requested_at: {
type: DataTypes.DATE,
},
due_at: {
type: DataTypes.DATE,
},
completed_at: {
type: DataTypes.DATE,
},
summary: {
type: DataTypes.TEXT,
},
details: {
type: DataTypes.TEXT,
},
estimated_cost: {
type: DataTypes.DECIMAL,
},
actual_cost: {
type: DataTypes.DECIMAL,
},
currency: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
service_requests.associate = (db) => {
db.service_requests.belongsToMany(db.documents, {
as: 'documents',
foreignKey: {
name: 'service_requests_documentsId',
},
constraints: false,
through: 'service_requestsDocumentsDocuments',
});
db.service_requests.belongsToMany(db.documents, {
as: 'documents_filter',
foreignKey: {
name: 'service_requests_documentsId',
},
constraints: false,
through: 'service_requestsDocumentsDocuments',
});
db.service_requests.belongsToMany(db.activity_comments, {
as: 'comments',
foreignKey: {
name: 'service_requests_commentsId',
},
constraints: false,
through: 'service_requestsCommentsActivity_comments',
});
db.service_requests.belongsToMany(db.activity_comments, {
as: 'comments_filter',
foreignKey: {
name: 'service_requests_commentsId',
},
constraints: false,
through: 'service_requestsCommentsActivity_comments',
});
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.service_requests.hasMany(db.documents, {
as: 'documents_service_request',
foreignKey: {
name: 'service_requestId',
},
constraints: false,
});
db.service_requests.hasMany(db.activity_comments, {
as: 'activity_comments_service_request',
foreignKey: {
name: 'service_requestId',
},
constraints: false,
});
//end loop
db.service_requests.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.service_requests.belongsTo(db.reservations, {
as: 'reservation',
foreignKey: {
name: 'reservationId',
},
constraints: false,
});
db.service_requests.belongsTo(db.users, {
as: 'requested_by',
foreignKey: {
name: 'requested_byId',
},
constraints: false,
});
db.service_requests.belongsTo(db.users, {
as: 'assigned_to',
foreignKey: {
name: 'assigned_toId',
},
constraints: false,
});
db.service_requests.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.service_requests.belongsTo(db.users, {
as: 'createdBy',
});
db.service_requests.belongsTo(db.users, {
as: 'updatedBy',
});
};
return service_requests;
};

View File

@ -0,0 +1,289 @@
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 tenants = sequelize.define(
'tenants',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
slug: {
type: DataTypes.TEXT,
},
legal_name: {
type: DataTypes.TEXT,
},
primary_domain: {
type: DataTypes.TEXT,
},
timezone: {
type: DataTypes.TEXT,
},
default_currency: {
type: DataTypes.TEXT,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
tenants.associate = (db) => {
db.tenants.belongsToMany(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'tenants_organizationsId',
},
constraints: false,
through: 'tenantsOrganizationsOrganizations',
});
db.tenants.belongsToMany(db.organizations, {
as: 'organizations_filter',
foreignKey: {
name: 'tenants_organizationsId',
},
constraints: false,
through: 'tenantsOrganizationsOrganizations',
});
db.tenants.belongsToMany(db.properties, {
as: 'properties',
foreignKey: {
name: 'tenants_propertiesId',
},
constraints: false,
through: 'tenantsPropertiesProperties',
});
db.tenants.belongsToMany(db.properties, {
as: 'properties_filter',
foreignKey: {
name: 'tenants_propertiesId',
},
constraints: false,
through: 'tenantsPropertiesProperties',
});
db.tenants.belongsToMany(db.audit_logs, {
as: 'audit_logs',
foreignKey: {
name: 'tenants_audit_logsId',
},
constraints: false,
through: 'tenantsAudit_logsAudit_logs',
});
db.tenants.belongsToMany(db.audit_logs, {
as: 'audit_logs_filter',
foreignKey: {
name: 'tenants_audit_logsId',
},
constraints: false,
through: 'tenantsAudit_logsAudit_logs',
});
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.tenants.hasMany(db.role_assignments, {
as: 'role_assignments_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.properties, {
as: 'properties_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.booking_requests, {
as: 'booking_requests_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.reservations, {
as: 'reservations_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.service_requests, {
as: 'service_requests_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.invoices, {
as: 'invoices_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.documents, {
as: 'documents_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.audit_logs, {
as: 'audit_logs_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.notifications, {
as: 'notifications_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.activity_comments, {
as: 'activity_comments_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.checklists, {
as: 'checklists_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.job_runs, {
as: 'job_runs_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
//end loop
db.tenants.belongsTo(db.users, {
as: 'createdBy',
});
db.tenants.belongsTo(db.users, {
as: 'updatedBy',
});
};
return tenants;
};

View File

@ -0,0 +1,154 @@
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 unit_availability_blocks = sequelize.define(
'unit_availability_blocks',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
block_type: {
type: DataTypes.ENUM,
values: [
"blackout",
"maintenance",
"owner_hold",
"reservation_hold"
],
},
start_at: {
type: DataTypes.DATE,
},
end_at: {
type: DataTypes.DATE,
},
reason: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
unit_availability_blocks.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.unit_availability_blocks.belongsTo(db.units, {
as: 'unit',
foreignKey: {
name: 'unitId',
},
constraints: false,
});
db.unit_availability_blocks.belongsTo(db.reservations, {
as: 'reservation',
foreignKey: {
name: 'reservationId',
},
constraints: false,
});
db.unit_availability_blocks.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.unit_availability_blocks.belongsTo(db.users, {
as: 'createdBy',
});
db.unit_availability_blocks.belongsTo(db.users, {
as: 'updatedBy',
});
};
return unit_availability_blocks;
};

View File

@ -0,0 +1,223 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const unit_types = sequelize.define(
'unit_types',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
code: {
type: DataTypes.TEXT,
},
max_occupancy: {
type: DataTypes.INTEGER,
},
bedrooms: {
type: DataTypes.INTEGER,
},
bathrooms: {
type: DataTypes.INTEGER,
},
size_sqm: {
type: DataTypes.DECIMAL,
},
description: {
type: DataTypes.TEXT,
},
base_nightly_rate: {
type: DataTypes.DECIMAL,
},
base_monthly_rate: {
type: DataTypes.DECIMAL,
},
minimum_stay_nights: {
type: DataTypes.INTEGER,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
unit_types.associate = (db) => {
db.unit_types.belongsToMany(db.units, {
as: 'units',
foreignKey: {
name: 'unit_types_unitsId',
},
constraints: false,
through: 'unit_typesUnitsUnits',
});
db.unit_types.belongsToMany(db.units, {
as: 'units_filter',
foreignKey: {
name: 'unit_types_unitsId',
},
constraints: false,
through: 'unit_typesUnitsUnits',
});
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.unit_types.hasMany(db.units, {
as: 'units_unit_type',
foreignKey: {
name: 'unit_typeId',
},
constraints: false,
});
db.unit_types.hasMany(db.negotiated_rates, {
as: 'negotiated_rates_unit_type',
foreignKey: {
name: 'unit_typeId',
},
constraints: false,
});
db.unit_types.hasMany(db.booking_requests, {
as: 'booking_requests_preferred_unit_type',
foreignKey: {
name: 'preferred_unit_typeId',
},
constraints: false,
});
db.unit_types.hasMany(db.reservations, {
as: 'reservations_unit_type',
foreignKey: {
name: 'unit_typeId',
},
constraints: false,
});
//end loop
db.unit_types.belongsTo(db.properties, {
as: 'property',
foreignKey: {
name: 'propertyId',
},
constraints: false,
});
db.unit_types.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.unit_types.belongsTo(db.users, {
as: 'createdBy',
});
db.unit_types.belongsTo(db.users, {
as: 'updatedBy',
});
};
return unit_types;
};

View File

@ -0,0 +1,201 @@
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 units = sequelize.define(
'units',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
unit_number: {
type: DataTypes.TEXT,
},
floor: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"available",
"occupied",
"maintenance",
"cleaning_hold",
"reserved",
"out_of_service"
],
},
max_occupancy_override: {
type: DataTypes.INTEGER,
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
units.associate = (db) => {
db.units.belongsToMany(db.unit_availability_blocks, {
as: 'availability_blocks',
foreignKey: {
name: 'units_availability_blocksId',
},
constraints: false,
through: 'unitsAvailability_blocksUnit_availability_blocks',
});
db.units.belongsToMany(db.unit_availability_blocks, {
as: 'availability_blocks_filter',
foreignKey: {
name: 'units_availability_blocksId',
},
constraints: false,
through: 'unitsAvailability_blocksUnit_availability_blocks',
});
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.units.hasMany(db.unit_availability_blocks, {
as: 'unit_availability_blocks_unit',
foreignKey: {
name: 'unitId',
},
constraints: false,
});
db.units.hasMany(db.reservations, {
as: 'reservations_unit',
foreignKey: {
name: 'unitId',
},
constraints: false,
});
//end loop
db.units.belongsTo(db.properties, {
as: 'property',
foreignKey: {
name: 'propertyId',
},
constraints: false,
});
db.units.belongsTo(db.unit_types, {
as: 'unit_type',
foreignKey: {
name: 'unit_typeId',
},
constraints: false,
});
db.units.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.units.belongsTo(db.users, {
as: 'createdBy',
});
db.units.belongsTo(db.users, {
as: 'updatedBy',
});
};
return units;
};

View File

@ -0,0 +1,356 @@
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.role_assignments, {
as: 'role_assignments_user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.users.hasMany(db.organization_memberships, {
as: 'organization_memberships_user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.users.hasMany(db.booking_requests, {
as: 'booking_requests_requested_by',
foreignKey: {
name: 'requested_byId',
},
constraints: false,
});
db.users.hasMany(db.approval_steps, {
as: 'approval_steps_approver',
foreignKey: {
name: 'approverId',
},
constraints: false,
});
db.users.hasMany(db.service_requests, {
as: 'service_requests_requested_by',
foreignKey: {
name: 'requested_byId',
},
constraints: false,
});
db.users.hasMany(db.service_requests, {
as: 'service_requests_assigned_to',
foreignKey: {
name: 'assigned_toId',
},
constraints: false,
});
db.users.hasMany(db.documents, {
as: 'documents_uploaded_by',
foreignKey: {
name: 'uploaded_byId',
},
constraints: false,
});
db.users.hasMany(db.audit_logs, {
as: 'audit_logs_actor',
foreignKey: {
name: 'actorId',
},
constraints: false,
});
db.users.hasMany(db.notifications, {
as: 'notifications_user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.users.hasMany(db.activity_comments, {
as: 'activity_comments_author',
foreignKey: {
name: 'authorId',
},
constraints: false,
});
db.users.hasMany(db.checklists, {
as: 'checklists_assigned_to',
foreignKey: {
name: 'assigned_toId',
},
constraints: false,
});
db.users.hasMany(db.checklist_items, {
as: 'checklist_items_done_by',
foreignKey: {
name: 'done_byId',
},
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;
}

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

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

@ -0,0 +1,247 @@
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 tenantsRoutes = require('./routes/tenants');
const role_assignmentsRoutes = require('./routes/role_assignments');
const organization_membershipsRoutes = require('./routes/organization_memberships');
const propertiesRoutes = require('./routes/properties');
const amenitiesRoutes = require('./routes/amenities');
const unit_typesRoutes = require('./routes/unit_types');
const unitsRoutes = require('./routes/units');
const unit_availability_blocksRoutes = require('./routes/unit_availability_blocks');
const negotiated_ratesRoutes = require('./routes/negotiated_rates');
const booking_requestsRoutes = require('./routes/booking_requests');
const booking_request_travelersRoutes = require('./routes/booking_request_travelers');
const approval_stepsRoutes = require('./routes/approval_steps');
const reservationsRoutes = require('./routes/reservations');
const reservation_guestsRoutes = require('./routes/reservation_guests');
const service_requestsRoutes = require('./routes/service_requests');
const invoicesRoutes = require('./routes/invoices');
const invoice_line_itemsRoutes = require('./routes/invoice_line_items');
const paymentsRoutes = require('./routes/payments');
const documentsRoutes = require('./routes/documents');
const audit_logsRoutes = require('./routes/audit_logs');
const notificationsRoutes = require('./routes/notifications');
const activity_commentsRoutes = require('./routes/activity_comments');
const checklistsRoutes = require('./routes/checklists');
const checklist_itemsRoutes = require('./routes/checklist_items');
const job_runsRoutes = require('./routes/job_runs');
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: "Gracey Corporate Stay Portal",
description: "Gracey Corporate Stay Portal 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/tenants', passport.authenticate('jwt', {session: false}), tenantsRoutes);
app.use('/api/role_assignments', passport.authenticate('jwt', {session: false}), role_assignmentsRoutes);
app.use('/api/organization_memberships', passport.authenticate('jwt', {session: false}), organization_membershipsRoutes);
app.use('/api/properties', passport.authenticate('jwt', {session: false}), propertiesRoutes);
app.use('/api/amenities', passport.authenticate('jwt', {session: false}), amenitiesRoutes);
app.use('/api/unit_types', passport.authenticate('jwt', {session: false}), unit_typesRoutes);
app.use('/api/units', passport.authenticate('jwt', {session: false}), unitsRoutes);
app.use('/api/unit_availability_blocks', passport.authenticate('jwt', {session: false}), unit_availability_blocksRoutes);
app.use('/api/negotiated_rates', passport.authenticate('jwt', {session: false}), negotiated_ratesRoutes);
app.use('/api/booking_requests', passport.authenticate('jwt', {session: false}), booking_requestsRoutes);
app.use('/api/booking_request_travelers', passport.authenticate('jwt', {session: false}), booking_request_travelersRoutes);
app.use('/api/approval_steps', passport.authenticate('jwt', {session: false}), approval_stepsRoutes);
app.use('/api/reservations', passport.authenticate('jwt', {session: false}), reservationsRoutes);
app.use('/api/reservation_guests', passport.authenticate('jwt', {session: false}), reservation_guestsRoutes);
app.use('/api/service_requests', passport.authenticate('jwt', {session: false}), service_requestsRoutes);
app.use('/api/invoices', passport.authenticate('jwt', {session: false}), invoicesRoutes);
app.use('/api/invoice_line_items', passport.authenticate('jwt', {session: false}), invoice_line_itemsRoutes);
app.use('/api/payments', passport.authenticate('jwt', {session: false}), paymentsRoutes);
app.use('/api/documents', passport.authenticate('jwt', {session: false}), documentsRoutes);
app.use('/api/audit_logs', passport.authenticate('jwt', {session: false}), audit_logsRoutes);
app.use('/api/notifications', passport.authenticate('jwt', {session: false}), notificationsRoutes);
app.use('/api/activity_comments', passport.authenticate('jwt', {session: false}), activity_commentsRoutes);
app.use('/api/checklists', passport.authenticate('jwt', {session: false}), checklistsRoutes);
app.use('/api/checklist_items', passport.authenticate('jwt', {session: false}), checklist_itemsRoutes);
app.use('/api/job_runs', passport.authenticate('jwt', {session: false}), job_runsRoutes);
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,441 @@
const express = require('express');
const Activity_commentsService = require('../services/activity_comments');
const Activity_commentsDBApi = require('../db/api/activity_comments');
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('activity_comments'));
/**
* @swagger
* components:
* schemas:
* Activity_comments:
* type: object
* properties:
* body:
* type: string
* default: body
*
*/
/**
* @swagger
* tags:
* name: Activity_comments
* description: The Activity_comments managing API
*/
/**
* @swagger
* /api/activity_comments:
* post:
* security:
* - bearerAuth: []
* tags: [Activity_comments]
* 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/Activity_comments"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Activity_comments"
* 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 Activity_commentsService.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: [Activity_comments]
* 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/Activity_comments"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Activity_comments"
* 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 Activity_commentsService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/activity_comments/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Activity_comments]
* 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/Activity_comments"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Activity_comments"
* 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 Activity_commentsService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/activity_comments/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Activity_comments]
* 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/Activity_comments"
* 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 Activity_commentsService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/activity_comments/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Activity_comments]
* 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/Activity_comments"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await Activity_commentsService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/activity_comments:
* get:
* security:
* - bearerAuth: []
* tags: [Activity_comments]
* summary: Get all activity_comments
* description: Get all activity_comments
* responses:
* 200:
* description: Activity_comments list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Activity_comments"
* 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 Activity_commentsDBApi.findAll(
req.query, globalAccess, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','body',
'posted_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/activity_comments/count:
* get:
* security:
* - bearerAuth: []
* tags: [Activity_comments]
* summary: Count all activity_comments
* description: Count all activity_comments
* responses:
* 200:
* description: Activity_comments count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Activity_comments"
* 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 Activity_commentsDBApi.findAll(
req.query,
globalAccess,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/activity_comments/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Activity_comments]
* summary: Find all activity_comments that match search criteria
* description: Find all activity_comments that match search criteria
* responses:
* 200:
* description: Activity_comments list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Activity_comments"
* 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 Activity_commentsDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
globalAccess, organizationId,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/activity_comments/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Activity_comments]
* 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/Activity_comments"
* 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 Activity_commentsDBApi.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 AmenitiesService = require('../services/amenities');
const AmenitiesDBApi = require('../db/api/amenities');
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('amenities'));
/**
* @swagger
* components:
* schemas:
* Amenities:
* type: object
* properties:
* name:
* type: string
* default: name
* description:
* type: string
* default: description
*/
/**
* @swagger
* tags:
* name: Amenities
* description: The Amenities managing API
*/
/**
* @swagger
* /api/amenities:
* post:
* security:
* - bearerAuth: []
* tags: [Amenities]
* 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/Amenities"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Amenities"
* 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 AmenitiesService.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: [Amenities]
* 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/Amenities"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Amenities"
* 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 AmenitiesService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/amenities/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Amenities]
* 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/Amenities"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Amenities"
* 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 AmenitiesService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/amenities/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Amenities]
* 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/Amenities"
* 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 AmenitiesService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/amenities/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Amenities]
* 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/Amenities"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await AmenitiesService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/amenities:
* get:
* security:
* - bearerAuth: []
* tags: [Amenities]
* summary: Get all amenities
* description: Get all amenities
* responses:
* 200:
* description: Amenities list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Amenities"
* 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 AmenitiesDBApi.findAll(
req.query, globalAccess, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','name','description',
];
const opts = { fields };
try {
const csv = parse(payload.rows, opts);
res.status(200).attachment(csv);
res.send(csv)
} catch (err) {
console.error(err);
}
} else {
res.status(200).send(payload);
}
}));
/**
* @swagger
* /api/amenities/count:
* get:
* security:
* - bearerAuth: []
* tags: [Amenities]
* summary: Count all amenities
* description: Count all amenities
* responses:
* 200:
* description: Amenities count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Amenities"
* 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 AmenitiesDBApi.findAll(
req.query,
globalAccess,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/amenities/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Amenities]
* summary: Find all amenities that match search criteria
* description: Find all amenities that match search criteria
* responses:
* 200:
* description: Amenities list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Amenities"
* 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 AmenitiesDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
globalAccess, organizationId,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/amenities/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Amenities]
* 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/Amenities"
* 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 AmenitiesDBApi.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 Approval_stepsService = require('../services/approval_steps');
const Approval_stepsDBApi = require('../db/api/approval_steps');
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('approval_steps'));
/**
* @swagger
* components:
* schemas:
* Approval_steps:
* type: object
* properties:
* decision_notes:
* type: string
* default: decision_notes
* step_order:
* type: integer
* format: int64
*
*/
/**
* @swagger
* tags:
* name: Approval_steps
* description: The Approval_steps managing API
*/
/**
* @swagger
* /api/approval_steps:
* post:
* security:
* - bearerAuth: []
* tags: [Approval_steps]
* 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/Approval_steps"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Approval_steps"
* 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 Approval_stepsService.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: [Approval_steps]
* 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/Approval_steps"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Approval_steps"
* 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 Approval_stepsService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/approval_steps/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Approval_steps]
* 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/Approval_steps"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Approval_steps"
* 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 Approval_stepsService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/approval_steps/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Approval_steps]
* 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/Approval_steps"
* 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 Approval_stepsService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/approval_steps/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Approval_steps]
* 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/Approval_steps"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await Approval_stepsService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/approval_steps:
* get:
* security:
* - bearerAuth: []
* tags: [Approval_steps]
* summary: Get all approval_steps
* description: Get all approval_steps
* responses:
* 200:
* description: Approval_steps list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Approval_steps"
* 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 Approval_stepsDBApi.findAll(
req.query, globalAccess, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','decision_notes',
'step_order',
'decided_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/approval_steps/count:
* get:
* security:
* - bearerAuth: []
* tags: [Approval_steps]
* summary: Count all approval_steps
* description: Count all approval_steps
* responses:
* 200:
* description: Approval_steps count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Approval_steps"
* 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 Approval_stepsDBApi.findAll(
req.query,
globalAccess,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/approval_steps/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Approval_steps]
* summary: Find all approval_steps that match search criteria
* description: Find all approval_steps that match search criteria
* responses:
* 200:
* description: Approval_steps list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Approval_steps"
* 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 Approval_stepsDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
globalAccess, organizationId,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/approval_steps/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Approval_steps]
* 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/Approval_steps"
* 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 Approval_stepsDBApi.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 Audit_logsService = require('../services/audit_logs');
const Audit_logsDBApi = require('../db/api/audit_logs');
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('audit_logs'));
/**
* @swagger
* components:
* schemas:
* Audit_logs:
* type: object
* properties:
* action:
* type: string
* default: action
* entity_name:
* type: string
* default: entity_name
* entity_reference:
* type: string
* default: entity_reference
* ip_address:
* type: string
* default: ip_address
* user_agent:
* type: string
* default: user_agent
* metadata_json:
* type: string
* default: metadata_json
*/
/**
* @swagger
* tags:
* name: Audit_logs
* description: The Audit_logs managing API
*/
/**
* @swagger
* /api/audit_logs:
* post:
* security:
* - bearerAuth: []
* tags: [Audit_logs]
* summary: Add new item
* description: Add new item
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Audit_logs"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Audit_logs"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*/
router.post('/', wrapAsync(async (req, res) => {
const referer = req.headers.referer || `${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await Audit_logsService.create(req.body.data, req.currentUser, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/budgets/bulk-import:
* post:
* security:
* - bearerAuth: []
* tags: [Audit_logs]
* summary: Bulk import items
* description: Bulk import items
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated items
* type: array
* items:
* $ref: "#/components/schemas/Audit_logs"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Audit_logs"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*
*/
router.post('/bulk-import', wrapAsync(async (req, res) => {
const referer = req.headers.referer || `${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await Audit_logsService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/audit_logs/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Audit_logs]
* summary: Update the data of the selected item
* description: Update the data of the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to update
* required: true
* schema:
* type: string
* requestBody:
* description: Set new item data
* required: true
* content:
* application/json:
* schema:
* properties:
* id:
* description: ID of the updated item
* type: string
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Audit_logs"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Audit_logs"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.put('/:id', wrapAsync(async (req, res) => {
await Audit_logsService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/audit_logs/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Audit_logs]
* summary: Delete the selected item
* description: Delete the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to delete
* required: true
* schema:
* type: string
* responses:
* 200:
* description: The item was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Audit_logs"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.delete('/:id', wrapAsync(async (req, res) => {
await Audit_logsService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/audit_logs/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Audit_logs]
* summary: Delete the selected item list
* description: Delete the selected item list
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* ids:
* description: IDs of the updated items
* type: array
* responses:
* 200:
* description: The items was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Audit_logs"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await Audit_logsService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/audit_logs:
* get:
* security:
* - bearerAuth: []
* tags: [Audit_logs]
* summary: Get all audit_logs
* description: Get all audit_logs
* responses:
* 200:
* description: Audit_logs list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Audit_logs"
* 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 Audit_logsDBApi.findAll(
req.query, globalAccess, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','action','entity_name','entity_reference','ip_address','user_agent','metadata_json',
'occurred_at',
];
const opts = { fields };
try {
const csv = parse(payload.rows, opts);
res.status(200).attachment(csv);
res.send(csv)
} catch (err) {
console.error(err);
}
} else {
res.status(200).send(payload);
}
}));
/**
* @swagger
* /api/audit_logs/count:
* get:
* security:
* - bearerAuth: []
* tags: [Audit_logs]
* summary: Count all audit_logs
* description: Count all audit_logs
* responses:
* 200:
* description: Audit_logs count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Audit_logs"
* 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 Audit_logsDBApi.findAll(
req.query,
globalAccess,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/audit_logs/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Audit_logs]
* summary: Find all audit_logs that match search criteria
* description: Find all audit_logs that match search criteria
* responses:
* 200:
* description: Audit_logs list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Audit_logs"
* 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 Audit_logsDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
globalAccess, organizationId,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/audit_logs/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Audit_logs]
* summary: Get selected item
* description: Get selected item
* parameters:
* - in: path
* name: id
* description: ID of item to get
* required: true
* schema:
* type: string
* responses:
* 200:
* description: Selected item successfully received
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Audit_logs"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.get('/:id', wrapAsync(async (req, res) => {
const payload = await Audit_logsDBApi.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,455 @@
const express = require('express');
const Booking_request_travelersService = require('../services/booking_request_travelers');
const Booking_request_travelersDBApi = require('../db/api/booking_request_travelers');
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('booking_request_travelers'));
/**
* @swagger
* components:
* schemas:
* Booking_request_travelers:
* type: object
* properties:
* full_name:
* type: string
* default: full_name
* email:
* type: string
* default: email
* phone:
* type: string
* default: phone
* nationality:
* type: string
* default: nationality
* passport_number:
* type: string
* default: passport_number
* notes:
* type: string
* default: notes
*/
/**
* @swagger
* tags:
* name: Booking_request_travelers
* description: The Booking_request_travelers managing API
*/
/**
* @swagger
* /api/booking_request_travelers:
* post:
* security:
* - bearerAuth: []
* tags: [Booking_request_travelers]
* 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/Booking_request_travelers"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Booking_request_travelers"
* 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 Booking_request_travelersService.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: [Booking_request_travelers]
* 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/Booking_request_travelers"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Booking_request_travelers"
* 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 Booking_request_travelersService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/booking_request_travelers/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Booking_request_travelers]
* 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/Booking_request_travelers"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Booking_request_travelers"
* 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 Booking_request_travelersService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/booking_request_travelers/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Booking_request_travelers]
* 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/Booking_request_travelers"
* 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 Booking_request_travelersService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/booking_request_travelers/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Booking_request_travelers]
* 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/Booking_request_travelers"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await Booking_request_travelersService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/booking_request_travelers:
* get:
* security:
* - bearerAuth: []
* tags: [Booking_request_travelers]
* summary: Get all booking_request_travelers
* description: Get all booking_request_travelers
* responses:
* 200:
* description: Booking_request_travelers list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Booking_request_travelers"
* 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 Booking_request_travelersDBApi.findAll(
req.query, globalAccess, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','full_name','email','phone','nationality','passport_number','notes',
'date_of_birth',
];
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/booking_request_travelers/count:
* get:
* security:
* - bearerAuth: []
* tags: [Booking_request_travelers]
* summary: Count all booking_request_travelers
* description: Count all booking_request_travelers
* responses:
* 200:
* description: Booking_request_travelers count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Booking_request_travelers"
* 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 Booking_request_travelersDBApi.findAll(
req.query,
globalAccess,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/booking_request_travelers/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Booking_request_travelers]
* summary: Find all booking_request_travelers that match search criteria
* description: Find all booking_request_travelers that match search criteria
* responses:
* 200:
* description: Booking_request_travelers list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Booking_request_travelers"
* 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 Booking_request_travelersDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
globalAccess, organizationId,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/booking_request_travelers/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Booking_request_travelers]
* 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/Booking_request_travelers"
* 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 Booking_request_travelersDBApi.findBy(
{ id: req.params.id },
);
res.status(200).send(payload);
}));
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

View File

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