Initial version

This commit is contained in:
Flatlogic Bot 2026-06-27 02:27:22 +00:00
commit 7a3d2b5d5f
691 changed files with 253222 additions and 0 deletions

305
.cursorrules Normal file
View File

@ -0,0 +1,305 @@
# Cursor Rules - Group 1: Development Philosophy & Coding Conventions
1. Overall Architecture & Structure:
- Enforce a clear separation of concerns between the backend and the frontend:
- **Backend**: Use Express for routing, Passport for authentication, and Swagger for API documentation. Organize code into modules such as routes, services, and helpers.
- **Example**:
- Routes: `src/routes/auth.js` for authentication routes.
- Services: `src/services/auth.js` for authentication logic.
- Helpers: `src/helpers/wrapAsync.js` for wrapping asynchronous functions.
- **Frontend**: Use Next.js with React and TypeScript. Structure components using functional components, hooks, and layouts.
- **Example**:
- Pages: `pages/index.tsx` for the main page.
- Components: `components/Header.tsx` for the header component.
- Layouts: `layouts/MainLayout.tsx` for common page layouts.
- Ensure that backend modules and frontend components are organized for reusability and maintainability:
- **Backend**: Separate business logic into services and use middleware for common tasks.
- **Frontend**: Use reusable components and hooks to manage state and lifecycle.
2. Coding Style & Formatting:
- For the backend (JavaScript):
• Use ES6+ features (const/let, arrow functions) consistently.
• Follow Prettier and ESLint configurations (e.g., consistent 2-space indentation, semicolons, and single quotes).
• Maintain clear asynchronous patterns with helper wrappers (e.g., wrapAsync).
- **Example from auth.js**:
```javascript
router.post('/signin/local', wrapAsync(async (req, res) => {
const payload = await AuthService.signin(req.body.email, req.body.password, req);
res.status(200).send(payload);
}));
```
• Document API endpoints with inline Swagger comments to ensure API clarity and consistency.
- **Example**:
```javascript
/**
* @swagger
* /api/auth/signin:
* post:
* summary: Sign in a user
* responses:
* 200:
* description: Successful login
*/
```
- For the frontend (TypeScript/React):
• Use functional components with strict typing and separation of concerns.
- **Example**:
```typescript
const Button: React.FC<{ onClick: () => void }> = ({ onClick }) => (
<button onClick={onClick}>Click me</button>
);
```
• Follow naming conventions: PascalCase for components and types/interfaces, camelCase for variables, hooks, and function names.
- **Example**:
```typescript
const useCustomHook = () => {
const [state, setState] = useState(false);
return [state, setState];
};
```
• Utilize hooks (useEffect, useState) to manage state and lifecycle in a clear and concise manner.
- **Example**:
```typescript
useEffect(() => {
console.log('Component mounted');
}, []);
```
3. Code Quality & Best Practices:
- Ensure code modularity by splitting complex logic into smaller, testable units.
- **Example**: In `auth.js`, routes are separated from business logic, which is handled in `AuthService`.
- Write self-documenting code and add comments where the logic is non-trivial.
- **Example**: Use descriptive function and variable names in `auth.js`, and add comments for complex asynchronous operations.
- Embrace declarative programming and adhere to SOLID principles.
- **Example**: In service functions, ensure each function has a single responsibility and dependencies are injected rather than hardcoded.
4. Consistency & Tools Integration:
- Leverage existing tools like Prettier and ESLint to automatically enforce style and formatting rules.
- **Example**: Use `.prettierrc` and `.eslintrc.cjs` for configuration in your project.
- Use TypeScript in the frontend to ensure type safety and catch errors early.
- **Example**: Define interfaces and types in your React components to enforce strict typing.
- Maintain uniformity in API design and error handling strategies.
- **Example**: Consistently use Passport for authentication and a common error handling middleware in `auth.js`.
## Group 2 Naming Conventions
1. File Naming and Structure:
• Frontend:
- Page Files: Use lower-case filenames (e.g., index.tsx) as prescribed by Next.js conventions.
- **Example**: `pages/index.tsx`, `pages/about.tsx`
- Component Files: Use PascalCase for React component files (e.g., WebSiteHeader.tsx, NavBar.tsx).
- **Example**: `components/Header.tsx`, `components/Footer.tsx`
- Directories: Use clear, descriptive names (e.g., 'pages', 'components', 'WebPageComponents').
- **Example**: `src/pages`, `src/components`
• Backend:
- Use lower-case filenames for modules (e.g., index.js, auth.js, projects.js).
- **Example**: `routes/auth.js`, `services/user.js`
- When needed, use hyphenation for clarity, but maintain consistency.
- **Example**: `helpers/wrap-async.js`
2. Component and Module Naming:
• Frontend:
- React Components: Define components in PascalCase.
- TypeScript Interfaces/Types: Use PascalCase (e.g., WebSiteHeaderProps).
• Backend:
- Classes (if any) and constructors should be in PascalCase; most helper functions and modules use camelCase.
3. Variable, Function, and Hook Naming:
• Use camelCase for variables and function names in both frontend and backend.
- **Example**:
```javascript
const userName = 'John Doe';
function handleLogin() { ... }
```
• Custom Hooks: Prefix with 'use' (e.g., useAuth, useForm).
- **Example**:
```typescript
const useAuth = () => {
const [isAuthenticated, setIsAuthenticated] = useState(false);
return { isAuthenticated, setIsAuthenticated };
};
```
4. Consistency and Readability:
• Maintain uniform naming across the project to ensure clarity and ease of maintenance.
- **Example**: Use consistent naming conventions for variables, functions, and components, such as camelCase for variables and functions, and PascalCase for components.
- **Example**: In `auth.js`, ensure that all function names clearly describe their purpose, such as `handleLogin` or `validateUserInput`.
## Group 3 Frontend & React Best Practices
1. Use of Functional Components & TypeScript:
• Build all components as functional components.
- **Example**:
```typescript
const Header: React.FC = () => {
return <header>Header Content</header>;
};
```
• Leverage TypeScript for static type checking and enforce strict prop and state types.
- **Example**:
```typescript
interface ButtonProps {
onClick: () => void;
}
const Button: React.FC<ButtonProps> = ({ onClick }) => (
<button onClick={onClick}>Click me</button>
);
```
2. Effective Use of React Hooks:
• Utilize useState and useEffect appropriately with proper dependency arrays.
- **Example**:
```typescript
const [count, setCount] = useState(0);
useEffect(() => {
console.log('Component mounted');
}, []);
```
• Create custom hooks to encapsulate shared logic (e.g., useAppSelector).
- **Example**:
```typescript
const useAuth = () => {
const [isAuthenticated, setIsAuthenticated] = useState(false);
return { isAuthenticated, setIsAuthenticated };
};
```
3. Component Composition & Separation of Concerns:
• Separate presentational (stateless) components from container components managing logic.
- **Example**: Use `LayoutGuest` to encapsulate common page structures.
4. Code Quality & Readability:
• Maintain consistent formatting and adhere to Prettier and ESLint rules.
• Use descriptive names for variables, functions, and components.
• Document non-trivial logic with inline comments and consider implementing error boundaries where needed.
• New code must adhere to these conventions to avoid ambiguity.
• Use descriptive names that reflect the purpose and domain, avoiding abbreviations unless standard in the project.
## Group 4 Backend & API Guidelines
1. API Endpoint Design & Documentation:
• Follow RESTful naming conventions; all route handlers should be named clearly and consistently.
- **Example**: Use verbs like `GET`, `POST`, `PUT`, `DELETE` to define actions, e.g., `GET /api/auth/me` to retrieve user info.
• Document endpoints with Swagger annotations to provide descriptions, expected request bodies, and response codes.
- **Example**:
```javascript
/**
* @swagger
* /api/auth/signin:
* post:
* summary: Sign in a user
* requestBody:
* description: User credentials
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Auth"
* responses:
* 200:
* description: Successful login
* 400:
* description: Invalid username/password supplied
*/
```
• Examples (for Auth endpoints):
- POST /api/auth/signin/local
• Description: Logs the user into the system.
• Request Body (application/json):
{ "email": "admin@flatlogic.com", "password": "password" }
• Responses:
- 200: Successful login (returns token and user data).
- 400: Invalid username/password supplied.
- GET /api/auth/me
• Description: Retrieves current authorized user information.
• Secured via Passport JWT; uses req.currentUser.
• Responses:
- 200: Returns current user info.
- 400: Invalid credentials or missing user data.
- POST /api/auth/signup
• Description: Registers a new user.
• Request Body (application/json):
{ "email": "admin@flatlogic.com", "password": "password" }
• Responses:
- 200: New user signed up successfully.
- 400: Invalid input supplied.
- 500: Server error.
## Group 5 Testing, Quality Assurance & Error Handling
1. Testing Guidelines:
• Write unit tests for critical backend and frontend components using frameworks such as Jest, React Testing Library, and Mocha/Chai.
- **Example**:
```javascript
test('should return user data', async () => {
const user = await getUserData();
expect(user).toHaveProperty('email');
});
```
• Practice test-driven development and maintain high test coverage.
• Regularly update tests following changes in business logic.
2. Quality Assurance:
• Enforce code quality with ESLint, Prettier, and static analysis tools.
• Integrate continuous testing workflows (CI/CD) to catch issues early.
- **Example**: Use GitHub Actions for automated testing and deployment.
• Ensure documentation is kept up-to-date with the implemented code.
3. Error Handling:
• Back-end:
- Wrap asynchronous route handlers with a helper (e.g., wrapAsync) to capture errors.
- **Example**:
```javascript
router.post('/signin', wrapAsync(async (req, res) => {
const user = await AuthService.signin(req.body);
res.send(user);
}));
```
- Use centralized error handling middleware (e.g., commonErrorHandler) for uniform error responses.
• Front-end:
- Implement error boundaries in React to gracefully handle runtime errors.
- Display user-friendly error messages and log errors for further analysis.
2. Authentication & Security:
• Protect endpoints by using Passport.js with JWT (e.g., passport.authenticate('jwt', { session: false })).
- **Example**:
```javascript
router.get('/profile', passport.authenticate('jwt', { session: false }), (req, res) => {
res.send(req.user);
});
```
• Ensure that secure routes check for existence of req.currentUser. If absent, return a ForbiddenError.
3. Consistent Error Handling & Middleware Usage:
• Wrap asynchronous route handlers with helpers like wrapAsync for error propagation.
• Use centralized error handling middleware (e.g., commonErrorHandler) to capture and format errors uniformly.
4. Modular Code Organization:
• Organize backend code into separate files for routes, services, and database access (e.g., auth.js, projects.js, tasks.js).
• Use descriptive, lowercase filenames for modules and routes.
5. Endpoint Security Best Practices:
• Validate input data and sanitize requests where necessary.
• Restrict sensitive operations to authenticated users with proper role-based permissions.
────────────────────────────────────────
Group 6 Accessibility, UI, and Styling Guidelines (Updated)
────────────────────────────────────────
1. Sidebar Styling:
• The sidebar is implemented in the authenticated layout via the AsideMenu component, with the actual element defined in AsideMenuLayer (located at frontend/src/components/AsideMenuLayer.tsx) as an <aside> element with id="asideMenu".
- **Example**:
```css
#asideMenu {
background-color: #F8F4E1 !important;
}
```
• When modifying sidebar styles, target #asideMenu and its child elements rather than generic selectors (e.g., avoid .app-sidebar) to ensure that the changes affect the actual rendered sidebar.
• Remove or override any conflicting background utilities (such as an unwanted bg-white) so our desired background color (#F8F4E1) is fully visible. Use a highly specific selector if necessary.
• Adjust spacing (padding/margins) at both the container (#asideMenu) and the individual menu item level to maintain a consistent, compact design.
2. General Project Styling and Tailwind CSS Usage:
• The application leverages Tailwind CSS extensively, with core styling defined in _theme.css using the @apply directive. Any new modifications should follow this pattern to ensure consistency.
- **Example**:
```css
.btn {
@apply bg-blue-500 text-white;
}
```
• The themed blocks (like .theme-pink and .theme-green) standardize the UI's appearance. When applying custom overrides, ensure they integrate cleanly into these structures and avoid conflicts or circular dependency errors (e.g., issues when redefining utilities such as text-blue-600).
• Adjustments via Tailwind CSS generally require modifying class names in the components and ensuring that global overrides are applied in the correct order. Consistent use of design tokens and custom color codes (e.g., #F8F4E1) throughout the app is crucial to a cohesive design.
• Specificity is key. If a change isn't visually reflected as expected, inspect the rendered HTML to identify which classes are taking precedence.

3
.dockerignore Normal file
View File

@ -0,0 +1,3 @@
backend/node_modules
frontend/node_modules
frontend/build

3
.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
node_modules/
*/node_modules/
*/build/

187
502.html Normal file
View File

@ -0,0 +1,187 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Service Starting</title>
<style>
body {
font-family: sans-serif;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
min-height: 100vh;
background-color: #EFF2FF;
margin: 0;
padding: 20px;
}
.container {
text-align: center;
padding: 30px 40px;
background-color: #fff;
border-radius: 20px;
margin-bottom: 20px;
max-width: 538px;
width: 100%;
box-shadow: 0 13px 34px 0 rgba(167, 187, 242, 0.2);
box-sizing: border-box;
}
#status-heading {
font-size: 24px;
font-weight: 700;
color: #02004E;
margin-bottom: 20px;
}
h2 {
color: #333;
margin-bottom: 15px;
}
p {
color: #666;
font-size: 1.1em;
margin-bottom: 10px;
}
.tip {
font-weight: 300;
font-size: 17px;
line-height: 150%;
letter-spacing: 0;
text-align: center;
margin-top: 30px;
}
.loader-container {
position: relative;
display: flex;
justify-content: center;
align-items: center;
}
.loader {
width: 100px;
aspect-ratio: 1;
border-radius: 50%;
background:
radial-gradient(farthest-side, #5C7EF1 94%, #0000) top/8px 8px no-repeat,
conic-gradient(#0000 30%, #5C7EF1);
-webkit-mask: radial-gradient(farthest-side, #0000 calc(100% - 8px), #000 0);
animation: l13 2s infinite linear;
}
@keyframes l13 {
100% {
transform: rotate(1turn)
}
}
.app-logo {
position: absolute;
width: 36px;
}
.panel {
padding: 0 18px;
display: none;
background-color: white;
overflow: hidden;
margin-top: 10px;
}
.show {
display: block;
}
.project-info {
border: 1px solid #8C9DFF;
border-radius: 10px;
padding: 12px 16px;
max-width: 600px;
margin: 40px auto;
background-color: #FBFCFF;
}
.project-info h2 {
color: #02004E;
font-size: 14px;
font-weight: 500;
margin-bottom: 10px;
text-align: left;
}
.project-info p {
color: #686791;
font-size: 12px;
font-weight: 400;
text-align: left;
}
</style>
</head>
<body>
<div class="container">
<h2 id="status-heading">Loading the app, just a moment…</h2>
<p class="tip">The application is currently launching. The page will automatically refresh once site is
available.</p>
<div class="project-info">
<h2>App Preview</h2>
<p>Multi-tenant Hotel PMS SaaS for reservations, front desk, housekeeping, billing, and analytics.</p>
</div>
<div class="loader-container">
<img src="https://flatlogic.com/blog/wp-content/uploads/2025/05/logo-bot-1.png" alt="App Logo"
class="app-logo">
<div class="loader"></div>
</div>
<div class="panel">
<video width="100%" height="315" controls loop>
<source
src="https://flatlogic.com/blog/wp-content/uploads/2025/04/20250430_1336_professional_dynamo_spinner_simple_compose_01jt349yvtenxt7xhg8hhr85j8.mp4"
type="video/mp4">
Your browser does not support the video tag.
</video>
</div>
</div>
<script>
function checkAvailability() {
fetch('/')
.then(response => {
if (response.ok) {
window.location.reload();
} else {
setTimeout(checkAvailability, 5000);
}
})
.catch(() => {
setTimeout(checkAvailability, 5000);
});
}
document.addEventListener('DOMContentLoaded', checkAvailability);
document.addEventListener('DOMContentLoaded', function () {
const appTitle = document.querySelector('#status-heading');
const panel = document.querySelector('.panel');
const video = panel.querySelector('video');
let clickCount = 0;
appTitle.addEventListener('click', function () {
clickCount++;
if (clickCount === 5) {
panel.classList.toggle('show');
if (panel.classList.contains('show')) {
video.play();
} else {
video.pause();
}
clickCount = 0;
}
});
});
</script>
</body>
</html>

21
Dockerfile Normal file
View File

@ -0,0 +1,21 @@
FROM node:20.15.1-alpine AS builder
RUN apk add --no-cache git
WORKDIR /app
COPY frontend/package.json frontend/yarn.lock ./
RUN yarn install --pure-lockfile
COPY frontend .
RUN yarn build
FROM node:20.15.1-alpine
WORKDIR /app
COPY backend/package.json backend/yarn.lock ./
RUN yarn install --pure-lockfile
COPY backend .
COPY --from=builder /app/build /app/public
CMD ["yarn", "start"]

85
Dockerfile.dev Normal file
View File

@ -0,0 +1,85 @@
# Base image for Node.js dependencies
FROM node:20.15.1-alpine AS frontend-deps
RUN apk add --no-cache git
WORKDIR /app/frontend
COPY frontend/package.json frontend/yarn.lock ./
RUN yarn install --pure-lockfile
FROM node:20.15.1-alpine AS backend-deps
RUN apk add --no-cache git
WORKDIR /app/backend
COPY backend/package.json backend/yarn.lock ./
RUN yarn install --pure-lockfile
FROM node:20.15.1-alpine AS app-shell-deps
RUN apk add --no-cache git
WORKDIR /app/app-shell
COPY app-shell/package.json app-shell/yarn.lock ./
RUN yarn install --pure-lockfile
# Nginx setup and application build
FROM node:20.15.1-alpine AS build
RUN apk add --no-cache git nginx curl
RUN apk add --no-cache lsof procps
RUN yarn global add concurrently
RUN apk add --no-cache \
chromium \
nss \
freetype \
harfbuzz \
ttf-freefont \
fontconfig
ENV PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=true
ENV PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium-browser
RUN mkdir -p /app/pids
# Make sure to add yarn global bin to PATH
ENV PATH /root/.yarn/bin:/root/.config/yarn/global/node_modules/.bin:$PATH
# Copy dependencies
WORKDIR /app
COPY --from=frontend-deps /app/frontend /app/frontend
COPY --from=backend-deps /app/backend /app/backend
COPY --from=app-shell-deps /app/app-shell /app/app-shell
COPY frontend /app/frontend
COPY backend /app/backend
COPY app-shell /app/app-shell
COPY docker /app/docker
# Copy all files from root to /app
COPY . /app
# Copy Nginx configuration
COPY nginx.conf /etc/nginx/nginx.conf
# Copy custom error page
COPY 502.html /usr/share/nginx/html/502.html
# Change owner and permissions of the error page
RUN chown nginx:nginx /usr/share/nginx/html/502.html && \
chmod 644 /usr/share/nginx/html/502.html
# Expose the port the app runs on
EXPOSE 8080
ENV NODE_ENV=dev_stage
ENV FRONT_PORT=3001
ENV BACKEND_PORT=3000
ENV APP_SHELL_PORT=4000
CMD ["sh", "-c", "\
yarn --cwd /app/frontend dev & echo $! > /app/pids/frontend.pid && \
yarn --cwd /app/backend start & echo $! > /app/pids/backend.pid && \
sleep 10 && nginx -g 'daemon off;' & \
NGINX_PID=$! && \
echo 'Waiting for backend (port 3000) to be available...' && \
while ! nc -z localhost ${BACKEND_PORT}; do \
sleep 2; \
done && \
echo 'Backend is up. Starting app_shell for Git check...' && \
yarn --cwd /app/app-shell start && \
wait $NGINX_PID"]

1
LICENSE Normal file
View File

@ -0,0 +1 @@
https://flatlogic.com/

244
README.md Normal file
View File

@ -0,0 +1,244 @@
# App Preview
## This project was generated by [Flatlogic Platform](https://flatlogic.com).
- Frontend: [React.js](https://flatlogic.com/templates?framework%5B%5D=react&sort=default)
- Backend: [NodeJS](https://flatlogic.com/templates?backend%5B%5D=nodejs&sort=default)
<details><summary>Backend Folder Structure</summary>
The generated application has the following backend folder structure:
`src` folder which contains your working files that will be used later to create the build. The src folder contains folders as:
- `auth` - config the library for authentication and authorization;
- `db` - contains such folders as:
- `api` - documentation that is automatically generated by jsdoc or other tools;
- `migrations` - is a skeleton of the database or all the actions that users do with the database;
- `models`- what will represent the database for the backend;
- `seeders` - the entity that creates the data for the database.
- `routes` - this folder would contain all the routes that you have created using Express Router and what they do would be exported from a Controller file;
- `services` - contains such folders as `emails` and `notifications`.
</details>
- Database: PostgreSQL
- app-shel: Core application framework that provides essential infrastructure services
for the entire application.
-----------------------
### We offer 2 ways how to start the project locally: by running Frontend and Backend or with Docker.
-----------------------
## To start the project:
### Backend:
> Please change current folder: `cd backend`
#### Install local dependencies:
`yarn install`
------------
#### Adjust local db:
##### 1. Install postgres:
MacOS:
`brew install postgres`
> if you dont have brew please install it (https://brew.sh) and repeat step `brew install postgres`.
Ubuntu:
`sudo apt update`
`sudo apt install postgresql postgresql-contrib`
##### 2. Create db and admin user:
Before run and test connection, make sure you have created a database as described in the above configuration. You can use the `psql` command to create a user and database.
`psql postgres --u postgres`
Next, type this command for creating a new user with password then give access for creating the database.
`postgres-# CREATE ROLE admin WITH LOGIN PASSWORD 'admin_pass';`
`postgres-# ALTER ROLE admin CREATEDB;`
Quit `psql` then log in again using the new user that previously created.
`postgres-# \q`
`psql postgres -U admin`
Type this command to creating a new database.
`postgres=> CREATE DATABASE db_{your_project_name};`
Then give that new user privileges to the new database then quit the `psql`.
`postgres=> GRANT ALL PRIVILEGES ON DATABASE db_{your_project_name} TO admin;`
`postgres=> \q`
------------
#### Create database:
`yarn db:create`
#### Start production build:
`yarn start`
### Frontend:
> Please change current folder: `cd frontend`
## To start the project with Docker:
### Description:
The project contains the **docker folder** and the `Dockerfile`.
The `Dockerfile` is used to Deploy the project to Google Cloud.
The **docker folder** contains a couple of helper scripts:
- `docker-compose.yml` (all our services: web, backend, db are described here)
- `start-backend.sh` (starts backend, but only after the database)
- `wait-for-it.sh` (imported from https://github.com/vishnubob/wait-for-it)
> To avoid breaking the application, we recommend you don't edit the following files: everything that includes the **docker folder** and `Dokerfile`.
## Run services:
1. Install docker compose (https://docs.docker.com/compose/install/)
2. Move to `docker` folder. All next steps should be done from this folder.
``` cd docker ```
3. Make executables from `wait-for-it.sh` and `start-backend.sh`:
``` chmod +x start-backend.sh && chmod +x wait-for-it.sh ```
4. Download dependend projects for services.
5. Review the docker-compose.yml file. Make sure that all services have Dockerfiles. Only db service doesn't require a Dockerfile.
6. Make sure you have needed ports (see them in `ports`) available on your local machine.
7. Start services:
7.1. With an empty database `rm -rf data && docker-compose up`
7.2. With a stored (from previus runs) database data `docker-compose up`
8. Check http://localhost:3000
9. Stop services:
9.1. Just press `Ctr+C`
## Most common errors:
1. `connection refused`
There could be many reasons, but the most common are:
- The port is not open on the destination machine.
- The port is open on the destination machine, but its backlog of pending connections is full.
- A firewall between the client and server is blocking access (also check local firewalls).
After checking for firewalls and that the port is open, use telnet to connect to the IP/port to test connectivity. This removes any potential issues from your application.
***MacOS:***
If you suspect that your SSH service might be down, you can run this command to find out:
`sudo service ssh status`
If the command line returns a status of down, then youve likely found the reason behind your connectivity error.
***Ubuntu:***
Sometimes a connection refused error can also indicate that there is an IP address conflict on your network. You can search for possible IP conflicts by running:
`arp-scan -I eth0 -l | grep <ipaddress>`
`arp-scan -I eth0 -l | grep <ipaddress>`
and
`arping <ipaddress>`
2. `yarn db:create` creates database with the assembled tables (on MacOS with Postgres database)
The workaround - put the next commands to your Postgres database terminal:
`DROP SCHEMA public CASCADE;`
`CREATE SCHEMA public;`
`GRANT ALL ON SCHEMA public TO postgres;`
`GRANT ALL ON SCHEMA public TO public;`
Afterwards, continue to start your project in the backend directory by running:
`yarn start`

1
backend/.env Normal file
View File

@ -0,0 +1 @@
PORT=8080

4
backend/.eslintignore Normal file
View File

@ -0,0 +1,4 @@
# Ignore generated and runtime files
node_modules/
tmp/
logs/

15
backend/.eslintrc.cjs Normal file
View File

@ -0,0 +1,15 @@
module.exports = {
env: {
node: true,
es2021: true
},
extends: [
'eslint:recommended'
],
plugins: [
'import'
],
rules: {
'import/no-unresolved': 'error'
}
};

11
backend/.prettierrc Normal file
View File

@ -0,0 +1,11 @@
{
"singleQuote": true,
"tabWidth": 2,
"printWidth": 80,
"trailingComma": "all",
"quoteProps": "as-needed",
"jsxSingleQuote": true,
"bracketSpacing": true,
"bracketSameLine": false,
"arrowParens": "always"
}

7
backend/.sequelizerc Normal file
View File

@ -0,0 +1,7 @@
const path = require('path');
module.exports = {
"config": path.resolve("src", "db", "db.config.js"),
"models-path": path.resolve("src", "db", "models"),
"seeders-path": path.resolve("src", "db", "seeders"),
"migrations-path": path.resolve("src", "db", "migrations")
};

23
backend/Dockerfile Normal file
View File

@ -0,0 +1,23 @@
FROM node:20.15.1-alpine
RUN apk update && apk add bash
# Create app directory
WORKDIR /usr/src/app
# Install app dependencies
# A wildcard is used to ensure both package.json AND package-lock.json are copied
# where available (npm@5+)
COPY package*.json ./
RUN yarn install
# If you are building your code for production
# RUN npm ci --only=production
# Bundle app source
COPY . .
EXPOSE 8080
CMD [ "yarn", "start" ]

56
backend/README.md Normal file
View File

@ -0,0 +1,56 @@
#App Preview - template backend,
#### Run App on local machine:
##### Install local dependencies:
- `yarn install`
------------
##### Adjust local db:
###### 1. Install postgres:
- MacOS:
- `brew install postgres`
- Ubuntu:
- `sudo apt update`
- `sudo apt install postgresql postgresql-contrib`
###### 2. Create db and admin user:
- Before run and test connection, make sure you have created a database as described in the above configuration. You can use the `psql` command to create a user and database.
- `psql postgres --u postgres`
- Next, type this command for creating a new user with password then give access for creating the database.
- `postgres-# CREATE ROLE admin WITH LOGIN PASSWORD 'admin_pass';`
- `postgres-# ALTER ROLE admin CREATEDB;`
- Quit `psql` then log in again using the new user that previously created.
- `postgres-# \q`
- `psql postgres -U admin`
- Type this command to creating a new database.
- `postgres=> CREATE DATABASE db_app_preview;`
- Then give that new user privileges to the new database then quit the `psql`.
- `postgres=> GRANT ALL PRIVILEGES ON DATABASE db_app_preview TO admin;`
- `postgres=> \q`
------------
#### Api Documentation (Swagger)
http://localhost:8080/api-docs (local host)
http://host_name/api-docs
------------
##### Setup database tables or update after schema change
- `yarn db:migrate`
##### Seed the initial data (admin accounts, relevant for the first setup):
- `yarn db:seed`
##### Start build:
- `yarn start`

56
backend/package.json Normal file
View File

@ -0,0 +1,56 @@
{
"name": "apppreview",
"description": "App Preview - template backend",
"scripts": {
"start": "npm run db:migrate && npm run db:seed && npm run watch",
"lint": "eslint . --ext .js",
"db:migrate": "sequelize-cli db:migrate",
"db:seed": "sequelize-cli db:seed:all",
"db:drop": "sequelize-cli db:drop",
"db:create": "sequelize-cli db:create",
"watch": "node watcher.js"
},
"dependencies": {
"@google-cloud/storage": "^5.18.2",
"axios": "^1.6.7",
"bcrypt": "5.1.1",
"chokidar": "^4.0.3",
"cors": "2.8.5",
"csv-parser": "^3.0.0",
"express": "4.18.2",
"formidable": "1.2.2",
"helmet": "4.1.1",
"json2csv": "^5.0.7",
"jsonwebtoken": "8.5.1",
"lodash": "4.17.21",
"moment": "2.30.1",
"multer": "^1.4.4",
"mysql2": "2.2.5",
"nodemailer": "6.9.9",
"passport": "^0.7.0",
"passport-google-oauth2": "^0.2.0",
"passport-jwt": "^4.0.1",
"passport-microsoft": "^0.1.0",
"pg": "8.4.1",
"pg-hstore": "2.3.4",
"sequelize": "6.35.2",
"sequelize-json-schema": "^2.1.1",
"sqlite": "4.0.15",
"swagger-jsdoc": "^6.2.8",
"swagger-ui-express": "^5.0.0",
"tedious": "^18.2.4"
},
"engines": {
"node": ">=18"
},
"private": true,
"devDependencies": {
"cross-env": "7.0.3",
"eslint": "^8.23.1",
"eslint-plugin-import": "^2.29.1",
"mocha": "8.1.3",
"node-mocks-http": "1.9.0",
"nodemon": "2.0.5",
"sequelize-cli": "6.6.2"
}
}

View File

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

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

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

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: "97ff8103",
user_pass: "289dd5a78a9d",
admin_email: "admin@flatlogic.com",
providers: {
LOCAL: 'local',
GOOGLE: 'google',
MICROSOFT: 'microsoft'
},
secret_key: process.env.SECRET_KEY || '97ff8103-cbf0-4e54-97d7-289dd5a78a9d',
remote: '',
port: process.env.NODE_ENV === "production" ? "" : "8080",
hostUI: process.env.NODE_ENV === "production" ? "" : "http://localhost",
portUI: process.env.NODE_ENV === "production" ? "" : "3000",
portUIProd: process.env.NODE_ENV === "production" ? "" : ":3000",
swaggerUI: process.env.NODE_ENV === "production" ? "" : "http://localhost",
swaggerPort: process.env.NODE_ENV === "production" ? "" : ":8080",
google: {
clientId: process.env.GOOGLE_CLIENT_ID || '',
clientSecret: process.env.GOOGLE_CLIENT_SECRET || '',
},
microsoft: {
clientId: process.env.MS_CLIENT_ID || '',
clientSecret: process.env.MS_CLIENT_SECRET || '',
},
uploadDir: os.tmpdir(),
email: {
from: 'App Preview <app@flatlogic.app>',
host: 'email-smtp.us-east-1.amazonaws.com',
port: 587,
auth: {
user: process.env.EMAIL_USER || '',
pass: process.env.EMAIL_PASS,
},
tls: {
rejectUnauthorized: false
}
},
roles: {
super_admin: 'Super Administrator',
admin: 'Administrator',
user: 'Housekeeping Associate',
},
project_uuid: '97ff8103-cbf0-4e54-97d7-289dd5a78a9d',
flHost: process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'dev_stage' ? 'https://flatlogic.com/projects' : 'http://localhost:3000/projects',
gpt_key: process.env.GPT_KEY || '',
};
config.pexelsKey = process.env.PEXELS_KEY || '';
config.pexelsQuery = 'Lighthouse guiding ships 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,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 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
,
record_reference: data.record_reference
||
null
,
occurred_at: data.occurred_at
||
null
,
ip_address: data.ip_address
||
null
,
user_agent: data.user_agent
||
null
,
details: data.details
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await audit_logs.setHotel( data.hotel || null, {
transaction,
});
await audit_logs.setActor_user( data.actor_user || 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
,
record_reference: item.record_reference
||
null
,
occurred_at: item.occurred_at
||
null
,
ip_address: item.ip_address
||
null
,
user_agent: item.user_agent
||
null
,
details: item.details
||
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.record_reference !== undefined) updatePayload.record_reference = data.record_reference;
if (data.occurred_at !== undefined) updatePayload.occurred_at = data.occurred_at;
if (data.ip_address !== undefined) updatePayload.ip_address = data.ip_address;
if (data.user_agent !== undefined) updatePayload.user_agent = data.user_agent;
if (data.details !== undefined) updatePayload.details = data.details;
updatePayload.updatedById = currentUser.id;
await audit_logs.update(updatePayload, {transaction});
if (data.hotel !== undefined) {
await audit_logs.setHotel(
data.hotel,
{ transaction }
);
}
if (data.actor_user !== undefined) {
await audit_logs.setActor_user(
data.actor_user,
{ 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.hotel = await audit_logs.getHotel({
transaction
});
output.actor_user = await audit_logs.getActor_user({
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.hotels,
as: 'hotel',
where: filter.hotel ? {
[Op.or]: [
{ id: { [Op.in]: filter.hotel.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.hotel.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'actor_user',
where: filter.actor_user ? {
[Op.or]: [
{ id: { [Op.in]: filter.actor_user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.actor_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.entity_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'audit_logs',
'entity_name',
filter.entity_name,
),
};
}
if (filter.record_reference) {
where = {
...where,
[Op.and]: Utils.ilike(
'audit_logs',
'record_reference',
filter.record_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.details) {
where = {
...where,
[Op.and]: Utils.ilike(
'audit_logs',
'details',
filter.details,
),
};
}
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.action) {
where = {
...where,
action: filter.action,
};
}
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',
'entity_name',
query,
),
],
};
}
const records = await db.audit_logs.findAll({
attributes: [ 'id', 'entity_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['entity_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.entity_name,
}));
}
};

View File

@ -0,0 +1,518 @@
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_widgetsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const booking_widgets = await db.booking_widgets.create(
{
id: data.id || undefined,
name: data.name
||
null
,
public_key: data.public_key
||
null
,
allowed_domains: data.allowed_domains
||
null
,
active: data.active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await booking_widgets.setHotel( data.hotel || null, {
transaction,
});
await booking_widgets.setOrganizations( data.organizations || null, {
transaction,
});
return booking_widgets;
}
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_widgetsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
public_key: item.public_key
||
null
,
allowed_domains: item.allowed_domains
||
null
,
active: item.active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const booking_widgets = await db.booking_widgets.bulkCreate(booking_widgetsData, { transaction });
// For each item created, replace relation files
return booking_widgets;
}
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_widgets = await db.booking_widgets.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.public_key !== undefined) updatePayload.public_key = data.public_key;
if (data.allowed_domains !== undefined) updatePayload.allowed_domains = data.allowed_domains;
if (data.active !== undefined) updatePayload.active = data.active;
updatePayload.updatedById = currentUser.id;
await booking_widgets.update(updatePayload, {transaction});
if (data.hotel !== undefined) {
await booking_widgets.setHotel(
data.hotel,
{ transaction }
);
}
if (data.organizations !== undefined) {
await booking_widgets.setOrganizations(
data.organizations,
{ transaction }
);
}
return booking_widgets;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const booking_widgets = await db.booking_widgets.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of booking_widgets) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of booking_widgets) {
await record.destroy({transaction});
}
});
return booking_widgets;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const booking_widgets = await db.booking_widgets.findByPk(id, options);
await booking_widgets.update({
deletedBy: currentUser.id
}, {
transaction,
});
await booking_widgets.destroy({
transaction
});
return booking_widgets;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const booking_widgets = await db.booking_widgets.findOne(
{ where },
{ transaction },
);
if (!booking_widgets) {
return booking_widgets;
}
const output = booking_widgets.get({plain: true});
output.hotel = await booking_widgets.getHotel({
transaction
});
output.organizations = await booking_widgets.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.hotels,
as: 'hotel',
where: filter.hotel ? {
[Op.or]: [
{ id: { [Op.in]: filter.hotel.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.hotel.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(
'booking_widgets',
'name',
filter.name,
),
};
}
if (filter.public_key) {
where = {
...where,
[Op.and]: Utils.ilike(
'booking_widgets',
'public_key',
filter.public_key,
),
};
}
if (filter.allowed_domains) {
where = {
...where,
[Op.and]: Utils.ilike(
'booking_widgets',
'allowed_domains',
filter.allowed_domains,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.active) {
where = {
...where,
active: filter.active,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.booking_widgets.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_widgets',
'name',
query,
),
],
};
}
const records = await db.booking_widgets.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,868 @@
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 Daily_snapshotsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const daily_snapshots = await db.daily_snapshots.create(
{
id: data.id || undefined,
snapshot_at: data.snapshot_at
||
null
,
rooms_available: data.rooms_available
||
null
,
rooms_occupied: data.rooms_occupied
||
null
,
rooms_dirty: data.rooms_dirty
||
null
,
rooms_out_of_service: data.rooms_out_of_service
||
null
,
occupancy_rate_percent: data.occupancy_rate_percent
||
null
,
revenue_today: data.revenue_today
||
null
,
revenue_month_to_date: data.revenue_month_to_date
||
null
,
adr: data.adr
||
null
,
revpar: data.revpar
||
null
,
arrivals_today: data.arrivals_today
||
null
,
departures_today: data.departures_today
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await daily_snapshots.setHotel( data.hotel || null, {
transaction,
});
await daily_snapshots.setOrganizations( data.organizations || null, {
transaction,
});
return daily_snapshots;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const daily_snapshotsData = data.map((item, index) => ({
id: item.id || undefined,
snapshot_at: item.snapshot_at
||
null
,
rooms_available: item.rooms_available
||
null
,
rooms_occupied: item.rooms_occupied
||
null
,
rooms_dirty: item.rooms_dirty
||
null
,
rooms_out_of_service: item.rooms_out_of_service
||
null
,
occupancy_rate_percent: item.occupancy_rate_percent
||
null
,
revenue_today: item.revenue_today
||
null
,
revenue_month_to_date: item.revenue_month_to_date
||
null
,
adr: item.adr
||
null
,
revpar: item.revpar
||
null
,
arrivals_today: item.arrivals_today
||
null
,
departures_today: item.departures_today
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const daily_snapshots = await db.daily_snapshots.bulkCreate(daily_snapshotsData, { transaction });
// For each item created, replace relation files
return daily_snapshots;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const daily_snapshots = await db.daily_snapshots.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.snapshot_at !== undefined) updatePayload.snapshot_at = data.snapshot_at;
if (data.rooms_available !== undefined) updatePayload.rooms_available = data.rooms_available;
if (data.rooms_occupied !== undefined) updatePayload.rooms_occupied = data.rooms_occupied;
if (data.rooms_dirty !== undefined) updatePayload.rooms_dirty = data.rooms_dirty;
if (data.rooms_out_of_service !== undefined) updatePayload.rooms_out_of_service = data.rooms_out_of_service;
if (data.occupancy_rate_percent !== undefined) updatePayload.occupancy_rate_percent = data.occupancy_rate_percent;
if (data.revenue_today !== undefined) updatePayload.revenue_today = data.revenue_today;
if (data.revenue_month_to_date !== undefined) updatePayload.revenue_month_to_date = data.revenue_month_to_date;
if (data.adr !== undefined) updatePayload.adr = data.adr;
if (data.revpar !== undefined) updatePayload.revpar = data.revpar;
if (data.arrivals_today !== undefined) updatePayload.arrivals_today = data.arrivals_today;
if (data.departures_today !== undefined) updatePayload.departures_today = data.departures_today;
updatePayload.updatedById = currentUser.id;
await daily_snapshots.update(updatePayload, {transaction});
if (data.hotel !== undefined) {
await daily_snapshots.setHotel(
data.hotel,
{ transaction }
);
}
if (data.organizations !== undefined) {
await daily_snapshots.setOrganizations(
data.organizations,
{ transaction }
);
}
return daily_snapshots;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const daily_snapshots = await db.daily_snapshots.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of daily_snapshots) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of daily_snapshots) {
await record.destroy({transaction});
}
});
return daily_snapshots;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const daily_snapshots = await db.daily_snapshots.findByPk(id, options);
await daily_snapshots.update({
deletedBy: currentUser.id
}, {
transaction,
});
await daily_snapshots.destroy({
transaction
});
return daily_snapshots;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const daily_snapshots = await db.daily_snapshots.findOne(
{ where },
{ transaction },
);
if (!daily_snapshots) {
return daily_snapshots;
}
const output = daily_snapshots.get({plain: true});
output.hotel = await daily_snapshots.getHotel({
transaction
});
output.organizations = await daily_snapshots.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.hotels,
as: 'hotel',
where: filter.hotel ? {
[Op.or]: [
{ id: { [Op.in]: filter.hotel.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.hotel.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.snapshot_atRange) {
const [start, end] = filter.snapshot_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
snapshot_at: {
...where.snapshot_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
snapshot_at: {
...where.snapshot_at,
[Op.lte]: end,
},
};
}
}
if (filter.rooms_availableRange) {
const [start, end] = filter.rooms_availableRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
rooms_available: {
...where.rooms_available,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
rooms_available: {
...where.rooms_available,
[Op.lte]: end,
},
};
}
}
if (filter.rooms_occupiedRange) {
const [start, end] = filter.rooms_occupiedRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
rooms_occupied: {
...where.rooms_occupied,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
rooms_occupied: {
...where.rooms_occupied,
[Op.lte]: end,
},
};
}
}
if (filter.rooms_dirtyRange) {
const [start, end] = filter.rooms_dirtyRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
rooms_dirty: {
...where.rooms_dirty,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
rooms_dirty: {
...where.rooms_dirty,
[Op.lte]: end,
},
};
}
}
if (filter.rooms_out_of_serviceRange) {
const [start, end] = filter.rooms_out_of_serviceRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
rooms_out_of_service: {
...where.rooms_out_of_service,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
rooms_out_of_service: {
...where.rooms_out_of_service,
[Op.lte]: end,
},
};
}
}
if (filter.occupancy_rate_percentRange) {
const [start, end] = filter.occupancy_rate_percentRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
occupancy_rate_percent: {
...where.occupancy_rate_percent,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
occupancy_rate_percent: {
...where.occupancy_rate_percent,
[Op.lte]: end,
},
};
}
}
if (filter.revenue_todayRange) {
const [start, end] = filter.revenue_todayRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
revenue_today: {
...where.revenue_today,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
revenue_today: {
...where.revenue_today,
[Op.lte]: end,
},
};
}
}
if (filter.revenue_month_to_dateRange) {
const [start, end] = filter.revenue_month_to_dateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
revenue_month_to_date: {
...where.revenue_month_to_date,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
revenue_month_to_date: {
...where.revenue_month_to_date,
[Op.lte]: end,
},
};
}
}
if (filter.adrRange) {
const [start, end] = filter.adrRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
adr: {
...where.adr,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
adr: {
...where.adr,
[Op.lte]: end,
},
};
}
}
if (filter.revparRange) {
const [start, end] = filter.revparRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
revpar: {
...where.revpar,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
revpar: {
...where.revpar,
[Op.lte]: end,
},
};
}
}
if (filter.arrivals_todayRange) {
const [start, end] = filter.arrivals_todayRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
arrivals_today: {
...where.arrivals_today,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
arrivals_today: {
...where.arrivals_today,
[Op.lte]: end,
},
};
}
}
if (filter.departures_todayRange) {
const [start, end] = filter.departures_todayRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
departures_today: {
...where.departures_today,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
departures_today: {
...where.departures_today,
[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.daily_snapshots.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'daily_snapshots',
'snapshot_at',
query,
),
],
};
}
const records = await db.daily_snapshots.findAll({
attributes: [ 'id', 'snapshot_at' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['snapshot_at', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.snapshot_at,
}));
}
};

View File

@ -0,0 +1,498 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class DepartmentsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const departments = await db.departments.create(
{
id: data.id || undefined,
name: data.name
||
null
,
description: data.description
||
null
,
active: data.active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await departments.setHotel( data.hotel || null, {
transaction,
});
await departments.setOrganizations( data.organizations || null, {
transaction,
});
return departments;
}
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 departmentsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
description: item.description
||
null
,
active: item.active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const departments = await db.departments.bulkCreate(departmentsData, { transaction });
// For each item created, replace relation files
return departments;
}
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 departments = await db.departments.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.active !== undefined) updatePayload.active = data.active;
updatePayload.updatedById = currentUser.id;
await departments.update(updatePayload, {transaction});
if (data.hotel !== undefined) {
await departments.setHotel(
data.hotel,
{ transaction }
);
}
if (data.organizations !== undefined) {
await departments.setOrganizations(
data.organizations,
{ transaction }
);
}
return departments;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const departments = await db.departments.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of departments) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of departments) {
await record.destroy({transaction});
}
});
return departments;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const departments = await db.departments.findByPk(id, options);
await departments.update({
deletedBy: currentUser.id
}, {
transaction,
});
await departments.destroy({
transaction
});
return departments;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const departments = await db.departments.findOne(
{ where },
{ transaction },
);
if (!departments) {
return departments;
}
const output = departments.get({plain: true});
output.staff_profiles_department = await departments.getStaff_profiles_department({
transaction
});
output.hotel = await departments.getHotel({
transaction
});
output.organizations = await departments.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.hotels,
as: 'hotel',
where: filter.hotel ? {
[Op.or]: [
{ id: { [Op.in]: filter.hotel.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.hotel.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(
'departments',
'name',
filter.name,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'departments',
'description',
filter.description,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.active) {
where = {
...where,
active: filter.active,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.departments.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(
'departments',
'name',
query,
),
],
};
}
const records = await db.departments.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,810 @@
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 Dynamic_pricing_rulesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const dynamic_pricing_rules = await db.dynamic_pricing_rules.create(
{
id: data.id || undefined,
name: data.name
||
null
,
rule_type: data.rule_type
||
null
,
adjustment_percent: data.adjustment_percent
||
null
,
adjustment_amount: data.adjustment_amount
||
null
,
min_occupancy_percent: data.min_occupancy_percent
||
null
,
max_occupancy_percent: data.max_occupancy_percent
||
null
,
min_days_before: data.min_days_before
||
null
,
max_days_before: data.max_days_before
||
null
,
applies_days_of_week: data.applies_days_of_week
||
null
,
active: data.active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await dynamic_pricing_rules.setHotel( data.hotel || null, {
transaction,
});
await dynamic_pricing_rules.setRoom_type( data.room_type || null, {
transaction,
});
await dynamic_pricing_rules.setRate_plan( data.rate_plan || null, {
transaction,
});
await dynamic_pricing_rules.setOrganizations( data.organizations || null, {
transaction,
});
return dynamic_pricing_rules;
}
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 dynamic_pricing_rulesData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
rule_type: item.rule_type
||
null
,
adjustment_percent: item.adjustment_percent
||
null
,
adjustment_amount: item.adjustment_amount
||
null
,
min_occupancy_percent: item.min_occupancy_percent
||
null
,
max_occupancy_percent: item.max_occupancy_percent
||
null
,
min_days_before: item.min_days_before
||
null
,
max_days_before: item.max_days_before
||
null
,
applies_days_of_week: item.applies_days_of_week
||
null
,
active: item.active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const dynamic_pricing_rules = await db.dynamic_pricing_rules.bulkCreate(dynamic_pricing_rulesData, { transaction });
// For each item created, replace relation files
return dynamic_pricing_rules;
}
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 dynamic_pricing_rules = await db.dynamic_pricing_rules.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.rule_type !== undefined) updatePayload.rule_type = data.rule_type;
if (data.adjustment_percent !== undefined) updatePayload.adjustment_percent = data.adjustment_percent;
if (data.adjustment_amount !== undefined) updatePayload.adjustment_amount = data.adjustment_amount;
if (data.min_occupancy_percent !== undefined) updatePayload.min_occupancy_percent = data.min_occupancy_percent;
if (data.max_occupancy_percent !== undefined) updatePayload.max_occupancy_percent = data.max_occupancy_percent;
if (data.min_days_before !== undefined) updatePayload.min_days_before = data.min_days_before;
if (data.max_days_before !== undefined) updatePayload.max_days_before = data.max_days_before;
if (data.applies_days_of_week !== undefined) updatePayload.applies_days_of_week = data.applies_days_of_week;
if (data.active !== undefined) updatePayload.active = data.active;
updatePayload.updatedById = currentUser.id;
await dynamic_pricing_rules.update(updatePayload, {transaction});
if (data.hotel !== undefined) {
await dynamic_pricing_rules.setHotel(
data.hotel,
{ transaction }
);
}
if (data.room_type !== undefined) {
await dynamic_pricing_rules.setRoom_type(
data.room_type,
{ transaction }
);
}
if (data.rate_plan !== undefined) {
await dynamic_pricing_rules.setRate_plan(
data.rate_plan,
{ transaction }
);
}
if (data.organizations !== undefined) {
await dynamic_pricing_rules.setOrganizations(
data.organizations,
{ transaction }
);
}
return dynamic_pricing_rules;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const dynamic_pricing_rules = await db.dynamic_pricing_rules.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of dynamic_pricing_rules) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of dynamic_pricing_rules) {
await record.destroy({transaction});
}
});
return dynamic_pricing_rules;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const dynamic_pricing_rules = await db.dynamic_pricing_rules.findByPk(id, options);
await dynamic_pricing_rules.update({
deletedBy: currentUser.id
}, {
transaction,
});
await dynamic_pricing_rules.destroy({
transaction
});
return dynamic_pricing_rules;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const dynamic_pricing_rules = await db.dynamic_pricing_rules.findOne(
{ where },
{ transaction },
);
if (!dynamic_pricing_rules) {
return dynamic_pricing_rules;
}
const output = dynamic_pricing_rules.get({plain: true});
output.hotel = await dynamic_pricing_rules.getHotel({
transaction
});
output.room_type = await dynamic_pricing_rules.getRoom_type({
transaction
});
output.rate_plan = await dynamic_pricing_rules.getRate_plan({
transaction
});
output.organizations = await dynamic_pricing_rules.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.hotels,
as: 'hotel',
where: filter.hotel ? {
[Op.or]: [
{ id: { [Op.in]: filter.hotel.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.hotel.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.room_types,
as: 'room_type',
where: filter.room_type ? {
[Op.or]: [
{ id: { [Op.in]: filter.room_type.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.room_type.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.rate_plans,
as: 'rate_plan',
where: filter.rate_plan ? {
[Op.or]: [
{ id: { [Op.in]: filter.rate_plan.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.rate_plan.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(
'dynamic_pricing_rules',
'name',
filter.name,
),
};
}
if (filter.applies_days_of_week) {
where = {
...where,
[Op.and]: Utils.ilike(
'dynamic_pricing_rules',
'applies_days_of_week',
filter.applies_days_of_week,
),
};
}
if (filter.adjustment_percentRange) {
const [start, end] = filter.adjustment_percentRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
adjustment_percent: {
...where.adjustment_percent,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
adjustment_percent: {
...where.adjustment_percent,
[Op.lte]: end,
},
};
}
}
if (filter.adjustment_amountRange) {
const [start, end] = filter.adjustment_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
adjustment_amount: {
...where.adjustment_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
adjustment_amount: {
...where.adjustment_amount,
[Op.lte]: end,
},
};
}
}
if (filter.min_occupancy_percentRange) {
const [start, end] = filter.min_occupancy_percentRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
min_occupancy_percent: {
...where.min_occupancy_percent,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
min_occupancy_percent: {
...where.min_occupancy_percent,
[Op.lte]: end,
},
};
}
}
if (filter.max_occupancy_percentRange) {
const [start, end] = filter.max_occupancy_percentRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
max_occupancy_percent: {
...where.max_occupancy_percent,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
max_occupancy_percent: {
...where.max_occupancy_percent,
[Op.lte]: end,
},
};
}
}
if (filter.min_days_beforeRange) {
const [start, end] = filter.min_days_beforeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
min_days_before: {
...where.min_days_before,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
min_days_before: {
...where.min_days_before,
[Op.lte]: end,
},
};
}
}
if (filter.max_days_beforeRange) {
const [start, end] = filter.max_days_beforeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
max_days_before: {
...where.max_days_before,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
max_days_before: {
...where.max_days_before,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.rule_type) {
where = {
...where,
rule_type: filter.rule_type,
};
}
if (filter.active) {
where = {
...where,
active: filter.active,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.dynamic_pricing_rules.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(
'dynamic_pricing_rules',
'name',
query,
),
],
};
}
const records = await db.dynamic_pricing_rules.findAll({
attributes: [ 'id', 'name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.name,
}));
}
};

View File

@ -0,0 +1,87 @@
const db = require('../models');
const assert = require('assert');
const services = require('../../services/file');
module.exports = class FileDBApi {
static async replaceRelationFiles(
relation,
rawFiles,
options,
) {
assert(relation.belongsTo, 'belongsTo is required');
assert(
relation.belongsToColumn,
'belongsToColumn is required',
);
assert(relation.belongsToId, 'belongsToId is required');
let files = [];
if (Array.isArray(rawFiles)) {
files = rawFiles;
} else {
files = rawFiles ? [rawFiles] : [];
}
await this._removeLegacyFiles(relation, files, options);
await this._addFiles(relation, files, options);
}
static async _addFiles(relation, files, options) {
const transaction = (options && options.transaction) || undefined;
const currentUser = (options && options.currentUser) || {id: null};
const inexistentFiles = files.filter(
(file) => !!file.new,
);
for (const file of inexistentFiles) {
await db.file.create(
{
belongsTo: relation.belongsTo,
belongsToColumn: relation.belongsToColumn,
belongsToId: relation.belongsToId,
name: file.name,
sizeInBytes: file.sizeInBytes,
privateUrl: file.privateUrl,
publicUrl: file.publicUrl,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{
transaction,
},
);
}
}
static async _removeLegacyFiles(
relation,
files,
options,
) {
const transaction = (options && options.transaction) || undefined;
const filesToDelete = await db.file.findAll({
where: {
belongsTo: relation.belongsTo,
belongsToId: relation.belongsToId,
belongsToColumn: relation.belongsToColumn,
id: {
[db.Sequelize.Op
.notIn]: files
.filter((file) => !file.new)
.map((file) => file.id)
},
},
transaction,
});
for (let file of filesToDelete) {
await services.deleteGCloud(file.privateUrl);
await file.destroy({
transaction,
});
}
}
};

View File

@ -0,0 +1,675 @@
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 Folio_itemsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const folio_items = await db.folio_items.create(
{
id: data.id || undefined,
item_type: data.item_type
||
null
,
description: data.description
||
null
,
posted_at: data.posted_at
||
null
,
quantity: data.quantity
||
null
,
unit_price: data.unit_price
||
null
,
amount: data.amount
||
null
,
taxable: data.taxable
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await folio_items.setHotel( data.hotel || null, {
transaction,
});
await folio_items.setStay_folio( data.stay_folio || null, {
transaction,
});
await folio_items.setOrganizations( data.organizations || null, {
transaction,
});
return folio_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 folio_itemsData = data.map((item, index) => ({
id: item.id || undefined,
item_type: item.item_type
||
null
,
description: item.description
||
null
,
posted_at: item.posted_at
||
null
,
quantity: item.quantity
||
null
,
unit_price: item.unit_price
||
null
,
amount: item.amount
||
null
,
taxable: item.taxable
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const folio_items = await db.folio_items.bulkCreate(folio_itemsData, { transaction });
// For each item created, replace relation files
return folio_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 folio_items = await db.folio_items.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.item_type !== undefined) updatePayload.item_type = data.item_type;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.posted_at !== undefined) updatePayload.posted_at = data.posted_at;
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.taxable !== undefined) updatePayload.taxable = data.taxable;
updatePayload.updatedById = currentUser.id;
await folio_items.update(updatePayload, {transaction});
if (data.hotel !== undefined) {
await folio_items.setHotel(
data.hotel,
{ transaction }
);
}
if (data.stay_folio !== undefined) {
await folio_items.setStay_folio(
data.stay_folio,
{ transaction }
);
}
if (data.organizations !== undefined) {
await folio_items.setOrganizations(
data.organizations,
{ transaction }
);
}
return folio_items;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const folio_items = await db.folio_items.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of folio_items) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of folio_items) {
await record.destroy({transaction});
}
});
return folio_items;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const folio_items = await db.folio_items.findByPk(id, options);
await folio_items.update({
deletedBy: currentUser.id
}, {
transaction,
});
await folio_items.destroy({
transaction
});
return folio_items;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const folio_items = await db.folio_items.findOne(
{ where },
{ transaction },
);
if (!folio_items) {
return folio_items;
}
const output = folio_items.get({plain: true});
output.hotel = await folio_items.getHotel({
transaction
});
output.stay_folio = await folio_items.getStay_folio({
transaction
});
output.organizations = await folio_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.hotels,
as: 'hotel',
where: filter.hotel ? {
[Op.or]: [
{ id: { [Op.in]: filter.hotel.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.hotel.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.stay_folios,
as: 'stay_folio',
where: filter.stay_folio ? {
[Op.or]: [
{ id: { [Op.in]: filter.stay_folio.split('|').map(term => Utils.uuid(term)) } },
{
folio_number: {
[Op.or]: filter.stay_folio.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(
'folio_items',
'description',
filter.description,
),
};
}
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.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.item_type) {
where = {
...where,
item_type: filter.item_type,
};
}
if (filter.taxable) {
where = {
...where,
taxable: filter.taxable,
};
}
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.folio_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(
'folio_items',
'description',
query,
),
],
};
}
const records = await db.folio_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,
}));
}
};

View File

@ -0,0 +1,645 @@
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 Guest_documentsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const guest_documents = await db.guest_documents.create(
{
id: data.id || undefined,
document_type: data.document_type
||
null
,
document_number: data.document_number
||
null
,
issued_at: data.issued_at
||
null
,
expires_at: data.expires_at
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await guest_documents.setHotel( data.hotel || null, {
transaction,
});
await guest_documents.setGuest( data.guest || null, {
transaction,
});
await guest_documents.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.guest_documents.getTableName(),
belongsToColumn: 'file',
belongsToId: guest_documents.id,
},
data.file,
options,
);
return guest_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 guest_documentsData = data.map((item, index) => ({
id: item.id || undefined,
document_type: item.document_type
||
null
,
document_number: item.document_number
||
null
,
issued_at: item.issued_at
||
null
,
expires_at: item.expires_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 guest_documents = await db.guest_documents.bulkCreate(guest_documentsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < guest_documents.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.guest_documents.getTableName(),
belongsToColumn: 'file',
belongsToId: guest_documents[i].id,
},
data[i].file,
options,
);
}
return guest_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 guest_documents = await db.guest_documents.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.document_type !== undefined) updatePayload.document_type = data.document_type;
if (data.document_number !== undefined) updatePayload.document_number = data.document_number;
if (data.issued_at !== undefined) updatePayload.issued_at = data.issued_at;
if (data.expires_at !== undefined) updatePayload.expires_at = data.expires_at;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await guest_documents.update(updatePayload, {transaction});
if (data.hotel !== undefined) {
await guest_documents.setHotel(
data.hotel,
{ transaction }
);
}
if (data.guest !== undefined) {
await guest_documents.setGuest(
data.guest,
{ transaction }
);
}
if (data.organizations !== undefined) {
await guest_documents.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.guest_documents.getTableName(),
belongsToColumn: 'file',
belongsToId: guest_documents.id,
},
data.file,
options,
);
return guest_documents;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const guest_documents = await db.guest_documents.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of guest_documents) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of guest_documents) {
await record.destroy({transaction});
}
});
return guest_documents;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const guest_documents = await db.guest_documents.findByPk(id, options);
await guest_documents.update({
deletedBy: currentUser.id
}, {
transaction,
});
await guest_documents.destroy({
transaction
});
return guest_documents;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const guest_documents = await db.guest_documents.findOne(
{ where },
{ transaction },
);
if (!guest_documents) {
return guest_documents;
}
const output = guest_documents.get({plain: true});
output.hotel = await guest_documents.getHotel({
transaction
});
output.guest = await guest_documents.getGuest({
transaction
});
output.file = await guest_documents.getFile({
transaction
});
output.organizations = await guest_documents.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.hotels,
as: 'hotel',
where: filter.hotel ? {
[Op.or]: [
{ id: { [Op.in]: filter.hotel.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.hotel.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.guests,
as: 'guest',
where: filter.guest ? {
[Op.or]: [
{ id: { [Op.in]: filter.guest.split('|').map(term => Utils.uuid(term)) } },
{
last_name: {
[Op.or]: filter.guest.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'file',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.document_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'guest_documents',
'document_number',
filter.document_number,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'guest_documents',
'notes',
filter.notes,
),
};
}
if (filter.issued_atRange) {
const [start, end] = filter.issued_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
issued_at: {
...where.issued_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
issued_at: {
...where.issued_at,
[Op.lte]: end,
},
};
}
}
if (filter.expires_atRange) {
const [start, end] = filter.expires_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
expires_at: {
...where.expires_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
expires_at: {
...where.expires_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.document_type) {
where = {
...where,
document_type: filter.document_type,
};
}
if (filter.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.guest_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(
'guest_documents',
'document_number',
query,
),
],
};
}
const records = await db.guest_documents.findAll({
attributes: [ 'id', 'document_number' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['document_number', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.document_number,
}));
}
};

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 GuestsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const guests = await db.guests.create(
{
id: data.id || undefined,
first_name: data.first_name
||
null
,
last_name: data.last_name
||
null
,
email: data.email
||
null
,
phone: data.phone
||
null
,
nationality: data.nationality
||
null
,
address_line1: data.address_line1
||
null
,
address_line2: data.address_line2
||
null
,
city: data.city
||
null
,
state_region: data.state_region
||
null
,
postal_code: data.postal_code
||
null
,
country: data.country
||
null
,
preferences: data.preferences
||
null
,
notes: data.notes
||
null
,
loyalty_points: data.loyalty_points
||
null
,
marketing_opt_in: data.marketing_opt_in
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await guests.setHotel( data.hotel || null, {
transaction,
});
await guests.setOrganizations( data.organizations || null, {
transaction,
});
return 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 guestsData = data.map((item, index) => ({
id: item.id || undefined,
first_name: item.first_name
||
null
,
last_name: item.last_name
||
null
,
email: item.email
||
null
,
phone: item.phone
||
null
,
nationality: item.nationality
||
null
,
address_line1: item.address_line1
||
null
,
address_line2: item.address_line2
||
null
,
city: item.city
||
null
,
state_region: item.state_region
||
null
,
postal_code: item.postal_code
||
null
,
country: item.country
||
null
,
preferences: item.preferences
||
null
,
notes: item.notes
||
null
,
loyalty_points: item.loyalty_points
||
null
,
marketing_opt_in: item.marketing_opt_in
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const guests = await db.guests.bulkCreate(guestsData, { transaction });
// For each item created, replace relation files
return 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 guests = await db.guests.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.first_name !== undefined) updatePayload.first_name = data.first_name;
if (data.last_name !== undefined) updatePayload.last_name = data.last_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.address_line1 !== undefined) updatePayload.address_line1 = data.address_line1;
if (data.address_line2 !== undefined) updatePayload.address_line2 = data.address_line2;
if (data.city !== undefined) updatePayload.city = data.city;
if (data.state_region !== undefined) updatePayload.state_region = data.state_region;
if (data.postal_code !== undefined) updatePayload.postal_code = data.postal_code;
if (data.country !== undefined) updatePayload.country = data.country;
if (data.preferences !== undefined) updatePayload.preferences = data.preferences;
if (data.notes !== undefined) updatePayload.notes = data.notes;
if (data.loyalty_points !== undefined) updatePayload.loyalty_points = data.loyalty_points;
if (data.marketing_opt_in !== undefined) updatePayload.marketing_opt_in = data.marketing_opt_in;
updatePayload.updatedById = currentUser.id;
await guests.update(updatePayload, {transaction});
if (data.hotel !== undefined) {
await guests.setHotel(
data.hotel,
{ transaction }
);
}
if (data.organizations !== undefined) {
await guests.setOrganizations(
data.organizations,
{ transaction }
);
}
return guests;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const guests = await db.guests.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of guests) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of guests) {
await record.destroy({transaction});
}
});
return guests;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const guests = await db.guests.findByPk(id, options);
await guests.update({
deletedBy: currentUser.id
}, {
transaction,
});
await guests.destroy({
transaction
});
return guests;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const guests = await db.guests.findOne(
{ where },
{ transaction },
);
if (!guests) {
return guests;
}
const output = guests.get({plain: true});
output.guest_documents_guest = await guests.getGuest_documents_guest({
transaction
});
output.reservations_guest = await guests.getReservations_guest({
transaction
});
output.reservation_guests_guest = await guests.getReservation_guests_guest({
transaction
});
output.notifications_guest = await guests.getNotifications_guest({
transaction
});
output.hotel = await guests.getHotel({
transaction
});
output.organizations = await 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.hotels,
as: 'hotel',
where: filter.hotel ? {
[Op.or]: [
{ id: { [Op.in]: filter.hotel.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.hotel.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.first_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'guests',
'first_name',
filter.first_name,
),
};
}
if (filter.last_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'guests',
'last_name',
filter.last_name,
),
};
}
if (filter.email) {
where = {
...where,
[Op.and]: Utils.ilike(
'guests',
'email',
filter.email,
),
};
}
if (filter.phone) {
where = {
...where,
[Op.and]: Utils.ilike(
'guests',
'phone',
filter.phone,
),
};
}
if (filter.nationality) {
where = {
...where,
[Op.and]: Utils.ilike(
'guests',
'nationality',
filter.nationality,
),
};
}
if (filter.address_line1) {
where = {
...where,
[Op.and]: Utils.ilike(
'guests',
'address_line1',
filter.address_line1,
),
};
}
if (filter.address_line2) {
where = {
...where,
[Op.and]: Utils.ilike(
'guests',
'address_line2',
filter.address_line2,
),
};
}
if (filter.city) {
where = {
...where,
[Op.and]: Utils.ilike(
'guests',
'city',
filter.city,
),
};
}
if (filter.state_region) {
where = {
...where,
[Op.and]: Utils.ilike(
'guests',
'state_region',
filter.state_region,
),
};
}
if (filter.postal_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'guests',
'postal_code',
filter.postal_code,
),
};
}
if (filter.country) {
where = {
...where,
[Op.and]: Utils.ilike(
'guests',
'country',
filter.country,
),
};
}
if (filter.preferences) {
where = {
...where,
[Op.and]: Utils.ilike(
'guests',
'preferences',
filter.preferences,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'guests',
'notes',
filter.notes,
),
};
}
if (filter.loyalty_pointsRange) {
const [start, end] = filter.loyalty_pointsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
loyalty_points: {
...where.loyalty_points,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
loyalty_points: {
...where.loyalty_points,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.marketing_opt_in) {
where = {
...where,
marketing_opt_in: filter.marketing_opt_in,
};
}
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.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(
'guests',
'last_name',
query,
),
],
};
}
const records = await db.guests.findAll({
attributes: [ 'id', 'last_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['last_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.last_name,
}));
}
};

View File

@ -0,0 +1,886 @@
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 HotelsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const hotels = await db.hotels.create(
{
id: data.id || undefined,
name: data.name
||
null
,
legal_name: data.legal_name
||
null
,
address_line1: data.address_line1
||
null
,
address_line2: data.address_line2
||
null
,
city: data.city
||
null
,
state_region: data.state_region
||
null
,
postal_code: data.postal_code
||
null
,
country: data.country
||
null
,
phone: data.phone
||
null
,
email: data.email
||
null
,
website: data.website
||
null
,
timezone: data.timezone
||
null
,
currency: data.currency
||
null
,
default_tax_rate: data.default_tax_rate
||
null
,
active: data.active
||
false
,
stripe_customer_reference: data.stripe_customer_reference
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await hotels.setOrganizations( data.organizations || null, {
transaction,
});
return hotels;
}
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 hotelsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
legal_name: item.legal_name
||
null
,
address_line1: item.address_line1
||
null
,
address_line2: item.address_line2
||
null
,
city: item.city
||
null
,
state_region: item.state_region
||
null
,
postal_code: item.postal_code
||
null
,
country: item.country
||
null
,
phone: item.phone
||
null
,
email: item.email
||
null
,
website: item.website
||
null
,
timezone: item.timezone
||
null
,
currency: item.currency
||
null
,
default_tax_rate: item.default_tax_rate
||
null
,
active: item.active
||
false
,
stripe_customer_reference: item.stripe_customer_reference
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const hotels = await db.hotels.bulkCreate(hotelsData, { transaction });
// For each item created, replace relation files
return hotels;
}
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 hotels = await db.hotels.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.legal_name !== undefined) updatePayload.legal_name = data.legal_name;
if (data.address_line1 !== undefined) updatePayload.address_line1 = data.address_line1;
if (data.address_line2 !== undefined) updatePayload.address_line2 = data.address_line2;
if (data.city !== undefined) updatePayload.city = data.city;
if (data.state_region !== undefined) updatePayload.state_region = data.state_region;
if (data.postal_code !== undefined) updatePayload.postal_code = data.postal_code;
if (data.country !== undefined) updatePayload.country = data.country;
if (data.phone !== undefined) updatePayload.phone = data.phone;
if (data.email !== undefined) updatePayload.email = data.email;
if (data.website !== undefined) updatePayload.website = data.website;
if (data.timezone !== undefined) updatePayload.timezone = data.timezone;
if (data.currency !== undefined) updatePayload.currency = data.currency;
if (data.default_tax_rate !== undefined) updatePayload.default_tax_rate = data.default_tax_rate;
if (data.active !== undefined) updatePayload.active = data.active;
if (data.stripe_customer_reference !== undefined) updatePayload.stripe_customer_reference = data.stripe_customer_reference;
updatePayload.updatedById = currentUser.id;
await hotels.update(updatePayload, {transaction});
if (data.organizations !== undefined) {
await hotels.setOrganizations(
data.organizations,
{ transaction }
);
}
return hotels;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const hotels = await db.hotels.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of hotels) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of hotels) {
await record.destroy({transaction});
}
});
return hotels;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const hotels = await db.hotels.findByPk(id, options);
await hotels.update({
deletedBy: currentUser.id
}, {
transaction,
});
await hotels.destroy({
transaction
});
return hotels;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const hotels = await db.hotels.findOne(
{ where },
{ transaction },
);
if (!hotels) {
return hotels;
}
const output = hotels.get({plain: true});
output.departments_hotel = await hotels.getDepartments_hotel({
transaction
});
output.staff_profiles_hotel = await hotels.getStaff_profiles_hotel({
transaction
});
output.shifts_hotel = await hotels.getShifts_hotel({
transaction
});
output.room_types_hotel = await hotels.getRoom_types_hotel({
transaction
});
output.rooms_hotel = await hotels.getRooms_hotel({
transaction
});
output.guests_hotel = await hotels.getGuests_hotel({
transaction
});
output.guest_documents_hotel = await hotels.getGuest_documents_hotel({
transaction
});
output.rate_plans_hotel = await hotels.getRate_plans_hotel({
transaction
});
output.seasonal_rates_hotel = await hotels.getSeasonal_rates_hotel({
transaction
});
output.dynamic_pricing_rules_hotel = await hotels.getDynamic_pricing_rules_hotel({
transaction
});
output.sales_channels_hotel = await hotels.getSales_channels_hotel({
transaction
});
output.ota_connections_hotel = await hotels.getOta_connections_hotel({
transaction
});
output.reservations_hotel = await hotels.getReservations_hotel({
transaction
});
output.reservation_guests_hotel = await hotels.getReservation_guests_hotel({
transaction
});
output.stay_folios_hotel = await hotels.getStay_folios_hotel({
transaction
});
output.folio_items_hotel = await hotels.getFolio_items_hotel({
transaction
});
output.payments_hotel = await hotels.getPayments_hotel({
transaction
});
output.refunds_hotel = await hotels.getRefunds_hotel({
transaction
});
output.invoices_hotel = await hotels.getInvoices_hotel({
transaction
});
output.housekeeping_tasks_hotel = await hotels.getHousekeeping_tasks_hotel({
transaction
});
output.maintenance_tickets_hotel = await hotels.getMaintenance_tickets_hotel({
transaction
});
output.notifications_hotel = await hotels.getNotifications_hotel({
transaction
});
output.booking_widgets_hotel = await hotels.getBooking_widgets_hotel({
transaction
});
output.subscriptions_hotel = await hotels.getSubscriptions_hotel({
transaction
});
output.audit_logs_hotel = await hotels.getAudit_logs_hotel({
transaction
});
output.daily_snapshots_hotel = await hotels.getDaily_snapshots_hotel({
transaction
});
output.organizations = await hotels.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'hotels',
'name',
filter.name,
),
};
}
if (filter.legal_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'hotels',
'legal_name',
filter.legal_name,
),
};
}
if (filter.address_line1) {
where = {
...where,
[Op.and]: Utils.ilike(
'hotels',
'address_line1',
filter.address_line1,
),
};
}
if (filter.address_line2) {
where = {
...where,
[Op.and]: Utils.ilike(
'hotels',
'address_line2',
filter.address_line2,
),
};
}
if (filter.city) {
where = {
...where,
[Op.and]: Utils.ilike(
'hotels',
'city',
filter.city,
),
};
}
if (filter.state_region) {
where = {
...where,
[Op.and]: Utils.ilike(
'hotels',
'state_region',
filter.state_region,
),
};
}
if (filter.postal_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'hotels',
'postal_code',
filter.postal_code,
),
};
}
if (filter.country) {
where = {
...where,
[Op.and]: Utils.ilike(
'hotels',
'country',
filter.country,
),
};
}
if (filter.phone) {
where = {
...where,
[Op.and]: Utils.ilike(
'hotels',
'phone',
filter.phone,
),
};
}
if (filter.email) {
where = {
...where,
[Op.and]: Utils.ilike(
'hotels',
'email',
filter.email,
),
};
}
if (filter.website) {
where = {
...where,
[Op.and]: Utils.ilike(
'hotels',
'website',
filter.website,
),
};
}
if (filter.timezone) {
where = {
...where,
[Op.and]: Utils.ilike(
'hotels',
'timezone',
filter.timezone,
),
};
}
if (filter.currency) {
where = {
...where,
[Op.and]: Utils.ilike(
'hotels',
'currency',
filter.currency,
),
};
}
if (filter.stripe_customer_reference) {
where = {
...where,
[Op.and]: Utils.ilike(
'hotels',
'stripe_customer_reference',
filter.stripe_customer_reference,
),
};
}
if (filter.default_tax_rateRange) {
const [start, end] = filter.default_tax_rateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
default_tax_rate: {
...where.default_tax_rate,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
default_tax_rate: {
...where.default_tax_rate,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.active) {
where = {
...where,
active: filter.active,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.hotels.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(
'hotels',
'name',
query,
),
],
};
}
const records = await db.hotels.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,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 Housekeeping_tasksDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const housekeeping_tasks = await db.housekeeping_tasks.create(
{
id: data.id || undefined,
scheduled_for: data.scheduled_for
||
null
,
started_at: data.started_at
||
null
,
completed_at: data.completed_at
||
null
,
status: data.status
||
null
,
task_type: data.task_type
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await housekeeping_tasks.setHotel( data.hotel || null, {
transaction,
});
await housekeeping_tasks.setRoom( data.room || null, {
transaction,
});
await housekeeping_tasks.setAssigned_staff_profile( data.assigned_staff_profile || null, {
transaction,
});
await housekeeping_tasks.setOrganizations( data.organizations || null, {
transaction,
});
return housekeeping_tasks;
}
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 housekeeping_tasksData = data.map((item, index) => ({
id: item.id || undefined,
scheduled_for: item.scheduled_for
||
null
,
started_at: item.started_at
||
null
,
completed_at: item.completed_at
||
null
,
status: item.status
||
null
,
task_type: item.task_type
||
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 housekeeping_tasks = await db.housekeeping_tasks.bulkCreate(housekeeping_tasksData, { transaction });
// For each item created, replace relation files
return housekeeping_tasks;
}
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 housekeeping_tasks = await db.housekeeping_tasks.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.scheduled_for !== undefined) updatePayload.scheduled_for = data.scheduled_for;
if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
if (data.completed_at !== undefined) updatePayload.completed_at = data.completed_at;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.task_type !== undefined) updatePayload.task_type = data.task_type;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await housekeeping_tasks.update(updatePayload, {transaction});
if (data.hotel !== undefined) {
await housekeeping_tasks.setHotel(
data.hotel,
{ transaction }
);
}
if (data.room !== undefined) {
await housekeeping_tasks.setRoom(
data.room,
{ transaction }
);
}
if (data.assigned_staff_profile !== undefined) {
await housekeeping_tasks.setAssigned_staff_profile(
data.assigned_staff_profile,
{ transaction }
);
}
if (data.organizations !== undefined) {
await housekeeping_tasks.setOrganizations(
data.organizations,
{ transaction }
);
}
return housekeeping_tasks;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const housekeeping_tasks = await db.housekeeping_tasks.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of housekeeping_tasks) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of housekeeping_tasks) {
await record.destroy({transaction});
}
});
return housekeeping_tasks;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const housekeeping_tasks = await db.housekeeping_tasks.findByPk(id, options);
await housekeeping_tasks.update({
deletedBy: currentUser.id
}, {
transaction,
});
await housekeeping_tasks.destroy({
transaction
});
return housekeeping_tasks;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const housekeeping_tasks = await db.housekeeping_tasks.findOne(
{ where },
{ transaction },
);
if (!housekeeping_tasks) {
return housekeeping_tasks;
}
const output = housekeeping_tasks.get({plain: true});
output.hotel = await housekeeping_tasks.getHotel({
transaction
});
output.room = await housekeeping_tasks.getRoom({
transaction
});
output.assigned_staff_profile = await housekeeping_tasks.getAssigned_staff_profile({
transaction
});
output.organizations = await housekeeping_tasks.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.hotels,
as: 'hotel',
where: filter.hotel ? {
[Op.or]: [
{ id: { [Op.in]: filter.hotel.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.hotel.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.rooms,
as: 'room',
where: filter.room ? {
[Op.or]: [
{ id: { [Op.in]: filter.room.split('|').map(term => Utils.uuid(term)) } },
{
room_number: {
[Op.or]: filter.room.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.staff_profiles,
as: 'assigned_staff_profile',
where: filter.assigned_staff_profile ? {
[Op.or]: [
{ id: { [Op.in]: filter.assigned_staff_profile.split('|').map(term => Utils.uuid(term)) } },
{
employee_code: {
[Op.or]: filter.assigned_staff_profile.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'housekeeping_tasks',
'notes',
filter.notes,
),
};
}
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.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.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.task_type) {
where = {
...where,
task_type: filter.task_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.housekeeping_tasks.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(
'housekeeping_tasks',
'task_type',
query,
),
],
};
}
const records = await db.housekeeping_tasks.findAll({
attributes: [ 'id', 'task_type' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['task_type', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.task_type,
}));
}
};

View File

@ -0,0 +1,780 @@
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 InvoicesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const invoices = await db.invoices.create(
{
id: data.id || undefined,
invoice_number: data.invoice_number
||
null
,
issued_at: data.issued_at
||
null
,
due_at: data.due_at
||
null
,
status: data.status
||
null
,
subtotal_amount: data.subtotal_amount
||
null
,
tax_amount: data.tax_amount
||
null
,
total_amount: data.total_amount
||
null
,
billing_name: data.billing_name
||
null
,
billing_address: data.billing_address
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await invoices.setHotel( data.hotel || null, {
transaction,
});
await invoices.setStay_folio( data.stay_folio || null, {
transaction,
});
await invoices.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.invoices.getTableName(),
belongsToColumn: 'pdf_file',
belongsToId: invoices.id,
},
data.pdf_file,
options,
);
return invoices;
}
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 invoicesData = data.map((item, index) => ({
id: item.id || undefined,
invoice_number: item.invoice_number
||
null
,
issued_at: item.issued_at
||
null
,
due_at: item.due_at
||
null
,
status: item.status
||
null
,
subtotal_amount: item.subtotal_amount
||
null
,
tax_amount: item.tax_amount
||
null
,
total_amount: item.total_amount
||
null
,
billing_name: item.billing_name
||
null
,
billing_address: item.billing_address
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const invoices = await db.invoices.bulkCreate(invoicesData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < invoices.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.invoices.getTableName(),
belongsToColumn: 'pdf_file',
belongsToId: invoices[i].id,
},
data[i].pdf_file,
options,
);
}
return invoices;
}
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 invoices = await db.invoices.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.invoice_number !== undefined) updatePayload.invoice_number = data.invoice_number;
if (data.issued_at !== undefined) updatePayload.issued_at = data.issued_at;
if (data.due_at !== undefined) updatePayload.due_at = data.due_at;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.subtotal_amount !== undefined) updatePayload.subtotal_amount = data.subtotal_amount;
if (data.tax_amount !== undefined) updatePayload.tax_amount = data.tax_amount;
if (data.total_amount !== undefined) updatePayload.total_amount = data.total_amount;
if (data.billing_name !== undefined) updatePayload.billing_name = data.billing_name;
if (data.billing_address !== undefined) updatePayload.billing_address = data.billing_address;
updatePayload.updatedById = currentUser.id;
await invoices.update(updatePayload, {transaction});
if (data.hotel !== undefined) {
await invoices.setHotel(
data.hotel,
{ transaction }
);
}
if (data.stay_folio !== undefined) {
await invoices.setStay_folio(
data.stay_folio,
{ transaction }
);
}
if (data.organizations !== undefined) {
await invoices.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.invoices.getTableName(),
belongsToColumn: 'pdf_file',
belongsToId: invoices.id,
},
data.pdf_file,
options,
);
return invoices;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const invoices = await db.invoices.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of invoices) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of invoices) {
await record.destroy({transaction});
}
});
return invoices;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const invoices = await db.invoices.findByPk(id, options);
await invoices.update({
deletedBy: currentUser.id
}, {
transaction,
});
await invoices.destroy({
transaction
});
return invoices;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const invoices = await db.invoices.findOne(
{ where },
{ transaction },
);
if (!invoices) {
return invoices;
}
const output = invoices.get({plain: true});
output.hotel = await invoices.getHotel({
transaction
});
output.stay_folio = await invoices.getStay_folio({
transaction
});
output.pdf_file = await invoices.getPdf_file({
transaction
});
output.organizations = await invoices.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.hotels,
as: 'hotel',
where: filter.hotel ? {
[Op.or]: [
{ id: { [Op.in]: filter.hotel.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.hotel.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.stay_folios,
as: 'stay_folio',
where: filter.stay_folio ? {
[Op.or]: [
{ id: { [Op.in]: filter.stay_folio.split('|').map(term => Utils.uuid(term)) } },
{
folio_number: {
[Op.or]: filter.stay_folio.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'pdf_file',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.invoice_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'invoices',
'invoice_number',
filter.invoice_number,
),
};
}
if (filter.billing_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'invoices',
'billing_name',
filter.billing_name,
),
};
}
if (filter.billing_address) {
where = {
...where,
[Op.and]: Utils.ilike(
'invoices',
'billing_address',
filter.billing_address,
),
};
}
if (filter.issued_atRange) {
const [start, end] = filter.issued_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
issued_at: {
...where.issued_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
issued_at: {
...where.issued_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.subtotal_amountRange) {
const [start, end] = filter.subtotal_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
subtotal_amount: {
...where.subtotal_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
subtotal_amount: {
...where.subtotal_amount,
[Op.lte]: end,
},
};
}
}
if (filter.tax_amountRange) {
const [start, end] = filter.tax_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
tax_amount: {
...where.tax_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
tax_amount: {
...where.tax_amount,
[Op.lte]: end,
},
};
}
}
if (filter.total_amountRange) {
const [start, end] = filter.total_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
total_amount: {
...where.total_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
total_amount: {
...where.total_amount,
[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.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.invoices.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(
'invoices',
'invoice_number',
query,
),
],
};
}
const records = await db.invoices.findAll({
attributes: [ 'id', 'invoice_number' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['invoice_number', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.invoice_number,
}));
}
};

View File

@ -0,0 +1,722 @@
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 Maintenance_ticketsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const maintenance_tickets = await db.maintenance_tickets.create(
{
id: data.id || undefined,
category: data.category
||
null
,
priority: data.priority
||
null
,
title: data.title
||
null
,
description: data.description
||
null
,
status: data.status
||
null
,
opened_at: data.opened_at
||
null
,
closed_at: data.closed_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await maintenance_tickets.setHotel( data.hotel || null, {
transaction,
});
await maintenance_tickets.setRoom( data.room || null, {
transaction,
});
await maintenance_tickets.setAssigned_staff_profile( data.assigned_staff_profile || null, {
transaction,
});
await maintenance_tickets.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.maintenance_tickets.getTableName(),
belongsToColumn: 'attachments',
belongsToId: maintenance_tickets.id,
},
data.attachments,
options,
);
return maintenance_tickets;
}
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 maintenance_ticketsData = data.map((item, index) => ({
id: item.id || undefined,
category: item.category
||
null
,
priority: item.priority
||
null
,
title: item.title
||
null
,
description: item.description
||
null
,
status: item.status
||
null
,
opened_at: item.opened_at
||
null
,
closed_at: item.closed_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const maintenance_tickets = await db.maintenance_tickets.bulkCreate(maintenance_ticketsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < maintenance_tickets.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.maintenance_tickets.getTableName(),
belongsToColumn: 'attachments',
belongsToId: maintenance_tickets[i].id,
},
data[i].attachments,
options,
);
}
return maintenance_tickets;
}
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 maintenance_tickets = await db.maintenance_tickets.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.category !== undefined) updatePayload.category = data.category;
if (data.priority !== undefined) updatePayload.priority = data.priority;
if (data.title !== undefined) updatePayload.title = data.title;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.opened_at !== undefined) updatePayload.opened_at = data.opened_at;
if (data.closed_at !== undefined) updatePayload.closed_at = data.closed_at;
updatePayload.updatedById = currentUser.id;
await maintenance_tickets.update(updatePayload, {transaction});
if (data.hotel !== undefined) {
await maintenance_tickets.setHotel(
data.hotel,
{ transaction }
);
}
if (data.room !== undefined) {
await maintenance_tickets.setRoom(
data.room,
{ transaction }
);
}
if (data.assigned_staff_profile !== undefined) {
await maintenance_tickets.setAssigned_staff_profile(
data.assigned_staff_profile,
{ transaction }
);
}
if (data.organizations !== undefined) {
await maintenance_tickets.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.maintenance_tickets.getTableName(),
belongsToColumn: 'attachments',
belongsToId: maintenance_tickets.id,
},
data.attachments,
options,
);
return maintenance_tickets;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const maintenance_tickets = await db.maintenance_tickets.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of maintenance_tickets) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of maintenance_tickets) {
await record.destroy({transaction});
}
});
return maintenance_tickets;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const maintenance_tickets = await db.maintenance_tickets.findByPk(id, options);
await maintenance_tickets.update({
deletedBy: currentUser.id
}, {
transaction,
});
await maintenance_tickets.destroy({
transaction
});
return maintenance_tickets;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const maintenance_tickets = await db.maintenance_tickets.findOne(
{ where },
{ transaction },
);
if (!maintenance_tickets) {
return maintenance_tickets;
}
const output = maintenance_tickets.get({plain: true});
output.hotel = await maintenance_tickets.getHotel({
transaction
});
output.room = await maintenance_tickets.getRoom({
transaction
});
output.assigned_staff_profile = await maintenance_tickets.getAssigned_staff_profile({
transaction
});
output.attachments = await maintenance_tickets.getAttachments({
transaction
});
output.organizations = await maintenance_tickets.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.hotels,
as: 'hotel',
where: filter.hotel ? {
[Op.or]: [
{ id: { [Op.in]: filter.hotel.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.hotel.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.rooms,
as: 'room',
where: filter.room ? {
[Op.or]: [
{ id: { [Op.in]: filter.room.split('|').map(term => Utils.uuid(term)) } },
{
room_number: {
[Op.or]: filter.room.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.staff_profiles,
as: 'assigned_staff_profile',
where: filter.assigned_staff_profile ? {
[Op.or]: [
{ id: { [Op.in]: filter.assigned_staff_profile.split('|').map(term => Utils.uuid(term)) } },
{
employee_code: {
[Op.or]: filter.assigned_staff_profile.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'attachments',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.title) {
where = {
...where,
[Op.and]: Utils.ilike(
'maintenance_tickets',
'title',
filter.title,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'maintenance_tickets',
'description',
filter.description,
),
};
}
if (filter.opened_atRange) {
const [start, end] = filter.opened_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
opened_at: {
...where.opened_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
opened_at: {
...where.opened_at,
[Op.lte]: end,
},
};
}
}
if (filter.closed_atRange) {
const [start, end] = filter.closed_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
closed_at: {
...where.closed_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
closed_at: {
...where.closed_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.category) {
where = {
...where,
category: filter.category,
};
}
if (filter.priority) {
where = {
...where,
priority: filter.priority,
};
}
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.maintenance_tickets.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(
'maintenance_tickets',
'title',
query,
),
],
};
}
const records = await db.maintenance_tickets.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,752 @@
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
,
template_type: data.template_type
||
null
,
status: data.status
||
null
,
scheduled_at: data.scheduled_at
||
null
,
sent_at: data.sent_at
||
null
,
to_address: data.to_address
||
null
,
subject: data.subject
||
null
,
body: data.body
||
null
,
provider_message_reference: data.provider_message_reference
||
null
,
error_message: data.error_message
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await notifications.setHotel( data.hotel || null, {
transaction,
});
await notifications.setReservation( data.reservation || null, {
transaction,
});
await notifications.setGuest( data.guest || 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
,
template_type: item.template_type
||
null
,
status: item.status
||
null
,
scheduled_at: item.scheduled_at
||
null
,
sent_at: item.sent_at
||
null
,
to_address: item.to_address
||
null
,
subject: item.subject
||
null
,
body: item.body
||
null
,
provider_message_reference: item.provider_message_reference
||
null
,
error_message: item.error_message
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const 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.template_type !== undefined) updatePayload.template_type = data.template_type;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.scheduled_at !== undefined) updatePayload.scheduled_at = data.scheduled_at;
if (data.sent_at !== undefined) updatePayload.sent_at = data.sent_at;
if (data.to_address !== undefined) updatePayload.to_address = data.to_address;
if (data.subject !== undefined) updatePayload.subject = data.subject;
if (data.body !== undefined) updatePayload.body = data.body;
if (data.provider_message_reference !== undefined) updatePayload.provider_message_reference = data.provider_message_reference;
if (data.error_message !== undefined) updatePayload.error_message = data.error_message;
updatePayload.updatedById = currentUser.id;
await notifications.update(updatePayload, {transaction});
if (data.hotel !== undefined) {
await notifications.setHotel(
data.hotel,
{ transaction }
);
}
if (data.reservation !== undefined) {
await notifications.setReservation(
data.reservation,
{ transaction }
);
}
if (data.guest !== undefined) {
await notifications.setGuest(
data.guest,
{ 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.hotel = await notifications.getHotel({
transaction
});
output.reservation = await notifications.getReservation({
transaction
});
output.guest = await notifications.getGuest({
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.hotels,
as: 'hotel',
where: filter.hotel ? {
[Op.or]: [
{ id: { [Op.in]: filter.hotel.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.hotel.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_number: {
[Op.or]: filter.reservation.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.guests,
as: 'guest',
where: filter.guest ? {
[Op.or]: [
{ id: { [Op.in]: filter.guest.split('|').map(term => Utils.uuid(term)) } },
{
last_name: {
[Op.or]: filter.guest.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.to_address) {
where = {
...where,
[Op.and]: Utils.ilike(
'notifications',
'to_address',
filter.to_address,
),
};
}
if (filter.subject) {
where = {
...where,
[Op.and]: Utils.ilike(
'notifications',
'subject',
filter.subject,
),
};
}
if (filter.body) {
where = {
...where,
[Op.and]: Utils.ilike(
'notifications',
'body',
filter.body,
),
};
}
if (filter.provider_message_reference) {
where = {
...where,
[Op.and]: Utils.ilike(
'notifications',
'provider_message_reference',
filter.provider_message_reference,
),
};
}
if (filter.error_message) {
where = {
...where,
[Op.and]: Utils.ilike(
'notifications',
'error_message',
filter.error_message,
),
};
}
if (filter.scheduled_atRange) {
const [start, end] = filter.scheduled_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
scheduled_at: {
...where.scheduled_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
scheduled_at: {
...where.scheduled_at,
[Op.lte]: end,
},
};
}
}
if (filter.sent_atRange) {
const [start, end] = filter.sent_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sent_at: {
...where.sent_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sent_at: {
...where.sent_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.channel) {
where = {
...where,
channel: filter.channel,
};
}
if (filter.template_type) {
where = {
...where,
template_type: filter.template_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.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',
'subject',
query,
),
],
};
}
const records = await db.notifications.findAll({
attributes: [ 'id', 'subject' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['subject', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.subject,
}));
}
};

View File

@ -0,0 +1,486 @@
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.hotels_organizations = await organizations.getHotels_organizations({
transaction
});
output.departments_organizations = await organizations.getDepartments_organizations({
transaction
});
output.staff_profiles_organizations = await organizations.getStaff_profiles_organizations({
transaction
});
output.shifts_organizations = await organizations.getShifts_organizations({
transaction
});
output.room_types_organizations = await organizations.getRoom_types_organizations({
transaction
});
output.rooms_organizations = await organizations.getRooms_organizations({
transaction
});
output.guests_organizations = await organizations.getGuests_organizations({
transaction
});
output.guest_documents_organizations = await organizations.getGuest_documents_organizations({
transaction
});
output.rate_plans_organizations = await organizations.getRate_plans_organizations({
transaction
});
output.seasonal_rates_organizations = await organizations.getSeasonal_rates_organizations({
transaction
});
output.dynamic_pricing_rules_organizations = await organizations.getDynamic_pricing_rules_organizations({
transaction
});
output.sales_channels_organizations = await organizations.getSales_channels_organizations({
transaction
});
output.ota_connections_organizations = await organizations.getOta_connections_organizations({
transaction
});
output.reservations_organizations = await organizations.getReservations_organizations({
transaction
});
output.reservation_guests_organizations = await organizations.getReservation_guests_organizations({
transaction
});
output.stay_folios_organizations = await organizations.getStay_folios_organizations({
transaction
});
output.folio_items_organizations = await organizations.getFolio_items_organizations({
transaction
});
output.payments_organizations = await organizations.getPayments_organizations({
transaction
});
output.refunds_organizations = await organizations.getRefunds_organizations({
transaction
});
output.invoices_organizations = await organizations.getInvoices_organizations({
transaction
});
output.housekeeping_tasks_organizations = await organizations.getHousekeeping_tasks_organizations({
transaction
});
output.maintenance_tickets_organizations = await organizations.getMaintenance_tickets_organizations({
transaction
});
output.notifications_organizations = await organizations.getNotifications_organizations({
transaction
});
output.booking_widgets_organizations = await organizations.getBooking_widgets_organizations({
transaction
});
output.subscriptions_organizations = await organizations.getSubscriptions_organizations({
transaction
});
output.audit_logs_organizations = await organizations.getAudit_logs_organizations({
transaction
});
output.daily_snapshots_organizations = await organizations.getDaily_snapshots_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,630 @@
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 Ota_connectionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const ota_connections = await db.ota_connections.create(
{
id: data.id || undefined,
provider: data.provider
||
null
,
account_identifier: data.account_identifier
||
null
,
api_key_reference: data.api_key_reference
||
null
,
inventory_sync_enabled: data.inventory_sync_enabled
||
false
,
rate_sync_enabled: data.rate_sync_enabled
||
false
,
last_sync_at: data.last_sync_at
||
null
,
sync_status: data.sync_status
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await ota_connections.setHotel( data.hotel || null, {
transaction,
});
await ota_connections.setSales_channel( data.sales_channel || null, {
transaction,
});
await ota_connections.setOrganizations( data.organizations || null, {
transaction,
});
return ota_connections;
}
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 ota_connectionsData = data.map((item, index) => ({
id: item.id || undefined,
provider: item.provider
||
null
,
account_identifier: item.account_identifier
||
null
,
api_key_reference: item.api_key_reference
||
null
,
inventory_sync_enabled: item.inventory_sync_enabled
||
false
,
rate_sync_enabled: item.rate_sync_enabled
||
false
,
last_sync_at: item.last_sync_at
||
null
,
sync_status: item.sync_status
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const ota_connections = await db.ota_connections.bulkCreate(ota_connectionsData, { transaction });
// For each item created, replace relation files
return ota_connections;
}
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 ota_connections = await db.ota_connections.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.provider !== undefined) updatePayload.provider = data.provider;
if (data.account_identifier !== undefined) updatePayload.account_identifier = data.account_identifier;
if (data.api_key_reference !== undefined) updatePayload.api_key_reference = data.api_key_reference;
if (data.inventory_sync_enabled !== undefined) updatePayload.inventory_sync_enabled = data.inventory_sync_enabled;
if (data.rate_sync_enabled !== undefined) updatePayload.rate_sync_enabled = data.rate_sync_enabled;
if (data.last_sync_at !== undefined) updatePayload.last_sync_at = data.last_sync_at;
if (data.sync_status !== undefined) updatePayload.sync_status = data.sync_status;
updatePayload.updatedById = currentUser.id;
await ota_connections.update(updatePayload, {transaction});
if (data.hotel !== undefined) {
await ota_connections.setHotel(
data.hotel,
{ transaction }
);
}
if (data.sales_channel !== undefined) {
await ota_connections.setSales_channel(
data.sales_channel,
{ transaction }
);
}
if (data.organizations !== undefined) {
await ota_connections.setOrganizations(
data.organizations,
{ transaction }
);
}
return ota_connections;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const ota_connections = await db.ota_connections.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of ota_connections) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of ota_connections) {
await record.destroy({transaction});
}
});
return ota_connections;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const ota_connections = await db.ota_connections.findByPk(id, options);
await ota_connections.update({
deletedBy: currentUser.id
}, {
transaction,
});
await ota_connections.destroy({
transaction
});
return ota_connections;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const ota_connections = await db.ota_connections.findOne(
{ where },
{ transaction },
);
if (!ota_connections) {
return ota_connections;
}
const output = ota_connections.get({plain: true});
output.hotel = await ota_connections.getHotel({
transaction
});
output.sales_channel = await ota_connections.getSales_channel({
transaction
});
output.organizations = await ota_connections.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.hotels,
as: 'hotel',
where: filter.hotel ? {
[Op.or]: [
{ id: { [Op.in]: filter.hotel.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.hotel.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.sales_channels,
as: 'sales_channel',
where: filter.sales_channel ? {
[Op.or]: [
{ id: { [Op.in]: filter.sales_channel.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.sales_channel.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.account_identifier) {
where = {
...where,
[Op.and]: Utils.ilike(
'ota_connections',
'account_identifier',
filter.account_identifier,
),
};
}
if (filter.api_key_reference) {
where = {
...where,
[Op.and]: Utils.ilike(
'ota_connections',
'api_key_reference',
filter.api_key_reference,
),
};
}
if (filter.last_sync_atRange) {
const [start, end] = filter.last_sync_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
last_sync_at: {
...where.last_sync_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
last_sync_at: {
...where.last_sync_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.provider) {
where = {
...where,
provider: filter.provider,
};
}
if (filter.inventory_sync_enabled) {
where = {
...where,
inventory_sync_enabled: filter.inventory_sync_enabled,
};
}
if (filter.rate_sync_enabled) {
where = {
...where,
rate_sync_enabled: filter.rate_sync_enabled,
};
}
if (filter.sync_status) {
where = {
...where,
sync_status: filter.sync_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.ota_connections.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(
'ota_connections',
'account_identifier',
query,
),
],
};
}
const records = await db.ota_connections.findAll({
attributes: [ 'id', 'account_identifier' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['account_identifier', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.account_identifier,
}));
}
};

View File

@ -0,0 +1,712 @@
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,
method: data.method
||
null
,
amount: data.amount
||
null
,
status: data.status
||
null
,
paid_at: data.paid_at
||
null
,
stripe_payment_intent_reference: data.stripe_payment_intent_reference
||
null
,
stripe_charge_reference: data.stripe_charge_reference
||
null
,
receipt_number: data.receipt_number
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await payments.setHotel( data.hotel || null, {
transaction,
});
await payments.setStay_folio( data.stay_folio || null, {
transaction,
});
await payments.setReservation( data.reservation || null, {
transaction,
});
await payments.setOrganizations( data.organizations || null, {
transaction,
});
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,
method: item.method
||
null
,
amount: item.amount
||
null
,
status: item.status
||
null
,
paid_at: item.paid_at
||
null
,
stripe_payment_intent_reference: item.stripe_payment_intent_reference
||
null
,
stripe_charge_reference: item.stripe_charge_reference
||
null
,
receipt_number: item.receipt_number
||
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
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.method !== undefined) updatePayload.method = data.method;
if (data.amount !== undefined) updatePayload.amount = data.amount;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.paid_at !== undefined) updatePayload.paid_at = data.paid_at;
if (data.stripe_payment_intent_reference !== undefined) updatePayload.stripe_payment_intent_reference = data.stripe_payment_intent_reference;
if (data.stripe_charge_reference !== undefined) updatePayload.stripe_charge_reference = data.stripe_charge_reference;
if (data.receipt_number !== undefined) updatePayload.receipt_number = data.receipt_number;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await payments.update(updatePayload, {transaction});
if (data.hotel !== undefined) {
await payments.setHotel(
data.hotel,
{ transaction }
);
}
if (data.stay_folio !== undefined) {
await payments.setStay_folio(
data.stay_folio,
{ transaction }
);
}
if (data.reservation !== undefined) {
await payments.setReservation(
data.reservation,
{ transaction }
);
}
if (data.organizations !== undefined) {
await payments.setOrganizations(
data.organizations,
{ transaction }
);
}
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.refunds_payment = await payments.getRefunds_payment({
transaction
});
output.hotel = await payments.getHotel({
transaction
});
output.stay_folio = await payments.getStay_folio({
transaction
});
output.reservation = await payments.getReservation({
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.hotels,
as: 'hotel',
where: filter.hotel ? {
[Op.or]: [
{ id: { [Op.in]: filter.hotel.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.hotel.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.stay_folios,
as: 'stay_folio',
where: filter.stay_folio ? {
[Op.or]: [
{ id: { [Op.in]: filter.stay_folio.split('|').map(term => Utils.uuid(term)) } },
{
folio_number: {
[Op.or]: filter.stay_folio.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_number: {
[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.stripe_payment_intent_reference) {
where = {
...where,
[Op.and]: Utils.ilike(
'payments',
'stripe_payment_intent_reference',
filter.stripe_payment_intent_reference,
),
};
}
if (filter.stripe_charge_reference) {
where = {
...where,
[Op.and]: Utils.ilike(
'payments',
'stripe_charge_reference',
filter.stripe_charge_reference,
),
};
}
if (filter.receipt_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'payments',
'receipt_number',
filter.receipt_number,
),
};
}
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.method) {
where = {
...where,
method: filter.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',
'receipt_number',
query,
),
],
};
}
const records = await db.payments.findAll({
attributes: [ 'id', 'receipt_number' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['receipt_number', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.receipt_number,
}));
}
};

View File

@ -0,0 +1,360 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class PermissionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const permissions = await db.permissions.create(
{
id: data.id || undefined,
name: data.name
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return permissions;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const permissionsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const permissions = await db.permissions.bulkCreate(permissionsData, { transaction });
// For each item created, replace relation files
return permissions;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const 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,659 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Rate_plansDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const rate_plans = await db.rate_plans.create(
{
id: data.id || undefined,
name: data.name
||
null
,
plan_type: data.plan_type
||
null
,
refundable: data.refundable
||
false
,
min_nights: data.min_nights
||
null
,
max_nights: data.max_nights
||
null
,
deposit_percent: data.deposit_percent
||
null
,
cancellation_policy: data.cancellation_policy
||
null
,
active: data.active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await rate_plans.setHotel( data.hotel || null, {
transaction,
});
await rate_plans.setOrganizations( data.organizations || null, {
transaction,
});
return rate_plans;
}
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 rate_plansData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
plan_type: item.plan_type
||
null
,
refundable: item.refundable
||
false
,
min_nights: item.min_nights
||
null
,
max_nights: item.max_nights
||
null
,
deposit_percent: item.deposit_percent
||
null
,
cancellation_policy: item.cancellation_policy
||
null
,
active: item.active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const rate_plans = await db.rate_plans.bulkCreate(rate_plansData, { transaction });
// For each item created, replace relation files
return rate_plans;
}
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 rate_plans = await db.rate_plans.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.plan_type !== undefined) updatePayload.plan_type = data.plan_type;
if (data.refundable !== undefined) updatePayload.refundable = data.refundable;
if (data.min_nights !== undefined) updatePayload.min_nights = data.min_nights;
if (data.max_nights !== undefined) updatePayload.max_nights = data.max_nights;
if (data.deposit_percent !== undefined) updatePayload.deposit_percent = data.deposit_percent;
if (data.cancellation_policy !== undefined) updatePayload.cancellation_policy = data.cancellation_policy;
if (data.active !== undefined) updatePayload.active = data.active;
updatePayload.updatedById = currentUser.id;
await rate_plans.update(updatePayload, {transaction});
if (data.hotel !== undefined) {
await rate_plans.setHotel(
data.hotel,
{ transaction }
);
}
if (data.organizations !== undefined) {
await rate_plans.setOrganizations(
data.organizations,
{ transaction }
);
}
return rate_plans;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const rate_plans = await db.rate_plans.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of rate_plans) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of rate_plans) {
await record.destroy({transaction});
}
});
return rate_plans;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const rate_plans = await db.rate_plans.findByPk(id, options);
await rate_plans.update({
deletedBy: currentUser.id
}, {
transaction,
});
await rate_plans.destroy({
transaction
});
return rate_plans;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const rate_plans = await db.rate_plans.findOne(
{ where },
{ transaction },
);
if (!rate_plans) {
return rate_plans;
}
const output = rate_plans.get({plain: true});
output.seasonal_rates_rate_plan = await rate_plans.getSeasonal_rates_rate_plan({
transaction
});
output.dynamic_pricing_rules_rate_plan = await rate_plans.getDynamic_pricing_rules_rate_plan({
transaction
});
output.reservations_rate_plan = await rate_plans.getReservations_rate_plan({
transaction
});
output.hotel = await rate_plans.getHotel({
transaction
});
output.organizations = await rate_plans.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.hotels,
as: 'hotel',
where: filter.hotel ? {
[Op.or]: [
{ id: { [Op.in]: filter.hotel.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.hotel.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(
'rate_plans',
'name',
filter.name,
),
};
}
if (filter.cancellation_policy) {
where = {
...where,
[Op.and]: Utils.ilike(
'rate_plans',
'cancellation_policy',
filter.cancellation_policy,
),
};
}
if (filter.min_nightsRange) {
const [start, end] = filter.min_nightsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
min_nights: {
...where.min_nights,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
min_nights: {
...where.min_nights,
[Op.lte]: end,
},
};
}
}
if (filter.max_nightsRange) {
const [start, end] = filter.max_nightsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
max_nights: {
...where.max_nights,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
max_nights: {
...where.max_nights,
[Op.lte]: end,
},
};
}
}
if (filter.deposit_percentRange) {
const [start, end] = filter.deposit_percentRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
deposit_percent: {
...where.deposit_percent,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
deposit_percent: {
...where.deposit_percent,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.plan_type) {
where = {
...where,
plan_type: filter.plan_type,
};
}
if (filter.refundable) {
where = {
...where,
refundable: filter.refundable,
};
}
if (filter.active) {
where = {
...where,
active: filter.active,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.rate_plans.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(
'rate_plans',
'name',
query,
),
],
};
}
const records = await db.rate_plans.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,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 RefundsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const refunds = await db.refunds.create(
{
id: data.id || undefined,
amount: data.amount
||
null
,
status: data.status
||
null
,
refunded_at: data.refunded_at
||
null
,
stripe_refund_reference: data.stripe_refund_reference
||
null
,
reason: data.reason
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await refunds.setHotel( data.hotel || null, {
transaction,
});
await refunds.setPayment( data.payment || null, {
transaction,
});
await refunds.setOrganizations( data.organizations || null, {
transaction,
});
return refunds;
}
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 refundsData = data.map((item, index) => ({
id: item.id || undefined,
amount: item.amount
||
null
,
status: item.status
||
null
,
refunded_at: item.refunded_at
||
null
,
stripe_refund_reference: item.stripe_refund_reference
||
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 refunds = await db.refunds.bulkCreate(refundsData, { transaction });
// For each item created, replace relation files
return refunds;
}
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 refunds = await db.refunds.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.amount !== undefined) updatePayload.amount = data.amount;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.refunded_at !== undefined) updatePayload.refunded_at = data.refunded_at;
if (data.stripe_refund_reference !== undefined) updatePayload.stripe_refund_reference = data.stripe_refund_reference;
if (data.reason !== undefined) updatePayload.reason = data.reason;
updatePayload.updatedById = currentUser.id;
await refunds.update(updatePayload, {transaction});
if (data.hotel !== undefined) {
await refunds.setHotel(
data.hotel,
{ transaction }
);
}
if (data.payment !== undefined) {
await refunds.setPayment(
data.payment,
{ transaction }
);
}
if (data.organizations !== undefined) {
await refunds.setOrganizations(
data.organizations,
{ transaction }
);
}
return refunds;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const refunds = await db.refunds.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of refunds) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of refunds) {
await record.destroy({transaction});
}
});
return refunds;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const refunds = await db.refunds.findByPk(id, options);
await refunds.update({
deletedBy: currentUser.id
}, {
transaction,
});
await refunds.destroy({
transaction
});
return refunds;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const refunds = await db.refunds.findOne(
{ where },
{ transaction },
);
if (!refunds) {
return refunds;
}
const output = refunds.get({plain: true});
output.hotel = await refunds.getHotel({
transaction
});
output.payment = await refunds.getPayment({
transaction
});
output.organizations = await refunds.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.hotels,
as: 'hotel',
where: filter.hotel ? {
[Op.or]: [
{ id: { [Op.in]: filter.hotel.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.hotel.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.payments,
as: 'payment',
where: filter.payment ? {
[Op.or]: [
{ id: { [Op.in]: filter.payment.split('|').map(term => Utils.uuid(term)) } },
{
receipt_number: {
[Op.or]: filter.payment.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.stripe_refund_reference) {
where = {
...where,
[Op.and]: Utils.ilike(
'refunds',
'stripe_refund_reference',
filter.stripe_refund_reference,
),
};
}
if (filter.reason) {
where = {
...where,
[Op.and]: Utils.ilike(
'refunds',
'reason',
filter.reason,
),
};
}
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.refunded_atRange) {
const [start, end] = filter.refunded_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
refunded_at: {
...where.refunded_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
refunded_at: {
...where.refunded_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.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.refunds.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(
'refunds',
'stripe_refund_reference',
query,
),
],
};
}
const records = await db.refunds.findAll({
attributes: [ 'id', 'stripe_refund_reference' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['stripe_refund_reference', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.stripe_refund_reference,
}));
}
};

View File

@ -0,0 +1,540 @@
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,
guest_role: data.guest_role
||
null
,
is_primary: data.is_primary
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await reservation_guests.setHotel( data.hotel || null, {
transaction,
});
await reservation_guests.setReservation( data.reservation || null, {
transaction,
});
await reservation_guests.setGuest( data.guest || 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,
guest_role: item.guest_role
||
null
,
is_primary: item.is_primary
||
false
,
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.guest_role !== undefined) updatePayload.guest_role = data.guest_role;
if (data.is_primary !== undefined) updatePayload.is_primary = data.is_primary;
updatePayload.updatedById = currentUser.id;
await reservation_guests.update(updatePayload, {transaction});
if (data.hotel !== undefined) {
await reservation_guests.setHotel(
data.hotel,
{ transaction }
);
}
if (data.reservation !== undefined) {
await reservation_guests.setReservation(
data.reservation,
{ transaction }
);
}
if (data.guest !== undefined) {
await reservation_guests.setGuest(
data.guest,
{ 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.hotel = await reservation_guests.getHotel({
transaction
});
output.reservation = await reservation_guests.getReservation({
transaction
});
output.guest = await reservation_guests.getGuest({
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.hotels,
as: 'hotel',
where: filter.hotel ? {
[Op.or]: [
{ id: { [Op.in]: filter.hotel.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.hotel.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_number: {
[Op.or]: filter.reservation.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.guests,
as: 'guest',
where: filter.guest ? {
[Op.or]: [
{ id: { [Op.in]: filter.guest.split('|').map(term => Utils.uuid(term)) } },
{
last_name: {
[Op.or]: filter.guest.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.guest_role) {
where = {
...where,
guest_role: filter.guest_role,
};
}
if (filter.is_primary) {
where = {
...where,
is_primary: filter.is_primary,
};
}
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',
'guest_role',
query,
),
],
};
}
const records = await db.reservation_guests.findAll({
attributes: [ 'id', 'guest_role' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['guest_role', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.guest_role,
}));
}
};

File diff suppressed because it is too large Load Diff

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

@ -0,0 +1,462 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const config = require('../../config');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class RolesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const roles = await db.roles.create(
{
id: data.id || undefined,
name: data.name
||
null
,
role_customization: data.role_customization
||
null
,
globalAccess: data.globalAccess
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await roles.setPermissions(data.permissions || [], {
transaction,
});
return roles;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const rolesData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
role_customization: item.role_customization
||
null
,
globalAccess: item.globalAccess
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const roles = await db.roles.bulkCreate(rolesData, { transaction });
// For each item created, replace relation files
return roles;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const roles = await db.roles.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.role_customization !== undefined) updatePayload.role_customization = data.role_customization;
if (data.globalAccess !== undefined) updatePayload.globalAccess = data.globalAccess;
updatePayload.updatedById = currentUser.id;
await roles.update(updatePayload, {transaction});
if (data.permissions !== undefined) {
await roles.setPermissions(data.permissions, { transaction });
}
return roles;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const roles = await db.roles.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of roles) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of roles) {
await record.destroy({transaction});
}
});
return roles;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const roles = await db.roles.findByPk(id, options);
await roles.update({
deletedBy: currentUser.id
}, {
transaction,
});
await roles.destroy({
transaction
});
return roles;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const roles = await db.roles.findOne(
{ where },
{ transaction },
);
if (!roles) {
return roles;
}
const output = roles.get({plain: true});
output.users_app_role = await roles.getUsers_app_role({
transaction
});
output.permissions = await roles.getPermissions({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.permissions,
as: 'permissions',
required: false,
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'roles',
'name',
filter.name,
),
};
}
if (filter.role_customization) {
where = {
...where,
[Op.and]: Utils.ilike(
'roles',
'role_customization',
filter.role_customization,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.globalAccess) {
where = {
...where,
globalAccess: filter.globalAccess,
};
}
if (filter.permissions) {
const searchTerms = filter.permissions.split('|');
include = [
{
model: db.permissions,
as: 'permissions_filter',
required: searchTerms.length > 0,
where: searchTerms.length > 0 ? {
[Op.or]: [
{ id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
}
}
]
} : undefined
},
...include,
]
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (!globalAccess) {
where = { name: { [Op.ne]: config.roles.super_admin } };
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.roles.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess,) {
let where = {};
if (!globalAccess) {
where = { name: { [Op.ne]: config.roles.super_admin } };
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'roles',
'name',
query,
),
],
};
}
const records = await db.roles.findAll({
attributes: [ 'id', 'name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.name,
}));
}
};

View File

@ -0,0 +1,663 @@
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 Room_typesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const room_types = await db.room_types.create(
{
id: data.id || undefined,
name: data.name
||
null
,
description: data.description
||
null
,
capacity_adults: data.capacity_adults
||
null
,
capacity_children: data.capacity_children
||
null
,
base_rate: data.base_rate
||
null
,
active: data.active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await room_types.setHotel( data.hotel || null, {
transaction,
});
await room_types.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.room_types.getTableName(),
belongsToColumn: 'photos',
belongsToId: room_types.id,
},
data.photos,
options,
);
return room_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 room_typesData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
description: item.description
||
null
,
capacity_adults: item.capacity_adults
||
null
,
capacity_children: item.capacity_children
||
null
,
base_rate: item.base_rate
||
null
,
active: item.active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const room_types = await db.room_types.bulkCreate(room_typesData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < room_types.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.room_types.getTableName(),
belongsToColumn: 'photos',
belongsToId: room_types[i].id,
},
data[i].photos,
options,
);
}
return room_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 room_types = await db.room_types.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.capacity_adults !== undefined) updatePayload.capacity_adults = data.capacity_adults;
if (data.capacity_children !== undefined) updatePayload.capacity_children = data.capacity_children;
if (data.base_rate !== undefined) updatePayload.base_rate = data.base_rate;
if (data.active !== undefined) updatePayload.active = data.active;
updatePayload.updatedById = currentUser.id;
await room_types.update(updatePayload, {transaction});
if (data.hotel !== undefined) {
await room_types.setHotel(
data.hotel,
{ transaction }
);
}
if (data.organizations !== undefined) {
await room_types.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.room_types.getTableName(),
belongsToColumn: 'photos',
belongsToId: room_types.id,
},
data.photos,
options,
);
return room_types;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const room_types = await db.room_types.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of room_types) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of room_types) {
await record.destroy({transaction});
}
});
return room_types;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const room_types = await db.room_types.findByPk(id, options);
await room_types.update({
deletedBy: currentUser.id
}, {
transaction,
});
await room_types.destroy({
transaction
});
return room_types;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const room_types = await db.room_types.findOne(
{ where },
{ transaction },
);
if (!room_types) {
return room_types;
}
const output = room_types.get({plain: true});
output.rooms_room_type = await room_types.getRooms_room_type({
transaction
});
output.seasonal_rates_room_type = await room_types.getSeasonal_rates_room_type({
transaction
});
output.dynamic_pricing_rules_room_type = await room_types.getDynamic_pricing_rules_room_type({
transaction
});
output.reservations_room_type = await room_types.getReservations_room_type({
transaction
});
output.hotel = await room_types.getHotel({
transaction
});
output.photos = await room_types.getPhotos({
transaction
});
output.organizations = await room_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.hotels,
as: 'hotel',
where: filter.hotel ? {
[Op.or]: [
{ id: { [Op.in]: filter.hotel.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.hotel.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'photos',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'room_types',
'name',
filter.name,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'room_types',
'description',
filter.description,
),
};
}
if (filter.capacity_adultsRange) {
const [start, end] = filter.capacity_adultsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
capacity_adults: {
...where.capacity_adults,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
capacity_adults: {
...where.capacity_adults,
[Op.lte]: end,
},
};
}
}
if (filter.capacity_childrenRange) {
const [start, end] = filter.capacity_childrenRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
capacity_children: {
...where.capacity_children,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
capacity_children: {
...where.capacity_children,
[Op.lte]: end,
},
};
}
}
if (filter.base_rateRange) {
const [start, end] = filter.base_rateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
base_rate: {
...where.base_rate,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
base_rate: {
...where.base_rate,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.active) {
where = {
...where,
active: filter.active,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.room_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(
'room_types',
'name',
query,
),
],
};
}
const records = await db.room_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,
}));
}
};

587
backend/src/db/api/rooms.js Normal file
View File

@ -0,0 +1,587 @@
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 RoomsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const rooms = await db.rooms.create(
{
id: data.id || undefined,
room_number: data.room_number
||
null
,
floor: data.floor
||
null
,
status: data.status
||
null
,
notes: data.notes
||
null
,
active: data.active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await rooms.setHotel( data.hotel || null, {
transaction,
});
await rooms.setRoom_type( data.room_type || null, {
transaction,
});
await rooms.setOrganizations( data.organizations || null, {
transaction,
});
return rooms;
}
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 roomsData = data.map((item, index) => ({
id: item.id || undefined,
room_number: item.room_number
||
null
,
floor: item.floor
||
null
,
status: item.status
||
null
,
notes: item.notes
||
null
,
active: item.active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const rooms = await db.rooms.bulkCreate(roomsData, { transaction });
// For each item created, replace relation files
return rooms;
}
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 rooms = await db.rooms.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.room_number !== undefined) updatePayload.room_number = data.room_number;
if (data.floor !== undefined) updatePayload.floor = data.floor;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.notes !== undefined) updatePayload.notes = data.notes;
if (data.active !== undefined) updatePayload.active = data.active;
updatePayload.updatedById = currentUser.id;
await rooms.update(updatePayload, {transaction});
if (data.hotel !== undefined) {
await rooms.setHotel(
data.hotel,
{ transaction }
);
}
if (data.room_type !== undefined) {
await rooms.setRoom_type(
data.room_type,
{ transaction }
);
}
if (data.organizations !== undefined) {
await rooms.setOrganizations(
data.organizations,
{ transaction }
);
}
return rooms;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const rooms = await db.rooms.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of rooms) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of rooms) {
await record.destroy({transaction});
}
});
return rooms;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const rooms = await db.rooms.findByPk(id, options);
await rooms.update({
deletedBy: currentUser.id
}, {
transaction,
});
await rooms.destroy({
transaction
});
return rooms;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const rooms = await db.rooms.findOne(
{ where },
{ transaction },
);
if (!rooms) {
return rooms;
}
const output = rooms.get({plain: true});
output.reservations_room = await rooms.getReservations_room({
transaction
});
output.housekeeping_tasks_room = await rooms.getHousekeeping_tasks_room({
transaction
});
output.maintenance_tickets_room = await rooms.getMaintenance_tickets_room({
transaction
});
output.hotel = await rooms.getHotel({
transaction
});
output.room_type = await rooms.getRoom_type({
transaction
});
output.organizations = await rooms.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.hotels,
as: 'hotel',
where: filter.hotel ? {
[Op.or]: [
{ id: { [Op.in]: filter.hotel.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.hotel.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.room_types,
as: 'room_type',
where: filter.room_type ? {
[Op.or]: [
{ id: { [Op.in]: filter.room_type.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.room_type.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.room_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'rooms',
'room_number',
filter.room_number,
),
};
}
if (filter.floor) {
where = {
...where,
[Op.and]: Utils.ilike(
'rooms',
'floor',
filter.floor,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'rooms',
'notes',
filter.notes,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.active) {
where = {
...where,
active: filter.active,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.rooms.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(
'rooms',
'room_number',
query,
),
],
};
}
const records = await db.rooms.findAll({
attributes: [ 'id', 'room_number' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['room_number', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.room_number,
}));
}
};

View File

@ -0,0 +1,522 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Sales_channelsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const sales_channels = await db.sales_channels.create(
{
id: data.id || undefined,
channel_type: data.channel_type
||
null
,
name: data.name
||
null
,
external_reference: data.external_reference
||
null
,
active: data.active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await sales_channels.setHotel( data.hotel || null, {
transaction,
});
await sales_channels.setOrganizations( data.organizations || null, {
transaction,
});
return sales_channels;
}
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 sales_channelsData = data.map((item, index) => ({
id: item.id || undefined,
channel_type: item.channel_type
||
null
,
name: item.name
||
null
,
external_reference: item.external_reference
||
null
,
active: item.active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const sales_channels = await db.sales_channels.bulkCreate(sales_channelsData, { transaction });
// For each item created, replace relation files
return sales_channels;
}
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 sales_channels = await db.sales_channels.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.channel_type !== undefined) updatePayload.channel_type = data.channel_type;
if (data.name !== undefined) updatePayload.name = data.name;
if (data.external_reference !== undefined) updatePayload.external_reference = data.external_reference;
if (data.active !== undefined) updatePayload.active = data.active;
updatePayload.updatedById = currentUser.id;
await sales_channels.update(updatePayload, {transaction});
if (data.hotel !== undefined) {
await sales_channels.setHotel(
data.hotel,
{ transaction }
);
}
if (data.organizations !== undefined) {
await sales_channels.setOrganizations(
data.organizations,
{ transaction }
);
}
return sales_channels;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const sales_channels = await db.sales_channels.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of sales_channels) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of sales_channels) {
await record.destroy({transaction});
}
});
return sales_channels;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const sales_channels = await db.sales_channels.findByPk(id, options);
await sales_channels.update({
deletedBy: currentUser.id
}, {
transaction,
});
await sales_channels.destroy({
transaction
});
return sales_channels;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const sales_channels = await db.sales_channels.findOne(
{ where },
{ transaction },
);
if (!sales_channels) {
return sales_channels;
}
const output = sales_channels.get({plain: true});
output.ota_connections_sales_channel = await sales_channels.getOta_connections_sales_channel({
transaction
});
output.reservations_sales_channel = await sales_channels.getReservations_sales_channel({
transaction
});
output.hotel = await sales_channels.getHotel({
transaction
});
output.organizations = await sales_channels.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.hotels,
as: 'hotel',
where: filter.hotel ? {
[Op.or]: [
{ id: { [Op.in]: filter.hotel.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.hotel.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(
'sales_channels',
'name',
filter.name,
),
};
}
if (filter.external_reference) {
where = {
...where,
[Op.and]: Utils.ilike(
'sales_channels',
'external_reference',
filter.external_reference,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.channel_type) {
where = {
...where,
channel_type: filter.channel_type,
};
}
if (filter.active) {
where = {
...where,
active: filter.active,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.sales_channels.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(
'sales_channels',
'name',
query,
),
],
};
}
const records = await db.sales_channels.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,706 @@
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 Seasonal_ratesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const seasonal_rates = await db.seasonal_rates.create(
{
id: data.id || undefined,
start_date: data.start_date
||
null
,
end_date: data.end_date
||
null
,
nightly_rate: data.nightly_rate
||
null
,
pricing_mode: data.pricing_mode
||
null
,
delta_amount: data.delta_amount
||
null
,
active: data.active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await seasonal_rates.setHotel( data.hotel || null, {
transaction,
});
await seasonal_rates.setRoom_type( data.room_type || null, {
transaction,
});
await seasonal_rates.setRate_plan( data.rate_plan || null, {
transaction,
});
await seasonal_rates.setOrganizations( data.organizations || null, {
transaction,
});
return seasonal_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 seasonal_ratesData = data.map((item, index) => ({
id: item.id || undefined,
start_date: item.start_date
||
null
,
end_date: item.end_date
||
null
,
nightly_rate: item.nightly_rate
||
null
,
pricing_mode: item.pricing_mode
||
null
,
delta_amount: item.delta_amount
||
null
,
active: item.active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const seasonal_rates = await db.seasonal_rates.bulkCreate(seasonal_ratesData, { transaction });
// For each item created, replace relation files
return seasonal_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 seasonal_rates = await db.seasonal_rates.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.start_date !== undefined) updatePayload.start_date = data.start_date;
if (data.end_date !== undefined) updatePayload.end_date = data.end_date;
if (data.nightly_rate !== undefined) updatePayload.nightly_rate = data.nightly_rate;
if (data.pricing_mode !== undefined) updatePayload.pricing_mode = data.pricing_mode;
if (data.delta_amount !== undefined) updatePayload.delta_amount = data.delta_amount;
if (data.active !== undefined) updatePayload.active = data.active;
updatePayload.updatedById = currentUser.id;
await seasonal_rates.update(updatePayload, {transaction});
if (data.hotel !== undefined) {
await seasonal_rates.setHotel(
data.hotel,
{ transaction }
);
}
if (data.room_type !== undefined) {
await seasonal_rates.setRoom_type(
data.room_type,
{ transaction }
);
}
if (data.rate_plan !== undefined) {
await seasonal_rates.setRate_plan(
data.rate_plan,
{ transaction }
);
}
if (data.organizations !== undefined) {
await seasonal_rates.setOrganizations(
data.organizations,
{ transaction }
);
}
return seasonal_rates;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const seasonal_rates = await db.seasonal_rates.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of seasonal_rates) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of seasonal_rates) {
await record.destroy({transaction});
}
});
return seasonal_rates;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const seasonal_rates = await db.seasonal_rates.findByPk(id, options);
await seasonal_rates.update({
deletedBy: currentUser.id
}, {
transaction,
});
await seasonal_rates.destroy({
transaction
});
return seasonal_rates;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const seasonal_rates = await db.seasonal_rates.findOne(
{ where },
{ transaction },
);
if (!seasonal_rates) {
return seasonal_rates;
}
const output = seasonal_rates.get({plain: true});
output.hotel = await seasonal_rates.getHotel({
transaction
});
output.room_type = await seasonal_rates.getRoom_type({
transaction
});
output.rate_plan = await seasonal_rates.getRate_plan({
transaction
});
output.organizations = await seasonal_rates.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.hotels,
as: 'hotel',
where: filter.hotel ? {
[Op.or]: [
{ id: { [Op.in]: filter.hotel.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.hotel.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.room_types,
as: 'room_type',
where: filter.room_type ? {
[Op.or]: [
{ id: { [Op.in]: filter.room_type.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.room_type.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.rate_plans,
as: 'rate_plan',
where: filter.rate_plan ? {
[Op.or]: [
{ id: { [Op.in]: filter.rate_plan.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.rate_plan.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.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
start_date: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
end_date: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.start_dateRange) {
const [start, end] = filter.start_dateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
start_date: {
...where.start_date,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
start_date: {
...where.start_date,
[Op.lte]: end,
},
};
}
}
if (filter.end_dateRange) {
const [start, end] = filter.end_dateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
end_date: {
...where.end_date,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
end_date: {
...where.end_date,
[Op.lte]: end,
},
};
}
}
if (filter.nightly_rateRange) {
const [start, end] = filter.nightly_rateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
nightly_rate: {
...where.nightly_rate,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
nightly_rate: {
...where.nightly_rate,
[Op.lte]: end,
},
};
}
}
if (filter.delta_amountRange) {
const [start, end] = filter.delta_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
delta_amount: {
...where.delta_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
delta_amount: {
...where.delta_amount,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.pricing_mode) {
where = {
...where,
pricing_mode: filter.pricing_mode,
};
}
if (filter.active) {
where = {
...where,
active: filter.active,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.seasonal_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(
'seasonal_rates',
'pricing_mode',
query,
),
],
};
}
const records = await db.seasonal_rates.findAll({
attributes: [ 'id', 'pricing_mode' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['pricing_mode', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.pricing_mode,
}));
}
};

View File

@ -0,0 +1,597 @@
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 ShiftsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const shifts = await db.shifts.create(
{
id: data.id || undefined,
start_at: data.start_at
||
null
,
end_at: data.end_at
||
null
,
status: data.status
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await shifts.setHotel( data.hotel || null, {
transaction,
});
await shifts.setStaff_profile( data.staff_profile || null, {
transaction,
});
await shifts.setOrganizations( data.organizations || null, {
transaction,
});
return shifts;
}
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 shiftsData = data.map((item, index) => ({
id: item.id || undefined,
start_at: item.start_at
||
null
,
end_at: item.end_at
||
null
,
status: item.status
||
null
,
notes: item.notes
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const shifts = await db.shifts.bulkCreate(shiftsData, { transaction });
// For each item created, replace relation files
return shifts;
}
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 shifts = await db.shifts.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.start_at !== undefined) updatePayload.start_at = data.start_at;
if (data.end_at !== undefined) updatePayload.end_at = data.end_at;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await shifts.update(updatePayload, {transaction});
if (data.hotel !== undefined) {
await shifts.setHotel(
data.hotel,
{ transaction }
);
}
if (data.staff_profile !== undefined) {
await shifts.setStaff_profile(
data.staff_profile,
{ transaction }
);
}
if (data.organizations !== undefined) {
await shifts.setOrganizations(
data.organizations,
{ transaction }
);
}
return shifts;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const shifts = await db.shifts.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of shifts) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of shifts) {
await record.destroy({transaction});
}
});
return shifts;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const shifts = await db.shifts.findByPk(id, options);
await shifts.update({
deletedBy: currentUser.id
}, {
transaction,
});
await shifts.destroy({
transaction
});
return shifts;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const shifts = await db.shifts.findOne(
{ where },
{ transaction },
);
if (!shifts) {
return shifts;
}
const output = shifts.get({plain: true});
output.hotel = await shifts.getHotel({
transaction
});
output.staff_profile = await shifts.getStaff_profile({
transaction
});
output.organizations = await shifts.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.hotels,
as: 'hotel',
where: filter.hotel ? {
[Op.or]: [
{ id: { [Op.in]: filter.hotel.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.hotel.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.staff_profiles,
as: 'staff_profile',
where: filter.staff_profile ? {
[Op.or]: [
{ id: { [Op.in]: filter.staff_profile.split('|').map(term => Utils.uuid(term)) } },
{
employee_code: {
[Op.or]: filter.staff_profile.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'shifts',
'notes',
filter.notes,
),
};
}
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.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.shifts.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(
'shifts',
'notes',
query,
),
],
};
}
const records = await db.shifts.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,639 @@
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 Staff_profilesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const staff_profiles = await db.staff_profiles.create(
{
id: data.id || undefined,
job_title: data.job_title
||
null
,
employee_code: data.employee_code
||
null
,
hire_date: data.hire_date
||
null
,
can_login: data.can_login
||
false
,
active: data.active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await staff_profiles.setHotel( data.hotel || null, {
transaction,
});
await staff_profiles.setUser( data.user || null, {
transaction,
});
await staff_profiles.setDepartment( data.department || null, {
transaction,
});
await staff_profiles.setOrganizations( data.organizations || null, {
transaction,
});
return staff_profiles;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const staff_profilesData = data.map((item, index) => ({
id: item.id || undefined,
job_title: item.job_title
||
null
,
employee_code: item.employee_code
||
null
,
hire_date: item.hire_date
||
null
,
can_login: item.can_login
||
false
,
active: item.active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const staff_profiles = await db.staff_profiles.bulkCreate(staff_profilesData, { transaction });
// For each item created, replace relation files
return staff_profiles;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const staff_profiles = await db.staff_profiles.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.job_title !== undefined) updatePayload.job_title = data.job_title;
if (data.employee_code !== undefined) updatePayload.employee_code = data.employee_code;
if (data.hire_date !== undefined) updatePayload.hire_date = data.hire_date;
if (data.can_login !== undefined) updatePayload.can_login = data.can_login;
if (data.active !== undefined) updatePayload.active = data.active;
updatePayload.updatedById = currentUser.id;
await staff_profiles.update(updatePayload, {transaction});
if (data.hotel !== undefined) {
await staff_profiles.setHotel(
data.hotel,
{ transaction }
);
}
if (data.user !== undefined) {
await staff_profiles.setUser(
data.user,
{ transaction }
);
}
if (data.department !== undefined) {
await staff_profiles.setDepartment(
data.department,
{ transaction }
);
}
if (data.organizations !== undefined) {
await staff_profiles.setOrganizations(
data.organizations,
{ transaction }
);
}
return staff_profiles;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const staff_profiles = await db.staff_profiles.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of staff_profiles) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of staff_profiles) {
await record.destroy({transaction});
}
});
return staff_profiles;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const staff_profiles = await db.staff_profiles.findByPk(id, options);
await staff_profiles.update({
deletedBy: currentUser.id
}, {
transaction,
});
await staff_profiles.destroy({
transaction
});
return staff_profiles;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const staff_profiles = await db.staff_profiles.findOne(
{ where },
{ transaction },
);
if (!staff_profiles) {
return staff_profiles;
}
const output = staff_profiles.get({plain: true});
output.shifts_staff_profile = await staff_profiles.getShifts_staff_profile({
transaction
});
output.housekeeping_tasks_assigned_staff_profile = await staff_profiles.getHousekeeping_tasks_assigned_staff_profile({
transaction
});
output.maintenance_tickets_assigned_staff_profile = await staff_profiles.getMaintenance_tickets_assigned_staff_profile({
transaction
});
output.hotel = await staff_profiles.getHotel({
transaction
});
output.user = await staff_profiles.getUser({
transaction
});
output.department = await staff_profiles.getDepartment({
transaction
});
output.organizations = await staff_profiles.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.hotels,
as: 'hotel',
where: filter.hotel ? {
[Op.or]: [
{ id: { [Op.in]: filter.hotel.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.hotel.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.departments,
as: 'department',
where: filter.department ? {
[Op.or]: [
{ id: { [Op.in]: filter.department.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.department.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.job_title) {
where = {
...where,
[Op.and]: Utils.ilike(
'staff_profiles',
'job_title',
filter.job_title,
),
};
}
if (filter.employee_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'staff_profiles',
'employee_code',
filter.employee_code,
),
};
}
if (filter.hire_dateRange) {
const [start, end] = filter.hire_dateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
hire_date: {
...where.hire_date,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
hire_date: {
...where.hire_date,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.can_login) {
where = {
...where,
can_login: filter.can_login,
};
}
if (filter.active) {
where = {
...where,
active: filter.active,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.staff_profiles.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'staff_profiles',
'employee_code',
query,
),
],
};
}
const records = await db.staff_profiles.findAll({
attributes: [ 'id', 'employee_code' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['employee_code', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.employee_code,
}));
}
};

View File

@ -0,0 +1,652 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Stay_foliosDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const stay_folios = await db.stay_folios.create(
{
id: data.id || undefined,
folio_number: data.folio_number
||
null
,
status: data.status
||
null
,
balance_due: data.balance_due
||
null
,
total_charges: data.total_charges
||
null
,
total_payments: data.total_payments
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await stay_folios.setHotel( data.hotel || null, {
transaction,
});
await stay_folios.setReservation( data.reservation || null, {
transaction,
});
await stay_folios.setOrganizations( data.organizations || null, {
transaction,
});
return stay_folios;
}
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 stay_foliosData = data.map((item, index) => ({
id: item.id || undefined,
folio_number: item.folio_number
||
null
,
status: item.status
||
null
,
balance_due: item.balance_due
||
null
,
total_charges: item.total_charges
||
null
,
total_payments: item.total_payments
||
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 stay_folios = await db.stay_folios.bulkCreate(stay_foliosData, { transaction });
// For each item created, replace relation files
return stay_folios;
}
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 stay_folios = await db.stay_folios.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.folio_number !== undefined) updatePayload.folio_number = data.folio_number;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.balance_due !== undefined) updatePayload.balance_due = data.balance_due;
if (data.total_charges !== undefined) updatePayload.total_charges = data.total_charges;
if (data.total_payments !== undefined) updatePayload.total_payments = data.total_payments;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await stay_folios.update(updatePayload, {transaction});
if (data.hotel !== undefined) {
await stay_folios.setHotel(
data.hotel,
{ transaction }
);
}
if (data.reservation !== undefined) {
await stay_folios.setReservation(
data.reservation,
{ transaction }
);
}
if (data.organizations !== undefined) {
await stay_folios.setOrganizations(
data.organizations,
{ transaction }
);
}
return stay_folios;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const stay_folios = await db.stay_folios.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of stay_folios) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of stay_folios) {
await record.destroy({transaction});
}
});
return stay_folios;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const stay_folios = await db.stay_folios.findByPk(id, options);
await stay_folios.update({
deletedBy: currentUser.id
}, {
transaction,
});
await stay_folios.destroy({
transaction
});
return stay_folios;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const stay_folios = await db.stay_folios.findOne(
{ where },
{ transaction },
);
if (!stay_folios) {
return stay_folios;
}
const output = stay_folios.get({plain: true});
output.folio_items_stay_folio = await stay_folios.getFolio_items_stay_folio({
transaction
});
output.payments_stay_folio = await stay_folios.getPayments_stay_folio({
transaction
});
output.invoices_stay_folio = await stay_folios.getInvoices_stay_folio({
transaction
});
output.hotel = await stay_folios.getHotel({
transaction
});
output.reservation = await stay_folios.getReservation({
transaction
});
output.organizations = await stay_folios.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.hotels,
as: 'hotel',
where: filter.hotel ? {
[Op.or]: [
{ id: { [Op.in]: filter.hotel.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.hotel.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_number: {
[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.folio_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'stay_folios',
'folio_number',
filter.folio_number,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'stay_folios',
'notes',
filter.notes,
),
};
}
if (filter.balance_dueRange) {
const [start, end] = filter.balance_dueRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
balance_due: {
...where.balance_due,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
balance_due: {
...where.balance_due,
[Op.lte]: end,
},
};
}
}
if (filter.total_chargesRange) {
const [start, end] = filter.total_chargesRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
total_charges: {
...where.total_charges,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
total_charges: {
...where.total_charges,
[Op.lte]: end,
},
};
}
}
if (filter.total_paymentsRange) {
const [start, end] = filter.total_paymentsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
total_payments: {
...where.total_payments,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
total_payments: {
...where.total_payments,
[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.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.stay_folios.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(
'stay_folios',
'folio_number',
query,
),
],
};
}
const records = await db.stay_folios.findAll({
attributes: [ 'id', 'folio_number' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['folio_number', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.folio_number,
}));
}
};

View File

@ -0,0 +1,739 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class SubscriptionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const subscriptions = await db.subscriptions.create(
{
id: data.id || undefined,
plan: data.plan
||
null
,
billing_cycle: data.billing_cycle
||
null
,
status: data.status
||
null
,
trial_ends_at: data.trial_ends_at
||
null
,
current_period_start_at: data.current_period_start_at
||
null
,
current_period_end_at: data.current_period_end_at
||
null
,
included_rooms_limit: data.included_rooms_limit
||
null
,
included_users_limit: data.included_users_limit
||
null
,
stripe_subscription_reference: data.stripe_subscription_reference
||
null
,
stripe_price_reference: data.stripe_price_reference
||
null
,
auto_renew: data.auto_renew
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await subscriptions.setHotel( data.hotel || null, {
transaction,
});
await subscriptions.setOrganizations( data.organizations || null, {
transaction,
});
return subscriptions;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const subscriptionsData = data.map((item, index) => ({
id: item.id || undefined,
plan: item.plan
||
null
,
billing_cycle: item.billing_cycle
||
null
,
status: item.status
||
null
,
trial_ends_at: item.trial_ends_at
||
null
,
current_period_start_at: item.current_period_start_at
||
null
,
current_period_end_at: item.current_period_end_at
||
null
,
included_rooms_limit: item.included_rooms_limit
||
null
,
included_users_limit: item.included_users_limit
||
null
,
stripe_subscription_reference: item.stripe_subscription_reference
||
null
,
stripe_price_reference: item.stripe_price_reference
||
null
,
auto_renew: item.auto_renew
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const subscriptions = await db.subscriptions.bulkCreate(subscriptionsData, { transaction });
// For each item created, replace relation files
return subscriptions;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const subscriptions = await db.subscriptions.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.plan !== undefined) updatePayload.plan = data.plan;
if (data.billing_cycle !== undefined) updatePayload.billing_cycle = data.billing_cycle;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.trial_ends_at !== undefined) updatePayload.trial_ends_at = data.trial_ends_at;
if (data.current_period_start_at !== undefined) updatePayload.current_period_start_at = data.current_period_start_at;
if (data.current_period_end_at !== undefined) updatePayload.current_period_end_at = data.current_period_end_at;
if (data.included_rooms_limit !== undefined) updatePayload.included_rooms_limit = data.included_rooms_limit;
if (data.included_users_limit !== undefined) updatePayload.included_users_limit = data.included_users_limit;
if (data.stripe_subscription_reference !== undefined) updatePayload.stripe_subscription_reference = data.stripe_subscription_reference;
if (data.stripe_price_reference !== undefined) updatePayload.stripe_price_reference = data.stripe_price_reference;
if (data.auto_renew !== undefined) updatePayload.auto_renew = data.auto_renew;
updatePayload.updatedById = currentUser.id;
await subscriptions.update(updatePayload, {transaction});
if (data.hotel !== undefined) {
await subscriptions.setHotel(
data.hotel,
{ transaction }
);
}
if (data.organizations !== undefined) {
await subscriptions.setOrganizations(
data.organizations,
{ transaction }
);
}
return subscriptions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const subscriptions = await db.subscriptions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of subscriptions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of subscriptions) {
await record.destroy({transaction});
}
});
return subscriptions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const subscriptions = await db.subscriptions.findByPk(id, options);
await subscriptions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await subscriptions.destroy({
transaction
});
return subscriptions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const subscriptions = await db.subscriptions.findOne(
{ where },
{ transaction },
);
if (!subscriptions) {
return subscriptions;
}
const output = subscriptions.get({plain: true});
output.hotel = await subscriptions.getHotel({
transaction
});
output.organizations = await subscriptions.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.hotels,
as: 'hotel',
where: filter.hotel ? {
[Op.or]: [
{ id: { [Op.in]: filter.hotel.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.hotel.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.stripe_subscription_reference) {
where = {
...where,
[Op.and]: Utils.ilike(
'subscriptions',
'stripe_subscription_reference',
filter.stripe_subscription_reference,
),
};
}
if (filter.stripe_price_reference) {
where = {
...where,
[Op.and]: Utils.ilike(
'subscriptions',
'stripe_price_reference',
filter.stripe_price_reference,
),
};
}
if (filter.trial_ends_atRange) {
const [start, end] = filter.trial_ends_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
trial_ends_at: {
...where.trial_ends_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
trial_ends_at: {
...where.trial_ends_at,
[Op.lte]: end,
},
};
}
}
if (filter.current_period_start_atRange) {
const [start, end] = filter.current_period_start_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
current_period_start_at: {
...where.current_period_start_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
current_period_start_at: {
...where.current_period_start_at,
[Op.lte]: end,
},
};
}
}
if (filter.current_period_end_atRange) {
const [start, end] = filter.current_period_end_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
current_period_end_at: {
...where.current_period_end_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
current_period_end_at: {
...where.current_period_end_at,
[Op.lte]: end,
},
};
}
}
if (filter.included_rooms_limitRange) {
const [start, end] = filter.included_rooms_limitRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
included_rooms_limit: {
...where.included_rooms_limit,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
included_rooms_limit: {
...where.included_rooms_limit,
[Op.lte]: end,
},
};
}
}
if (filter.included_users_limitRange) {
const [start, end] = filter.included_users_limitRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
included_users_limit: {
...where.included_users_limit,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
included_users_limit: {
...where.included_users_limit,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.plan) {
where = {
...where,
plan: filter.plan,
};
}
if (filter.billing_cycle) {
where = {
...where,
billing_cycle: filter.billing_cycle,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.auto_renew) {
where = {
...where,
auto_renew: filter.auto_renew,
};
}
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.subscriptions.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'subscriptions',
'plan',
query,
),
],
};
}
const records = await db.subscriptions.findAll({
attributes: [ 'id', 'plan' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['plan', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.plan,
}));
}
};

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

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,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,189 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const audit_logs = sequelize.define(
'audit_logs',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
action: {
type: DataTypes.ENUM,
values: [
"create",
"update",
"delete",
"login",
"logout",
"export",
"sync",
"suspend"
],
},
entity_name: {
type: DataTypes.TEXT,
},
record_reference: {
type: DataTypes.TEXT,
},
occurred_at: {
type: DataTypes.DATE,
},
ip_address: {
type: DataTypes.TEXT,
},
user_agent: {
type: DataTypes.TEXT,
},
details: {
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.hotels, {
as: 'hotel',
foreignKey: {
name: 'hotelId',
},
constraints: false,
});
db.audit_logs.belongsTo(db.users, {
as: 'actor_user',
foreignKey: {
name: 'actor_userId',
},
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,136 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const booking_widgets = sequelize.define(
'booking_widgets',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
public_key: {
type: DataTypes.TEXT,
},
allowed_domains: {
type: DataTypes.TEXT,
},
active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
booking_widgets.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_widgets.belongsTo(db.hotels, {
as: 'hotel',
foreignKey: {
name: 'hotelId',
},
constraints: false,
});
db.booking_widgets.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.booking_widgets.belongsTo(db.users, {
as: 'createdBy',
});
db.booking_widgets.belongsTo(db.users, {
as: 'updatedBy',
});
};
return booking_widgets;
};

View File

@ -0,0 +1,189 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const daily_snapshots = sequelize.define(
'daily_snapshots',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
snapshot_at: {
type: DataTypes.DATE,
},
rooms_available: {
type: DataTypes.INTEGER,
},
rooms_occupied: {
type: DataTypes.INTEGER,
},
rooms_dirty: {
type: DataTypes.INTEGER,
},
rooms_out_of_service: {
type: DataTypes.INTEGER,
},
occupancy_rate_percent: {
type: DataTypes.DECIMAL,
},
revenue_today: {
type: DataTypes.DECIMAL,
},
revenue_month_to_date: {
type: DataTypes.DECIMAL,
},
adr: {
type: DataTypes.DECIMAL,
},
revpar: {
type: DataTypes.DECIMAL,
},
arrivals_today: {
type: DataTypes.INTEGER,
},
departures_today: {
type: DataTypes.INTEGER,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
daily_snapshots.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.daily_snapshots.belongsTo(db.hotels, {
as: 'hotel',
foreignKey: {
name: 'hotelId',
},
constraints: false,
});
db.daily_snapshots.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.daily_snapshots.belongsTo(db.users, {
as: 'createdBy',
});
db.daily_snapshots.belongsTo(db.users, {
as: 'updatedBy',
});
};
return daily_snapshots;
};

View File

@ -0,0 +1,137 @@
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 departments = sequelize.define(
'departments',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
description: {
type: DataTypes.TEXT,
},
active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
departments.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.departments.hasMany(db.staff_profiles, {
as: 'staff_profiles_department',
foreignKey: {
name: 'departmentId',
},
constraints: false,
});
//end loop
db.departments.belongsTo(db.hotels, {
as: 'hotel',
foreignKey: {
name: 'hotelId',
},
constraints: false,
});
db.departments.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.departments.belongsTo(db.users, {
as: 'createdBy',
});
db.departments.belongsTo(db.users, {
as: 'updatedBy',
});
};
return departments;
};

View File

@ -0,0 +1,209 @@
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 dynamic_pricing_rules = sequelize.define(
'dynamic_pricing_rules',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
rule_type: {
type: DataTypes.ENUM,
values: [
"occupancy_based",
"days_before_arrival",
"day_of_week",
"length_of_stay"
],
},
adjustment_percent: {
type: DataTypes.DECIMAL,
},
adjustment_amount: {
type: DataTypes.DECIMAL,
},
min_occupancy_percent: {
type: DataTypes.INTEGER,
},
max_occupancy_percent: {
type: DataTypes.INTEGER,
},
min_days_before: {
type: DataTypes.INTEGER,
},
max_days_before: {
type: DataTypes.INTEGER,
},
applies_days_of_week: {
type: DataTypes.TEXT,
},
active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
dynamic_pricing_rules.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.dynamic_pricing_rules.belongsTo(db.hotels, {
as: 'hotel',
foreignKey: {
name: 'hotelId',
},
constraints: false,
});
db.dynamic_pricing_rules.belongsTo(db.room_types, {
as: 'room_type',
foreignKey: {
name: 'room_typeId',
},
constraints: false,
});
db.dynamic_pricing_rules.belongsTo(db.rate_plans, {
as: 'rate_plan',
foreignKey: {
name: 'rate_planId',
},
constraints: false,
});
db.dynamic_pricing_rules.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.dynamic_pricing_rules.belongsTo(db.users, {
as: 'createdBy',
});
db.dynamic_pricing_rules.belongsTo(db.users, {
as: 'updatedBy',
});
};
return dynamic_pricing_rules;
};

View File

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

View File

@ -0,0 +1,189 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const folio_items = sequelize.define(
'folio_items',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
item_type: {
type: DataTypes.ENUM,
values: [
"room_charge",
"tax",
"fee",
"service",
"pos",
"discount",
"adjustment"
],
},
description: {
type: DataTypes.TEXT,
},
posted_at: {
type: DataTypes.DATE,
},
quantity: {
type: DataTypes.INTEGER,
},
unit_price: {
type: DataTypes.DECIMAL,
},
amount: {
type: DataTypes.DECIMAL,
},
taxable: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
folio_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.folio_items.belongsTo(db.hotels, {
as: 'hotel',
foreignKey: {
name: 'hotelId',
},
constraints: false,
});
db.folio_items.belongsTo(db.stay_folios, {
as: 'stay_folio',
foreignKey: {
name: 'stay_folioId',
},
constraints: false,
});
db.folio_items.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.folio_items.belongsTo(db.users, {
as: 'createdBy',
});
db.folio_items.belongsTo(db.users, {
as: 'updatedBy',
});
};
return folio_items;
};

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 guest_documents = sequelize.define(
'guest_documents',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
document_type: {
type: DataTypes.ENUM,
values: [
"passport",
"national_id",
"drivers_license",
"other"
],
},
document_number: {
type: DataTypes.TEXT,
},
issued_at: {
type: DataTypes.DATE,
},
expires_at: {
type: DataTypes.DATE,
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
guest_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.guest_documents.belongsTo(db.hotels, {
as: 'hotel',
foreignKey: {
name: 'hotelId',
},
constraints: false,
});
db.guest_documents.belongsTo(db.guests, {
as: 'guest',
foreignKey: {
name: 'guestId',
},
constraints: false,
});
db.guest_documents.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.guest_documents.hasMany(db.file, {
as: 'file',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.guest_documents.getTableName(),
belongsToColumn: 'file',
},
});
db.guest_documents.belongsTo(db.users, {
as: 'createdBy',
});
db.guest_documents.belongsTo(db.users, {
as: 'updatedBy',
});
};
return guest_documents;
};

View File

@ -0,0 +1,245 @@
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 guests = sequelize.define(
'guests',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
first_name: {
type: DataTypes.TEXT,
},
last_name: {
type: DataTypes.TEXT,
},
email: {
type: DataTypes.TEXT,
},
phone: {
type: DataTypes.TEXT,
},
nationality: {
type: DataTypes.TEXT,
},
address_line1: {
type: DataTypes.TEXT,
},
address_line2: {
type: DataTypes.TEXT,
},
city: {
type: DataTypes.TEXT,
},
state_region: {
type: DataTypes.TEXT,
},
postal_code: {
type: DataTypes.TEXT,
},
country: {
type: DataTypes.TEXT,
},
preferences: {
type: DataTypes.TEXT,
},
notes: {
type: DataTypes.TEXT,
},
loyalty_points: {
type: DataTypes.INTEGER,
},
marketing_opt_in: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
guests.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.guests.hasMany(db.guest_documents, {
as: 'guest_documents_guest',
foreignKey: {
name: 'guestId',
},
constraints: false,
});
db.guests.hasMany(db.reservations, {
as: 'reservations_guest',
foreignKey: {
name: 'guestId',
},
constraints: false,
});
db.guests.hasMany(db.reservation_guests, {
as: 'reservation_guests_guest',
foreignKey: {
name: 'guestId',
},
constraints: false,
});
db.guests.hasMany(db.notifications, {
as: 'notifications_guest',
foreignKey: {
name: 'guestId',
},
constraints: false,
});
//end loop
db.guests.belongsTo(db.hotels, {
as: 'hotel',
foreignKey: {
name: 'hotelId',
},
constraints: false,
});
db.guests.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.guests.belongsTo(db.users, {
as: 'createdBy',
});
db.guests.belongsTo(db.users, {
as: 'updatedBy',
});
};
return guests;
};

View File

@ -0,0 +1,420 @@
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 hotels = sequelize.define(
'hotels',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
legal_name: {
type: DataTypes.TEXT,
},
address_line1: {
type: DataTypes.TEXT,
},
address_line2: {
type: DataTypes.TEXT,
},
city: {
type: DataTypes.TEXT,
},
state_region: {
type: DataTypes.TEXT,
},
postal_code: {
type: DataTypes.TEXT,
},
country: {
type: DataTypes.TEXT,
},
phone: {
type: DataTypes.TEXT,
},
email: {
type: DataTypes.TEXT,
},
website: {
type: DataTypes.TEXT,
},
timezone: {
type: DataTypes.TEXT,
},
currency: {
type: DataTypes.TEXT,
},
default_tax_rate: {
type: DataTypes.DECIMAL,
},
active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
stripe_customer_reference: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
hotels.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.hotels.hasMany(db.departments, {
as: 'departments_hotel',
foreignKey: {
name: 'hotelId',
},
constraints: false,
});
db.hotels.hasMany(db.staff_profiles, {
as: 'staff_profiles_hotel',
foreignKey: {
name: 'hotelId',
},
constraints: false,
});
db.hotels.hasMany(db.shifts, {
as: 'shifts_hotel',
foreignKey: {
name: 'hotelId',
},
constraints: false,
});
db.hotels.hasMany(db.room_types, {
as: 'room_types_hotel',
foreignKey: {
name: 'hotelId',
},
constraints: false,
});
db.hotels.hasMany(db.rooms, {
as: 'rooms_hotel',
foreignKey: {
name: 'hotelId',
},
constraints: false,
});
db.hotels.hasMany(db.guests, {
as: 'guests_hotel',
foreignKey: {
name: 'hotelId',
},
constraints: false,
});
db.hotels.hasMany(db.guest_documents, {
as: 'guest_documents_hotel',
foreignKey: {
name: 'hotelId',
},
constraints: false,
});
db.hotels.hasMany(db.rate_plans, {
as: 'rate_plans_hotel',
foreignKey: {
name: 'hotelId',
},
constraints: false,
});
db.hotels.hasMany(db.seasonal_rates, {
as: 'seasonal_rates_hotel',
foreignKey: {
name: 'hotelId',
},
constraints: false,
});
db.hotels.hasMany(db.dynamic_pricing_rules, {
as: 'dynamic_pricing_rules_hotel',
foreignKey: {
name: 'hotelId',
},
constraints: false,
});
db.hotels.hasMany(db.sales_channels, {
as: 'sales_channels_hotel',
foreignKey: {
name: 'hotelId',
},
constraints: false,
});
db.hotels.hasMany(db.ota_connections, {
as: 'ota_connections_hotel',
foreignKey: {
name: 'hotelId',
},
constraints: false,
});
db.hotels.hasMany(db.reservations, {
as: 'reservations_hotel',
foreignKey: {
name: 'hotelId',
},
constraints: false,
});
db.hotels.hasMany(db.reservation_guests, {
as: 'reservation_guests_hotel',
foreignKey: {
name: 'hotelId',
},
constraints: false,
});
db.hotels.hasMany(db.stay_folios, {
as: 'stay_folios_hotel',
foreignKey: {
name: 'hotelId',
},
constraints: false,
});
db.hotels.hasMany(db.folio_items, {
as: 'folio_items_hotel',
foreignKey: {
name: 'hotelId',
},
constraints: false,
});
db.hotels.hasMany(db.payments, {
as: 'payments_hotel',
foreignKey: {
name: 'hotelId',
},
constraints: false,
});
db.hotels.hasMany(db.refunds, {
as: 'refunds_hotel',
foreignKey: {
name: 'hotelId',
},
constraints: false,
});
db.hotels.hasMany(db.invoices, {
as: 'invoices_hotel',
foreignKey: {
name: 'hotelId',
},
constraints: false,
});
db.hotels.hasMany(db.housekeeping_tasks, {
as: 'housekeeping_tasks_hotel',
foreignKey: {
name: 'hotelId',
},
constraints: false,
});
db.hotels.hasMany(db.maintenance_tickets, {
as: 'maintenance_tickets_hotel',
foreignKey: {
name: 'hotelId',
},
constraints: false,
});
db.hotels.hasMany(db.notifications, {
as: 'notifications_hotel',
foreignKey: {
name: 'hotelId',
},
constraints: false,
});
db.hotels.hasMany(db.booking_widgets, {
as: 'booking_widgets_hotel',
foreignKey: {
name: 'hotelId',
},
constraints: false,
});
db.hotels.hasMany(db.subscriptions, {
as: 'subscriptions_hotel',
foreignKey: {
name: 'hotelId',
},
constraints: false,
});
db.hotels.hasMany(db.audit_logs, {
as: 'audit_logs_hotel',
foreignKey: {
name: 'hotelId',
},
constraints: false,
});
db.hotels.hasMany(db.daily_snapshots, {
as: 'daily_snapshots_hotel',
foreignKey: {
name: 'hotelId',
},
constraints: false,
});
//end loop
db.hotels.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.hotels.belongsTo(db.users, {
as: 'createdBy',
});
db.hotels.belongsTo(db.users, {
as: 'updatedBy',
});
};
return hotels;
};

View File

@ -0,0 +1,196 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const housekeeping_tasks = sequelize.define(
'housekeeping_tasks',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
scheduled_for: {
type: DataTypes.DATE,
},
started_at: {
type: DataTypes.DATE,
},
completed_at: {
type: DataTypes.DATE,
},
status: {
type: DataTypes.ENUM,
values: [
"pending",
"in_progress",
"completed",
"cancelled"
],
},
task_type: {
type: DataTypes.ENUM,
values: [
"cleaning",
"inspection",
"turndown",
"linen_change",
"deep_clean"
],
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
housekeeping_tasks.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.housekeeping_tasks.belongsTo(db.hotels, {
as: 'hotel',
foreignKey: {
name: 'hotelId',
},
constraints: false,
});
db.housekeeping_tasks.belongsTo(db.rooms, {
as: 'room',
foreignKey: {
name: 'roomId',
},
constraints: false,
});
db.housekeeping_tasks.belongsTo(db.staff_profiles, {
as: 'assigned_staff_profile',
foreignKey: {
name: 'assigned_staff_profileId',
},
constraints: false,
});
db.housekeeping_tasks.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.housekeeping_tasks.belongsTo(db.users, {
as: 'createdBy',
});
db.housekeeping_tasks.belongsTo(db.users, {
as: 'updatedBy',
});
};
return housekeeping_tasks;
};

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,204 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const invoices = sequelize.define(
'invoices',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
invoice_number: {
type: DataTypes.TEXT,
},
issued_at: {
type: DataTypes.DATE,
},
due_at: {
type: DataTypes.DATE,
},
status: {
type: DataTypes.ENUM,
values: [
"draft",
"issued",
"paid",
"void",
"overdue"
],
},
subtotal_amount: {
type: DataTypes.DECIMAL,
},
tax_amount: {
type: DataTypes.DECIMAL,
},
total_amount: {
type: DataTypes.DECIMAL,
},
billing_name: {
type: DataTypes.TEXT,
},
billing_address: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
invoices.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.invoices.belongsTo(db.hotels, {
as: 'hotel',
foreignKey: {
name: 'hotelId',
},
constraints: false,
});
db.invoices.belongsTo(db.stay_folios, {
as: 'stay_folio',
foreignKey: {
name: 'stay_folioId',
},
constraints: false,
});
db.invoices.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
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,231 @@
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 maintenance_tickets = sequelize.define(
'maintenance_tickets',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
category: {
type: DataTypes.ENUM,
values: [
"plumbing",
"electrical",
"hvac",
"appliance",
"furniture",
"internet_tv",
"other"
],
},
priority: {
type: DataTypes.ENUM,
values: [
"low",
"medium",
"high",
"urgent"
],
},
title: {
type: DataTypes.TEXT,
},
description: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"open",
"in_progress",
"closed"
],
},
opened_at: {
type: DataTypes.DATE,
},
closed_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
maintenance_tickets.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.maintenance_tickets.belongsTo(db.hotels, {
as: 'hotel',
foreignKey: {
name: 'hotelId',
},
constraints: false,
});
db.maintenance_tickets.belongsTo(db.rooms, {
as: 'room',
foreignKey: {
name: 'roomId',
},
constraints: false,
});
db.maintenance_tickets.belongsTo(db.staff_profiles, {
as: 'assigned_staff_profile',
foreignKey: {
name: 'assigned_staff_profileId',
},
constraints: false,
});
db.maintenance_tickets.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.maintenance_tickets.hasMany(db.file, {
as: 'attachments',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.maintenance_tickets.getTableName(),
belongsToColumn: 'attachments',
},
});
db.maintenance_tickets.belongsTo(db.users, {
as: 'createdBy',
});
db.maintenance_tickets.belongsTo(db.users, {
as: 'updatedBy',
});
};
return maintenance_tickets;
};

View File

@ -0,0 +1,233 @@
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: [
"email",
"sms"
],
},
template_type: {
type: DataTypes.ENUM,
values: [
"booking_confirmation",
"check_in_reminder",
"check_out_reminder",
"payment_confirmation",
"invoice"
],
},
status: {
type: DataTypes.ENUM,
values: [
"queued",
"sent",
"failed",
"cancelled"
],
},
scheduled_at: {
type: DataTypes.DATE,
},
sent_at: {
type: DataTypes.DATE,
},
to_address: {
type: DataTypes.TEXT,
},
subject: {
type: DataTypes.TEXT,
},
body: {
type: DataTypes.TEXT,
},
provider_message_reference: {
type: DataTypes.TEXT,
},
error_message: {
type: DataTypes.TEXT,
},
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.hotels, {
as: 'hotel',
foreignKey: {
name: 'hotelId',
},
constraints: false,
});
db.notifications.belongsTo(db.reservations, {
as: 'reservation',
foreignKey: {
name: 'reservationId',
},
constraints: false,
});
db.notifications.belongsTo(db.guests, {
as: 'guest',
foreignKey: {
name: 'guestId',
},
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,320 @@
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.hotels, {
as: 'hotels_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.departments, {
as: 'departments_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.staff_profiles, {
as: 'staff_profiles_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.shifts, {
as: 'shifts_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.room_types, {
as: 'room_types_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.rooms, {
as: 'rooms_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.guests, {
as: 'guests_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.guest_documents, {
as: 'guest_documents_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.rate_plans, {
as: 'rate_plans_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.seasonal_rates, {
as: 'seasonal_rates_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.dynamic_pricing_rules, {
as: 'dynamic_pricing_rules_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.sales_channels, {
as: 'sales_channels_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.ota_connections, {
as: 'ota_connections_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.reservations, {
as: 'reservations_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.reservation_guests, {
as: 'reservation_guests_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.stay_folios, {
as: 'stay_folios_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.folio_items, {
as: 'folio_items_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.payments, {
as: 'payments_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.refunds, {
as: 'refunds_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.invoices, {
as: 'invoices_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.housekeeping_tasks, {
as: 'housekeeping_tasks_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.maintenance_tickets, {
as: 'maintenance_tickets_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.notifications, {
as: 'notifications_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.booking_widgets, {
as: 'booking_widgets_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.subscriptions, {
as: 'subscriptions_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.audit_logs, {
as: 'audit_logs_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.daily_snapshots, {
as: 'daily_snapshots_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,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 ota_connections = sequelize.define(
'ota_connections',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
provider: {
type: DataTypes.ENUM,
values: [
"booking_com",
"expedia",
"airbnb",
"agoda",
"other"
],
},
account_identifier: {
type: DataTypes.TEXT,
},
api_key_reference: {
type: DataTypes.TEXT,
},
inventory_sync_enabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
rate_sync_enabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
last_sync_at: {
type: DataTypes.DATE,
},
sync_status: {
type: DataTypes.ENUM,
values: [
"ok",
"warning",
"error",
"disabled"
],
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
ota_connections.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.ota_connections.belongsTo(db.hotels, {
as: 'hotel',
foreignKey: {
name: 'hotelId',
},
constraints: false,
});
db.ota_connections.belongsTo(db.sales_channels, {
as: 'sales_channel',
foreignKey: {
name: 'sales_channelId',
},
constraints: false,
});
db.ota_connections.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.ota_connections.belongsTo(db.users, {
as: 'createdBy',
});
db.ota_connections.belongsTo(db.users, {
as: 'updatedBy',
});
};
return ota_connections;
};

View File

@ -0,0 +1,224 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const payments = sequelize.define(
'payments',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
method: {
type: DataTypes.ENUM,
values: [
"cash",
"credit_card",
"debit_card",
"bank_transfer",
"stripe"
],
},
amount: {
type: DataTypes.DECIMAL,
},
status: {
type: DataTypes.ENUM,
values: [
"pending",
"authorized",
"captured",
"failed",
"refunded",
"cancelled"
],
},
paid_at: {
type: DataTypes.DATE,
},
stripe_payment_intent_reference: {
type: DataTypes.TEXT,
},
stripe_charge_reference: {
type: DataTypes.TEXT,
},
receipt_number: {
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
db.payments.hasMany(db.refunds, {
as: 'refunds_payment',
foreignKey: {
name: 'paymentId',
},
constraints: false,
});
//end loop
db.payments.belongsTo(db.hotels, {
as: 'hotel',
foreignKey: {
name: 'hotelId',
},
constraints: false,
});
db.payments.belongsTo(db.stay_folios, {
as: 'stay_folio',
foreignKey: {
name: 'stay_folioId',
},
constraints: false,
});
db.payments.belongsTo(db.reservations, {
as: 'reservation',
foreignKey: {
name: 'reservationId',
},
constraints: false,
});
db.payments.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.payments.belongsTo(db.users, {
as: 'createdBy',
});
db.payments.belongsTo(db.users, {
as: 'updatedBy',
});
};
return payments;
};

View File

@ -0,0 +1,96 @@
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,209 @@
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 rate_plans = sequelize.define(
'rate_plans',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
plan_type: {
type: DataTypes.ENUM,
values: [
"standard",
"non_refundable",
"package",
"corporate",
"promo"
],
},
refundable: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
min_nights: {
type: DataTypes.INTEGER,
},
max_nights: {
type: DataTypes.INTEGER,
},
deposit_percent: {
type: DataTypes.DECIMAL,
},
cancellation_policy: {
type: DataTypes.TEXT,
},
active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
rate_plans.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.rate_plans.hasMany(db.seasonal_rates, {
as: 'seasonal_rates_rate_plan',
foreignKey: {
name: 'rate_planId',
},
constraints: false,
});
db.rate_plans.hasMany(db.dynamic_pricing_rules, {
as: 'dynamic_pricing_rules_rate_plan',
foreignKey: {
name: 'rate_planId',
},
constraints: false,
});
db.rate_plans.hasMany(db.reservations, {
as: 'reservations_rate_plan',
foreignKey: {
name: 'rate_planId',
},
constraints: false,
});
//end loop
db.rate_plans.belongsTo(db.hotels, {
as: 'hotel',
foreignKey: {
name: 'hotelId',
},
constraints: false,
});
db.rate_plans.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.rate_plans.belongsTo(db.users, {
as: 'createdBy',
});
db.rate_plans.belongsTo(db.users, {
as: 'updatedBy',
});
};
return rate_plans;
};

View File

@ -0,0 +1,163 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const refunds = sequelize.define(
'refunds',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
amount: {
type: DataTypes.DECIMAL,
},
status: {
type: DataTypes.ENUM,
values: [
"pending",
"succeeded",
"failed",
"cancelled"
],
},
refunded_at: {
type: DataTypes.DATE,
},
stripe_refund_reference: {
type: DataTypes.TEXT,
},
reason: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
refunds.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.refunds.belongsTo(db.hotels, {
as: 'hotel',
foreignKey: {
name: 'hotelId',
},
constraints: false,
});
db.refunds.belongsTo(db.payments, {
as: 'payment',
foreignKey: {
name: 'paymentId',
},
constraints: false,
});
db.refunds.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.refunds.belongsTo(db.users, {
as: 'createdBy',
});
db.refunds.belongsTo(db.users, {
as: 'updatedBy',
});
};
return refunds;
};

View File

@ -0,0 +1,147 @@
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,
},
guest_role: {
type: DataTypes.ENUM,
values: [
"primary",
"additional"
],
},
is_primary: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
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.hotels, {
as: 'hotel',
foreignKey: {
name: 'hotelId',
},
constraints: false,
});
db.reservation_guests.belongsTo(db.reservations, {
as: 'reservation',
foreignKey: {
name: 'reservationId',
},
constraints: false,
});
db.reservation_guests.belongsTo(db.guests, {
as: 'guest',
foreignKey: {
name: 'guestId',
},
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,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 reservations = sequelize.define(
'reservations',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
reservation_number: {
type: DataTypes.TEXT,
},
check_in_at: {
type: DataTypes.DATE,
},
check_out_at: {
type: DataTypes.DATE,
},
adults: {
type: DataTypes.INTEGER,
},
children: {
type: DataTypes.INTEGER,
},
status: {
type: DataTypes.ENUM,
values: [
"pending",
"confirmed",
"checked_in",
"checked_out",
"cancelled",
"no_show"
],
},
total_amount: {
type: DataTypes.DECIMAL,
},
tax_amount: {
type: DataTypes.DECIMAL,
},
deposit_amount: {
type: DataTypes.DECIMAL,
},
special_requests: {
type: DataTypes.TEXT,
},
internal_notes: {
type: DataTypes.TEXT,
},
cancelled_at: {
type: DataTypes.DATE,
},
cancellation_reason: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
reservations.associate = (db) => {
/// 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.reservation_guests, {
as: 'reservation_guests_reservation',
foreignKey: {
name: 'reservationId',
},
constraints: false,
});
db.reservations.hasMany(db.stay_folios, {
as: 'stay_folios_reservation',
foreignKey: {
name: 'reservationId',
},
constraints: false,
});
db.reservations.hasMany(db.payments, {
as: 'payments_reservation',
foreignKey: {
name: 'reservationId',
},
constraints: false,
});
db.reservations.hasMany(db.notifications, {
as: 'notifications_reservation',
foreignKey: {
name: 'reservationId',
},
constraints: false,
});
//end loop
db.reservations.belongsTo(db.hotels, {
as: 'hotel',
foreignKey: {
name: 'hotelId',
},
constraints: false,
});
db.reservations.belongsTo(db.guests, {
as: 'guest',
foreignKey: {
name: 'guestId',
},
constraints: false,
});
db.reservations.belongsTo(db.rooms, {
as: 'room',
foreignKey: {
name: 'roomId',
},
constraints: false,
});
db.reservations.belongsTo(db.room_types, {
as: 'room_type',
foreignKey: {
name: 'room_typeId',
},
constraints: false,
});
db.reservations.belongsTo(db.rate_plans, {
as: 'rate_plan',
foreignKey: {
name: 'rate_planId',
},
constraints: false,
});
db.reservations.belongsTo(db.sales_channels, {
as: 'sales_channel',
foreignKey: {
name: 'sales_channelId',
},
constraints: false,
});
db.reservations.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.reservations.belongsTo(db.users, {
as: 'createdBy',
});
db.reservations.belongsTo(db.users, {
as: 'updatedBy',
});
};
return reservations;
};

View File

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

View File

@ -0,0 +1,192 @@
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 room_types = sequelize.define(
'room_types',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
description: {
type: DataTypes.TEXT,
},
capacity_adults: {
type: DataTypes.INTEGER,
},
capacity_children: {
type: DataTypes.INTEGER,
},
base_rate: {
type: DataTypes.DECIMAL,
},
active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
room_types.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.room_types.hasMany(db.rooms, {
as: 'rooms_room_type',
foreignKey: {
name: 'room_typeId',
},
constraints: false,
});
db.room_types.hasMany(db.seasonal_rates, {
as: 'seasonal_rates_room_type',
foreignKey: {
name: 'room_typeId',
},
constraints: false,
});
db.room_types.hasMany(db.dynamic_pricing_rules, {
as: 'dynamic_pricing_rules_room_type',
foreignKey: {
name: 'room_typeId',
},
constraints: false,
});
db.room_types.hasMany(db.reservations, {
as: 'reservations_room_type',
foreignKey: {
name: 'room_typeId',
},
constraints: false,
});
//end loop
db.room_types.belongsTo(db.hotels, {
as: 'hotel',
foreignKey: {
name: 'hotelId',
},
constraints: false,
});
db.room_types.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.room_types.hasMany(db.file, {
as: 'photos',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.room_types.getTableName(),
belongsToColumn: 'photos',
},
});
db.room_types.belongsTo(db.users, {
as: 'createdBy',
});
db.room_types.belongsTo(db.users, {
as: 'updatedBy',
});
};
return room_types;
};

View File

@ -0,0 +1,196 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const rooms = sequelize.define(
'rooms',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
room_number: {
type: DataTypes.TEXT,
},
floor: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"available",
"occupied",
"dirty",
"cleaning",
"inspected",
"out_of_service"
],
},
notes: {
type: DataTypes.TEXT,
},
active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
rooms.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.rooms.hasMany(db.reservations, {
as: 'reservations_room',
foreignKey: {
name: 'roomId',
},
constraints: false,
});
db.rooms.hasMany(db.housekeeping_tasks, {
as: 'housekeeping_tasks_room',
foreignKey: {
name: 'roomId',
},
constraints: false,
});
db.rooms.hasMany(db.maintenance_tickets, {
as: 'maintenance_tickets_room',
foreignKey: {
name: 'roomId',
},
constraints: false,
});
//end loop
db.rooms.belongsTo(db.hotels, {
as: 'hotel',
foreignKey: {
name: 'hotelId',
},
constraints: false,
});
db.rooms.belongsTo(db.room_types, {
as: 'room_type',
foreignKey: {
name: 'room_typeId',
},
constraints: false,
});
db.rooms.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.rooms.belongsTo(db.users, {
as: 'createdBy',
});
db.rooms.belongsTo(db.users, {
as: 'updatedBy',
});
};
return rooms;
};

View File

@ -0,0 +1,170 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const sales_channels = sequelize.define(
'sales_channels',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
channel_type: {
type: DataTypes.ENUM,
values: [
"direct",
"ota",
"phone",
"walk_in",
"corporate"
],
},
name: {
type: DataTypes.TEXT,
},
external_reference: {
type: DataTypes.TEXT,
},
active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
sales_channels.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.sales_channels.hasMany(db.ota_connections, {
as: 'ota_connections_sales_channel',
foreignKey: {
name: 'sales_channelId',
},
constraints: false,
});
db.sales_channels.hasMany(db.reservations, {
as: 'reservations_sales_channel',
foreignKey: {
name: 'sales_channelId',
},
constraints: false,
});
//end loop
db.sales_channels.belongsTo(db.hotels, {
as: 'hotel',
foreignKey: {
name: 'hotelId',
},
constraints: false,
});
db.sales_channels.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.sales_channels.belongsTo(db.users, {
as: 'createdBy',
});
db.sales_channels.belongsTo(db.users, {
as: 'updatedBy',
});
};
return sales_channels;
};

View File

@ -0,0 +1,175 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const seasonal_rates = sequelize.define(
'seasonal_rates',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
start_date: {
type: DataTypes.DATE,
},
end_date: {
type: DataTypes.DATE,
},
nightly_rate: {
type: DataTypes.DECIMAL,
},
pricing_mode: {
type: DataTypes.ENUM,
values: [
"override",
"delta"
],
},
delta_amount: {
type: DataTypes.DECIMAL,
},
active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
seasonal_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.seasonal_rates.belongsTo(db.hotels, {
as: 'hotel',
foreignKey: {
name: 'hotelId',
},
constraints: false,
});
db.seasonal_rates.belongsTo(db.room_types, {
as: 'room_type',
foreignKey: {
name: 'room_typeId',
},
constraints: false,
});
db.seasonal_rates.belongsTo(db.rate_plans, {
as: 'rate_plan',
foreignKey: {
name: 'rate_planId',
},
constraints: false,
});
db.seasonal_rates.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.seasonal_rates.belongsTo(db.users, {
as: 'createdBy',
});
db.seasonal_rates.belongsTo(db.users, {
as: 'updatedBy',
});
};
return seasonal_rates;
};

View File

@ -0,0 +1,156 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const shifts = sequelize.define(
'shifts',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
start_at: {
type: DataTypes.DATE,
},
end_at: {
type: DataTypes.DATE,
},
status: {
type: DataTypes.ENUM,
values: [
"scheduled",
"in_progress",
"completed",
"cancelled"
],
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
shifts.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.shifts.belongsTo(db.hotels, {
as: 'hotel',
foreignKey: {
name: 'hotelId',
},
constraints: false,
});
db.shifts.belongsTo(db.staff_profiles, {
as: 'staff_profile',
foreignKey: {
name: 'staff_profileId',
},
constraints: false,
});
db.shifts.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.shifts.belongsTo(db.users, {
as: 'createdBy',
});
db.shifts.belongsTo(db.users, {
as: 'updatedBy',
});
};
return shifts;
};

View File

@ -0,0 +1,186 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const staff_profiles = sequelize.define(
'staff_profiles',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
job_title: {
type: DataTypes.TEXT,
},
employee_code: {
type: DataTypes.TEXT,
},
hire_date: {
type: DataTypes.DATE,
},
can_login: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
staff_profiles.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.staff_profiles.hasMany(db.shifts, {
as: 'shifts_staff_profile',
foreignKey: {
name: 'staff_profileId',
},
constraints: false,
});
db.staff_profiles.hasMany(db.housekeeping_tasks, {
as: 'housekeeping_tasks_assigned_staff_profile',
foreignKey: {
name: 'assigned_staff_profileId',
},
constraints: false,
});
db.staff_profiles.hasMany(db.maintenance_tickets, {
as: 'maintenance_tickets_assigned_staff_profile',
foreignKey: {
name: 'assigned_staff_profileId',
},
constraints: false,
});
//end loop
db.staff_profiles.belongsTo(db.hotels, {
as: 'hotel',
foreignKey: {
name: 'hotelId',
},
constraints: false,
});
db.staff_profiles.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.staff_profiles.belongsTo(db.departments, {
as: 'department',
foreignKey: {
name: 'departmentId',
},
constraints: false,
});
db.staff_profiles.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.staff_profiles.belongsTo(db.users, {
as: 'createdBy',
});
db.staff_profiles.belongsTo(db.users, {
as: 'updatedBy',
});
};
return staff_profiles;
};

View File

@ -0,0 +1,191 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const stay_folios = sequelize.define(
'stay_folios',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
folio_number: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"open",
"closed",
"void"
],
},
balance_due: {
type: DataTypes.DECIMAL,
},
total_charges: {
type: DataTypes.DECIMAL,
},
total_payments: {
type: DataTypes.DECIMAL,
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
stay_folios.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.stay_folios.hasMany(db.folio_items, {
as: 'folio_items_stay_folio',
foreignKey: {
name: 'stay_folioId',
},
constraints: false,
});
db.stay_folios.hasMany(db.payments, {
as: 'payments_stay_folio',
foreignKey: {
name: 'stay_folioId',
},
constraints: false,
});
db.stay_folios.hasMany(db.invoices, {
as: 'invoices_stay_folio',
foreignKey: {
name: 'stay_folioId',
},
constraints: false,
});
//end loop
db.stay_folios.belongsTo(db.hotels, {
as: 'hotel',
foreignKey: {
name: 'hotelId',
},
constraints: false,
});
db.stay_folios.belongsTo(db.reservations, {
as: 'reservation',
foreignKey: {
name: 'reservationId',
},
constraints: false,
});
db.stay_folios.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.stay_folios.belongsTo(db.users, {
as: 'createdBy',
});
db.stay_folios.belongsTo(db.users, {
as: 'updatedBy',
});
};
return stay_folios;
};

View File

@ -0,0 +1,224 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const subscriptions = sequelize.define(
'subscriptions',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
plan: {
type: DataTypes.ENUM,
values: [
"starter",
"professional",
"enterprise"
],
},
billing_cycle: {
type: DataTypes.ENUM,
values: [
"monthly",
"annual"
],
},
status: {
type: DataTypes.ENUM,
values: [
"trialing",
"active",
"past_due",
"cancelled",
"paused"
],
},
trial_ends_at: {
type: DataTypes.DATE,
},
current_period_start_at: {
type: DataTypes.DATE,
},
current_period_end_at: {
type: DataTypes.DATE,
},
included_rooms_limit: {
type: DataTypes.INTEGER,
},
included_users_limit: {
type: DataTypes.INTEGER,
},
stripe_subscription_reference: {
type: DataTypes.TEXT,
},
stripe_price_reference: {
type: DataTypes.TEXT,
},
auto_renew: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
subscriptions.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.subscriptions.belongsTo(db.hotels, {
as: 'hotel',
foreignKey: {
name: 'hotelId',
},
constraints: false,
});
db.subscriptions.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.subscriptions.belongsTo(db.users, {
as: 'createdBy',
});
db.subscriptions.belongsTo(db.users, {
as: 'updatedBy',
});
};
return subscriptions;
};

View File

@ -0,0 +1,278 @@
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.staff_profiles, {
as: 'staff_profiles_user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.users.hasMany(db.audit_logs, {
as: 'audit_logs_actor_user',
foreignKey: {
name: 'actor_userId',
},
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'});
};
};

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

@ -0,0 +1,255 @@
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 hotelsRoutes = require('./routes/hotels');
const departmentsRoutes = require('./routes/departments');
const staff_profilesRoutes = require('./routes/staff_profiles');
const shiftsRoutes = require('./routes/shifts');
const room_typesRoutes = require('./routes/room_types');
const roomsRoutes = require('./routes/rooms');
const guestsRoutes = require('./routes/guests');
const guest_documentsRoutes = require('./routes/guest_documents');
const rate_plansRoutes = require('./routes/rate_plans');
const seasonal_ratesRoutes = require('./routes/seasonal_rates');
const dynamic_pricing_rulesRoutes = require('./routes/dynamic_pricing_rules');
const sales_channelsRoutes = require('./routes/sales_channels');
const ota_connectionsRoutes = require('./routes/ota_connections');
const reservationsRoutes = require('./routes/reservations');
const reservation_guestsRoutes = require('./routes/reservation_guests');
const stay_foliosRoutes = require('./routes/stay_folios');
const folio_itemsRoutes = require('./routes/folio_items');
const paymentsRoutes = require('./routes/payments');
const refundsRoutes = require('./routes/refunds');
const invoicesRoutes = require('./routes/invoices');
const housekeeping_tasksRoutes = require('./routes/housekeeping_tasks');
const maintenance_ticketsRoutes = require('./routes/maintenance_tickets');
const notificationsRoutes = require('./routes/notifications');
const booking_widgetsRoutes = require('./routes/booking_widgets');
const subscriptionsRoutes = require('./routes/subscriptions');
const audit_logsRoutes = require('./routes/audit_logs');
const daily_snapshotsRoutes = require('./routes/daily_snapshots');
const getBaseUrl = (url) => {
if (!url) return '';
return url.endsWith('/api') ? url.slice(0, -4) : url;
};
const options = {
definition: {
openapi: "3.0.0",
info: {
version: "1.0.0",
title: "App Preview",
description: "App Preview Online REST API for Testing and Prototyping application. You can perform all major operations with your entities - create, delete and etc.",
},
servers: [
{
url: getBaseUrl(process.env.NEXT_PUBLIC_BACK_API) || config.swaggerUrl,
description: "Development server",
}
],
components: {
securitySchemes: {
bearerAuth: {
type: 'http',
scheme: 'bearer',
bearerFormat: 'JWT',
}
},
responses: {
UnauthorizedError: {
description: "Access token is missing or invalid"
}
}
},
security: [{
bearerAuth: []
}]
},
apis: ["./src/routes/*.js"],
};
const specs = swaggerJsDoc(options);
app.use('/api-docs', function (req, res, next) {
swaggerUI.host = getBaseUrl(process.env.NEXT_PUBLIC_BACK_API) || req.get('host');
next()
}, swaggerUI.serve, swaggerUI.setup(specs))
app.use(cors({origin: true}));
require('./auth/auth');
app.use(bodyParser.json());
app.use('/api/auth', authRoutes);
app.use('/api/file', fileRoutes);
app.use('/api/pexels', pexelsRoutes);
app.enable('trust proxy');
app.use('/api/users', passport.authenticate('jwt', {session: false}), usersRoutes);
app.use('/api/roles', passport.authenticate('jwt', {session: false}), rolesRoutes);
app.use('/api/permissions', passport.authenticate('jwt', {session: false}), permissionsRoutes);
app.use('/api/organizations', passport.authenticate('jwt', {session: false}), organizationsRoutes);
app.use('/api/hotels', passport.authenticate('jwt', {session: false}), hotelsRoutes);
app.use('/api/departments', passport.authenticate('jwt', {session: false}), departmentsRoutes);
app.use('/api/staff_profiles', passport.authenticate('jwt', {session: false}), staff_profilesRoutes);
app.use('/api/shifts', passport.authenticate('jwt', {session: false}), shiftsRoutes);
app.use('/api/room_types', passport.authenticate('jwt', {session: false}), room_typesRoutes);
app.use('/api/rooms', passport.authenticate('jwt', {session: false}), roomsRoutes);
app.use('/api/guests', passport.authenticate('jwt', {session: false}), guestsRoutes);
app.use('/api/guest_documents', passport.authenticate('jwt', {session: false}), guest_documentsRoutes);
app.use('/api/rate_plans', passport.authenticate('jwt', {session: false}), rate_plansRoutes);
app.use('/api/seasonal_rates', passport.authenticate('jwt', {session: false}), seasonal_ratesRoutes);
app.use('/api/dynamic_pricing_rules', passport.authenticate('jwt', {session: false}), dynamic_pricing_rulesRoutes);
app.use('/api/sales_channels', passport.authenticate('jwt', {session: false}), sales_channelsRoutes);
app.use('/api/ota_connections', passport.authenticate('jwt', {session: false}), ota_connectionsRoutes);
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/stay_folios', passport.authenticate('jwt', {session: false}), stay_foliosRoutes);
app.use('/api/folio_items', passport.authenticate('jwt', {session: false}), folio_itemsRoutes);
app.use('/api/payments', passport.authenticate('jwt', {session: false}), paymentsRoutes);
app.use('/api/refunds', passport.authenticate('jwt', {session: false}), refundsRoutes);
app.use('/api/invoices', passport.authenticate('jwt', {session: false}), invoicesRoutes);
app.use('/api/housekeeping_tasks', passport.authenticate('jwt', {session: false}), housekeeping_tasksRoutes);
app.use('/api/maintenance_tickets', passport.authenticate('jwt', {session: false}), maintenance_ticketsRoutes);
app.use('/api/notifications', passport.authenticate('jwt', {session: false}), notificationsRoutes);
app.use('/api/booking_widgets', passport.authenticate('jwt', {session: false}), booking_widgetsRoutes);
app.use('/api/subscriptions', passport.authenticate('jwt', {session: false}), subscriptionsRoutes);
app.use('/api/audit_logs', passport.authenticate('jwt', {session: false}), audit_logsRoutes);
app.use('/api/daily_snapshots', passport.authenticate('jwt', {session: false}), daily_snapshotsRoutes);
app.use(
'/api/openai',
passport.authenticate('jwt', { session: false }),
openaiRoutes,
);
app.use(
'/api/ai',
passport.authenticate('jwt', { session: false }),
openaiRoutes,
);
app.use(
'/api/search',
passport.authenticate('jwt', { session: false }),
searchRoutes);
app.use(
'/api/sql',
passport.authenticate('jwt', { session: false }),
sqlRoutes);
app.use(
'/api/org-for-auth',
organizationForAuthRoutes,
);
const publicDir = path.join(
__dirname,
'../public',
);
if (fs.existsSync(publicDir)) {
app.use('/', express.static(publicDir));
app.get('*', function(request, response) {
response.sendFile(
path.resolve(publicDir, 'index.html'),
);
});
}
const PORT = process.env.NODE_ENV === 'dev_stage' ? 3000 : 8080;
app.listen(PORT, () => {
console.log(`Listening on port ${PORT}`);
});
module.exports = app;

View File

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

View File

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

View File

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