Initial version

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

14
backend/.env Normal file
View File

@ -0,0 +1,14 @@
DB_NAME=app_38214
DB_USER=app_38214
DB_PASS=73b5f587-5e62-4ed7-9562-f0b286311caa
DB_HOST=127.0.0.1
DB_PORT=5432
PORT=3000
GOOGLE_CLIENT_ID=671001533244-kf1k1gmp6mnl0r030qmvdu6v36ghmim6.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET=Yo4qbKZniqvojzUQ60iKlxqR
MS_CLIENT_ID=4696f457-31af-40de-897c-e00d7d4cff73
MS_CLIENT_SECRET=m8jzZ.5UpHF3=-dXzyxiZ4e[F8OF54@p
EMAIL_USER=AKIAVEW7G4PQUBGM52OF
EMAIL_PASS=BLnD4hKGb6YkSz3gaQrf8fnyLi3C3/EdjOOsLEDTDPTz
SECRET_KEY=HUEyqESqgQ1yTwzVlO6wprC9Kf1J1xuA
PEXELS_KEY=Vc99rnmOhHhJAbgGQoKLZtsaIVfkeownoQNbTj78VemUjKh08ZYRbf18

4
backend/.eslintignore Normal file
View File

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

15
backend/.eslintrc.cjs Normal file
View File

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

11
backend/.prettierrc Normal file
View File

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

7
backend/.sequelizerc Normal file
View File

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

23
backend/Dockerfile Normal file
View File

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

56
backend/README.md Normal file
View File

@ -0,0 +1,56 @@
#CleanerOps SaaS - 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_cleanerops_saas;`
- Then give that new user privileges to the new database then quit the `psql`.
- `postgres=> GRANT ALL PRIVILEGES ON DATABASE db_cleanerops_saas 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": "cleaneropssaas",
"description": "CleanerOps SaaS - 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: "73b5f587",
user_pass: "f0b286311caa",
admin_email: "admin@flatlogic.com",
providers: {
LOCAL: 'local',
GOOGLE: 'google',
MICROSOFT: 'microsoft'
},
secret_key: process.env.SECRET_KEY || '73b5f587-5e62-4ed7-9562-f0b286311caa',
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: 'CleanerOps SaaS <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: 'Billing Specialist',
},
project_uuid: '73b5f587-5e62-4ed7-9562-f0b286311caa',
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 = 'Freshly cleaned empty room sunlight';
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,568 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Checklist_itemsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const checklist_items = await db.checklist_items.create(
{
id: data.id || undefined,
title: data.title
||
null
,
details: data.details
||
null
,
sort_order: data.sort_order
||
null
,
is_required: data.is_required
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await checklist_items.setWorkspace( data.workspace || null, {
transaction,
});
await checklist_items.setChecklist( data.checklist || null, {
transaction,
});
await checklist_items.setOrganizations( data.organizations || null, {
transaction,
});
return checklist_items;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const checklist_itemsData = data.map((item, index) => ({
id: item.id || undefined,
title: item.title
||
null
,
details: item.details
||
null
,
sort_order: item.sort_order
||
null
,
is_required: item.is_required
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const checklist_items = await db.checklist_items.bulkCreate(checklist_itemsData, { transaction });
// For each item created, replace relation files
return checklist_items;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const checklist_items = await db.checklist_items.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.title !== undefined) updatePayload.title = data.title;
if (data.details !== undefined) updatePayload.details = data.details;
if (data.sort_order !== undefined) updatePayload.sort_order = data.sort_order;
if (data.is_required !== undefined) updatePayload.is_required = data.is_required;
updatePayload.updatedById = currentUser.id;
await checklist_items.update(updatePayload, {transaction});
if (data.workspace !== undefined) {
await checklist_items.setWorkspace(
data.workspace,
{ transaction }
);
}
if (data.checklist !== undefined) {
await checklist_items.setChecklist(
data.checklist,
{ transaction }
);
}
if (data.organizations !== undefined) {
await checklist_items.setOrganizations(
data.organizations,
{ transaction }
);
}
return checklist_items;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const checklist_items = await db.checklist_items.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of checklist_items) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of checklist_items) {
await record.destroy({transaction});
}
});
return checklist_items;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const checklist_items = await db.checklist_items.findByPk(id, options);
await checklist_items.update({
deletedBy: currentUser.id
}, {
transaction,
});
await checklist_items.destroy({
transaction
});
return checklist_items;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const checklist_items = await db.checklist_items.findOne(
{ where },
{ transaction },
);
if (!checklist_items) {
return checklist_items;
}
const output = checklist_items.get({plain: true});
output.job_checklist_run_items_checklist_item = await checklist_items.getJob_checklist_run_items_checklist_item({
transaction
});
output.workspace = await checklist_items.getWorkspace({
transaction
});
output.checklist = await checklist_items.getChecklist({
transaction
});
output.organizations = await checklist_items.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.workspaces,
as: 'workspace',
where: filter.workspace ? {
[Op.or]: [
{ id: { [Op.in]: filter.workspace.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.workspace.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.checklists,
as: 'checklist',
where: filter.checklist ? {
[Op.or]: [
{ id: { [Op.in]: filter.checklist.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.checklist.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.title) {
where = {
...where,
[Op.and]: Utils.ilike(
'checklist_items',
'title',
filter.title,
),
};
}
if (filter.details) {
where = {
...where,
[Op.and]: Utils.ilike(
'checklist_items',
'details',
filter.details,
),
};
}
if (filter.sort_orderRange) {
const [start, end] = filter.sort_orderRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sort_order: {
...where.sort_order,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sort_order: {
...where.sort_order,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.is_required) {
where = {
...where,
is_required: filter.is_required,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.checklist_items.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'checklist_items',
'title',
query,
),
],
};
}
const records = await db.checklist_items.findAll({
attributes: [ 'id', 'title' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['title', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.title,
}));
}
};

View File

@ -0,0 +1,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 ChecklistsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const checklists = await db.checklists.create(
{
id: data.id || undefined,
name: data.name
||
null
,
scope: data.scope
||
null
,
description: data.description
||
null
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await checklists.setWorkspace( data.workspace || null, {
transaction,
});
await checklists.setOrganizations( data.organizations || null, {
transaction,
});
return checklists;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const checklistsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
scope: item.scope
||
null
,
description: item.description
||
null
,
is_active: item.is_active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const checklists = await db.checklists.bulkCreate(checklistsData, { transaction });
// For each item created, replace relation files
return checklists;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const checklists = await db.checklists.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.scope !== undefined) updatePayload.scope = data.scope;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await checklists.update(updatePayload, {transaction});
if (data.workspace !== undefined) {
await checklists.setWorkspace(
data.workspace,
{ transaction }
);
}
if (data.organizations !== undefined) {
await checklists.setOrganizations(
data.organizations,
{ transaction }
);
}
return checklists;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const checklists = await db.checklists.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of checklists) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of checklists) {
await record.destroy({transaction});
}
});
return checklists;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const checklists = await db.checklists.findByPk(id, options);
await checklists.update({
deletedBy: currentUser.id
}, {
transaction,
});
await checklists.destroy({
transaction
});
return checklists;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const checklists = await db.checklists.findOne(
{ where },
{ transaction },
);
if (!checklists) {
return checklists;
}
const output = checklists.get({plain: true});
output.checklist_items_checklist = await checklists.getChecklist_items_checklist({
transaction
});
output.job_checklist_runs_checklist = await checklists.getJob_checklist_runs_checklist({
transaction
});
output.workspace = await checklists.getWorkspace({
transaction
});
output.organizations = await checklists.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.workspaces,
as: 'workspace',
where: filter.workspace ? {
[Op.or]: [
{ id: { [Op.in]: filter.workspace.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.workspace.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(
'checklists',
'name',
filter.name,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'checklists',
'description',
filter.description,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.scope) {
where = {
...where,
scope: filter.scope,
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.checklists.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'checklists',
'name',
query,
),
],
};
}
const records = await db.checklists.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,606 @@
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 CustomersDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const customers = await db.customers.create(
{
id: data.id || undefined,
name: data.name
||
null
,
customer_type: data.customer_type
||
null
,
email: data.email
||
null
,
phone: data.phone
||
null
,
billing_address: data.billing_address
||
null
,
notes: data.notes
||
null
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await customers.setWorkspace( data.workspace || null, {
transaction,
});
await customers.setOrganizations( data.organizations || null, {
transaction,
});
return customers;
}
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 customersData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
customer_type: item.customer_type
||
null
,
email: item.email
||
null
,
phone: item.phone
||
null
,
billing_address: item.billing_address
||
null
,
notes: item.notes
||
null
,
is_active: item.is_active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const customers = await db.customers.bulkCreate(customersData, { transaction });
// For each item created, replace relation files
return customers;
}
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 customers = await db.customers.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.customer_type !== undefined) updatePayload.customer_type = data.customer_type;
if (data.email !== undefined) updatePayload.email = data.email;
if (data.phone !== undefined) updatePayload.phone = data.phone;
if (data.billing_address !== undefined) updatePayload.billing_address = data.billing_address;
if (data.notes !== undefined) updatePayload.notes = data.notes;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await customers.update(updatePayload, {transaction});
if (data.workspace !== undefined) {
await customers.setWorkspace(
data.workspace,
{ transaction }
);
}
if (data.organizations !== undefined) {
await customers.setOrganizations(
data.organizations,
{ transaction }
);
}
return customers;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const customers = await db.customers.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of customers) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of customers) {
await record.destroy({transaction});
}
});
return customers;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const customers = await db.customers.findByPk(id, options);
await customers.update({
deletedBy: currentUser.id
}, {
transaction,
});
await customers.destroy({
transaction
});
return customers;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const customers = await db.customers.findOne(
{ where },
{ transaction },
);
if (!customers) {
return customers;
}
const output = customers.get({plain: true});
output.properties_customer = await customers.getProperties_customer({
transaction
});
output.jobs_customer = await customers.getJobs_customer({
transaction
});
output.invoices_customer = await customers.getInvoices_customer({
transaction
});
output.payments_customer = await customers.getPayments_customer({
transaction
});
output.estimates_customer = await customers.getEstimates_customer({
transaction
});
output.recurring_schedules_customer = await customers.getRecurring_schedules_customer({
transaction
});
output.workspace = await customers.getWorkspace({
transaction
});
output.organizations = await customers.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.workspaces,
as: 'workspace',
where: filter.workspace ? {
[Op.or]: [
{ id: { [Op.in]: filter.workspace.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.workspace.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(
'customers',
'name',
filter.name,
),
};
}
if (filter.email) {
where = {
...where,
[Op.and]: Utils.ilike(
'customers',
'email',
filter.email,
),
};
}
if (filter.phone) {
where = {
...where,
[Op.and]: Utils.ilike(
'customers',
'phone',
filter.phone,
),
};
}
if (filter.billing_address) {
where = {
...where,
[Op.and]: Utils.ilike(
'customers',
'billing_address',
filter.billing_address,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'customers',
'notes',
filter.notes,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.customer_type) {
where = {
...where,
customer_type: filter.customer_type,
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.customers.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(
'customers',
'name',
query,
),
],
};
}
const records = await db.customers.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,629 @@
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 Estimate_line_itemsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const estimate_line_items = await db.estimate_line_items.create(
{
id: data.id || undefined,
description: data.description
||
null
,
quantity: data.quantity
||
null
,
unit_price: data.unit_price
||
null
,
line_total: data.line_total
||
null
,
sort_order: data.sort_order
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await estimate_line_items.setWorkspace( data.workspace || null, {
transaction,
});
await estimate_line_items.setEstimate( data.estimate || null, {
transaction,
});
await estimate_line_items.setOrganizations( data.organizations || null, {
transaction,
});
return estimate_line_items;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const estimate_line_itemsData = data.map((item, index) => ({
id: item.id || undefined,
description: item.description
||
null
,
quantity: item.quantity
||
null
,
unit_price: item.unit_price
||
null
,
line_total: item.line_total
||
null
,
sort_order: item.sort_order
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const estimate_line_items = await db.estimate_line_items.bulkCreate(estimate_line_itemsData, { transaction });
// For each item created, replace relation files
return estimate_line_items;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const estimate_line_items = await db.estimate_line_items.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.description !== undefined) updatePayload.description = data.description;
if (data.quantity !== undefined) updatePayload.quantity = data.quantity;
if (data.unit_price !== undefined) updatePayload.unit_price = data.unit_price;
if (data.line_total !== undefined) updatePayload.line_total = data.line_total;
if (data.sort_order !== undefined) updatePayload.sort_order = data.sort_order;
updatePayload.updatedById = currentUser.id;
await estimate_line_items.update(updatePayload, {transaction});
if (data.workspace !== undefined) {
await estimate_line_items.setWorkspace(
data.workspace,
{ transaction }
);
}
if (data.estimate !== undefined) {
await estimate_line_items.setEstimate(
data.estimate,
{ transaction }
);
}
if (data.organizations !== undefined) {
await estimate_line_items.setOrganizations(
data.organizations,
{ transaction }
);
}
return estimate_line_items;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const estimate_line_items = await db.estimate_line_items.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of estimate_line_items) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of estimate_line_items) {
await record.destroy({transaction});
}
});
return estimate_line_items;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const estimate_line_items = await db.estimate_line_items.findByPk(id, options);
await estimate_line_items.update({
deletedBy: currentUser.id
}, {
transaction,
});
await estimate_line_items.destroy({
transaction
});
return estimate_line_items;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const estimate_line_items = await db.estimate_line_items.findOne(
{ where },
{ transaction },
);
if (!estimate_line_items) {
return estimate_line_items;
}
const output = estimate_line_items.get({plain: true});
output.workspace = await estimate_line_items.getWorkspace({
transaction
});
output.estimate = await estimate_line_items.getEstimate({
transaction
});
output.organizations = await estimate_line_items.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.workspaces,
as: 'workspace',
where: filter.workspace ? {
[Op.or]: [
{ id: { [Op.in]: filter.workspace.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.workspace.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.estimates,
as: 'estimate',
where: filter.estimate ? {
[Op.or]: [
{ id: { [Op.in]: filter.estimate.split('|').map(term => Utils.uuid(term)) } },
{
estimate_number: {
[Op.or]: filter.estimate.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(
'estimate_line_items',
'description',
filter.description,
),
};
}
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.line_totalRange) {
const [start, end] = filter.line_totalRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
line_total: {
...where.line_total,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
line_total: {
...where.line_total,
[Op.lte]: end,
},
};
}
}
if (filter.sort_orderRange) {
const [start, end] = filter.sort_orderRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sort_order: {
...where.sort_order,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sort_order: {
...where.sort_order,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.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.estimate_line_items.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'estimate_line_items',
'description',
query,
),
],
};
}
const records = await db.estimate_line_items.findAll({
attributes: [ 'id', 'description' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['description', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.description,
}));
}
};

View File

@ -0,0 +1,788 @@
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 EstimatesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const estimates = await db.estimates.create(
{
id: data.id || undefined,
estimate_number: data.estimate_number
||
null
,
status: data.status
||
null
,
issue_date: data.issue_date
||
null
,
expires_at: data.expires_at
||
null
,
subtotal: data.subtotal
||
null
,
tax_amount: data.tax_amount
||
null
,
discount_amount: data.discount_amount
||
null
,
total: data.total
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await estimates.setWorkspace( data.workspace || null, {
transaction,
});
await estimates.setCustomer( data.customer || null, {
transaction,
});
await estimates.setProperty( data.property || null, {
transaction,
});
await estimates.setOrganizations( data.organizations || null, {
transaction,
});
return estimates;
}
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 estimatesData = data.map((item, index) => ({
id: item.id || undefined,
estimate_number: item.estimate_number
||
null
,
status: item.status
||
null
,
issue_date: item.issue_date
||
null
,
expires_at: item.expires_at
||
null
,
subtotal: item.subtotal
||
null
,
tax_amount: item.tax_amount
||
null
,
discount_amount: item.discount_amount
||
null
,
total: item.total
||
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 estimates = await db.estimates.bulkCreate(estimatesData, { transaction });
// For each item created, replace relation files
return estimates;
}
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 estimates = await db.estimates.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.estimate_number !== undefined) updatePayload.estimate_number = data.estimate_number;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.issue_date !== undefined) updatePayload.issue_date = data.issue_date;
if (data.expires_at !== undefined) updatePayload.expires_at = data.expires_at;
if (data.subtotal !== undefined) updatePayload.subtotal = data.subtotal;
if (data.tax_amount !== undefined) updatePayload.tax_amount = data.tax_amount;
if (data.discount_amount !== undefined) updatePayload.discount_amount = data.discount_amount;
if (data.total !== undefined) updatePayload.total = data.total;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await estimates.update(updatePayload, {transaction});
if (data.workspace !== undefined) {
await estimates.setWorkspace(
data.workspace,
{ transaction }
);
}
if (data.customer !== undefined) {
await estimates.setCustomer(
data.customer,
{ transaction }
);
}
if (data.property !== undefined) {
await estimates.setProperty(
data.property,
{ transaction }
);
}
if (data.organizations !== undefined) {
await estimates.setOrganizations(
data.organizations,
{ transaction }
);
}
return estimates;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const estimates = await db.estimates.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of estimates) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of estimates) {
await record.destroy({transaction});
}
});
return estimates;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const estimates = await db.estimates.findByPk(id, options);
await estimates.update({
deletedBy: currentUser.id
}, {
transaction,
});
await estimates.destroy({
transaction
});
return estimates;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const estimates = await db.estimates.findOne(
{ where },
{ transaction },
);
if (!estimates) {
return estimates;
}
const output = estimates.get({plain: true});
output.estimate_line_items_estimate = await estimates.getEstimate_line_items_estimate({
transaction
});
output.workspace = await estimates.getWorkspace({
transaction
});
output.customer = await estimates.getCustomer({
transaction
});
output.property = await estimates.getProperty({
transaction
});
output.organizations = await estimates.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.workspaces,
as: 'workspace',
where: filter.workspace ? {
[Op.or]: [
{ id: { [Op.in]: filter.workspace.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.workspace.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.customers,
as: 'customer',
where: filter.customer ? {
[Op.or]: [
{ id: { [Op.in]: filter.customer.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.customer.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.properties,
as: 'property',
where: filter.property ? {
[Op.or]: [
{ id: { [Op.in]: filter.property.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.property.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.estimate_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'estimates',
'estimate_number',
filter.estimate_number,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'estimates',
'notes',
filter.notes,
),
};
}
if (filter.issue_dateRange) {
const [start, end] = filter.issue_dateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
issue_date: {
...where.issue_date,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
issue_date: {
...where.issue_date,
[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.subtotalRange) {
const [start, end] = filter.subtotalRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
subtotal: {
...where.subtotal,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
subtotal: {
...where.subtotal,
[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.discount_amountRange) {
const [start, end] = filter.discount_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
discount_amount: {
...where.discount_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
discount_amount: {
...where.discount_amount,
[Op.lte]: end,
},
};
}
}
if (filter.totalRange) {
const [start, end] = filter.totalRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
total: {
...where.total,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
total: {
...where.total,
[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.estimates.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(
'estimates',
'estimate_number',
query,
),
],
};
}
const records = await db.estimates.findAll({
attributes: [ 'id', 'estimate_number' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['estimate_number', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.estimate_number,
}));
}
};

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,629 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Invoice_line_itemsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const invoice_line_items = await db.invoice_line_items.create(
{
id: data.id || undefined,
description: data.description
||
null
,
quantity: data.quantity
||
null
,
unit_price: data.unit_price
||
null
,
line_total: data.line_total
||
null
,
sort_order: data.sort_order
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await invoice_line_items.setWorkspace( data.workspace || null, {
transaction,
});
await invoice_line_items.setInvoice( data.invoice || null, {
transaction,
});
await invoice_line_items.setOrganizations( data.organizations || null, {
transaction,
});
return invoice_line_items;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const invoice_line_itemsData = data.map((item, index) => ({
id: item.id || undefined,
description: item.description
||
null
,
quantity: item.quantity
||
null
,
unit_price: item.unit_price
||
null
,
line_total: item.line_total
||
null
,
sort_order: item.sort_order
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const invoice_line_items = await db.invoice_line_items.bulkCreate(invoice_line_itemsData, { transaction });
// For each item created, replace relation files
return invoice_line_items;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const invoice_line_items = await db.invoice_line_items.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.description !== undefined) updatePayload.description = data.description;
if (data.quantity !== undefined) updatePayload.quantity = data.quantity;
if (data.unit_price !== undefined) updatePayload.unit_price = data.unit_price;
if (data.line_total !== undefined) updatePayload.line_total = data.line_total;
if (data.sort_order !== undefined) updatePayload.sort_order = data.sort_order;
updatePayload.updatedById = currentUser.id;
await invoice_line_items.update(updatePayload, {transaction});
if (data.workspace !== undefined) {
await invoice_line_items.setWorkspace(
data.workspace,
{ transaction }
);
}
if (data.invoice !== undefined) {
await invoice_line_items.setInvoice(
data.invoice,
{ transaction }
);
}
if (data.organizations !== undefined) {
await invoice_line_items.setOrganizations(
data.organizations,
{ transaction }
);
}
return invoice_line_items;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const invoice_line_items = await db.invoice_line_items.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of invoice_line_items) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of invoice_line_items) {
await record.destroy({transaction});
}
});
return invoice_line_items;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const invoice_line_items = await db.invoice_line_items.findByPk(id, options);
await invoice_line_items.update({
deletedBy: currentUser.id
}, {
transaction,
});
await invoice_line_items.destroy({
transaction
});
return invoice_line_items;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const invoice_line_items = await db.invoice_line_items.findOne(
{ where },
{ transaction },
);
if (!invoice_line_items) {
return invoice_line_items;
}
const output = invoice_line_items.get({plain: true});
output.workspace = await invoice_line_items.getWorkspace({
transaction
});
output.invoice = await invoice_line_items.getInvoice({
transaction
});
output.organizations = await invoice_line_items.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.workspaces,
as: 'workspace',
where: filter.workspace ? {
[Op.or]: [
{ id: { [Op.in]: filter.workspace.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.workspace.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.invoices,
as: 'invoice',
where: filter.invoice ? {
[Op.or]: [
{ id: { [Op.in]: filter.invoice.split('|').map(term => Utils.uuid(term)) } },
{
invoice_number: {
[Op.or]: filter.invoice.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'invoice_line_items',
'description',
filter.description,
),
};
}
if (filter.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.line_totalRange) {
const [start, end] = filter.line_totalRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
line_total: {
...where.line_total,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
line_total: {
...where.line_total,
[Op.lte]: end,
},
};
}
}
if (filter.sort_orderRange) {
const [start, end] = filter.sort_orderRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sort_order: {
...where.sort_order,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sort_order: {
...where.sort_order,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.invoice_line_items.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'invoice_line_items',
'description',
query,
),
],
};
}
const records = await db.invoice_line_items.findAll({
attributes: [ 'id', 'description' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['description', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.description,
}));
}
};

View File

@ -0,0 +1,792 @@
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
,
status: data.status
||
null
,
issue_date: data.issue_date
||
null
,
due_date: data.due_date
||
null
,
subtotal: data.subtotal
||
null
,
tax_amount: data.tax_amount
||
null
,
discount_amount: data.discount_amount
||
null
,
total: data.total
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await invoices.setWorkspace( data.workspace || null, {
transaction,
});
await invoices.setCustomer( data.customer || null, {
transaction,
});
await invoices.setJob( data.job || null, {
transaction,
});
await invoices.setOrganizations( data.organizations || null, {
transaction,
});
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
,
status: item.status
||
null
,
issue_date: item.issue_date
||
null
,
due_date: item.due_date
||
null
,
subtotal: item.subtotal
||
null
,
tax_amount: item.tax_amount
||
null
,
discount_amount: item.discount_amount
||
null
,
total: item.total
||
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 invoices = await db.invoices.bulkCreate(invoicesData, { transaction });
// For each item created, replace relation files
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.status !== undefined) updatePayload.status = data.status;
if (data.issue_date !== undefined) updatePayload.issue_date = data.issue_date;
if (data.due_date !== undefined) updatePayload.due_date = data.due_date;
if (data.subtotal !== undefined) updatePayload.subtotal = data.subtotal;
if (data.tax_amount !== undefined) updatePayload.tax_amount = data.tax_amount;
if (data.discount_amount !== undefined) updatePayload.discount_amount = data.discount_amount;
if (data.total !== undefined) updatePayload.total = data.total;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await invoices.update(updatePayload, {transaction});
if (data.workspace !== undefined) {
await invoices.setWorkspace(
data.workspace,
{ transaction }
);
}
if (data.customer !== undefined) {
await invoices.setCustomer(
data.customer,
{ transaction }
);
}
if (data.job !== undefined) {
await invoices.setJob(
data.job,
{ transaction }
);
}
if (data.organizations !== undefined) {
await invoices.setOrganizations(
data.organizations,
{ transaction }
);
}
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.invoice_line_items_invoice = await invoices.getInvoice_line_items_invoice({
transaction
});
output.payments_invoice = await invoices.getPayments_invoice({
transaction
});
output.workspace = await invoices.getWorkspace({
transaction
});
output.customer = await invoices.getCustomer({
transaction
});
output.job = await invoices.getJob({
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.workspaces,
as: 'workspace',
where: filter.workspace ? {
[Op.or]: [
{ id: { [Op.in]: filter.workspace.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.workspace.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.customers,
as: 'customer',
where: filter.customer ? {
[Op.or]: [
{ id: { [Op.in]: filter.customer.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.customer.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.jobs,
as: 'job',
where: filter.job ? {
[Op.or]: [
{ id: { [Op.in]: filter.job.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.job.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.invoice_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'invoices',
'invoice_number',
filter.invoice_number,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'invoices',
'notes',
filter.notes,
),
};
}
if (filter.issue_dateRange) {
const [start, end] = filter.issue_dateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
issue_date: {
...where.issue_date,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
issue_date: {
...where.issue_date,
[Op.lte]: end,
},
};
}
}
if (filter.due_dateRange) {
const [start, end] = filter.due_dateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
due_date: {
...where.due_date,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
due_date: {
...where.due_date,
[Op.lte]: end,
},
};
}
}
if (filter.subtotalRange) {
const [start, end] = filter.subtotalRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
subtotal: {
...where.subtotal,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
subtotal: {
...where.subtotal,
[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.discount_amountRange) {
const [start, end] = filter.discount_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
discount_amount: {
...where.discount_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
discount_amount: {
...where.discount_amount,
[Op.lte]: end,
},
};
}
}
if (filter.totalRange) {
const [start, end] = filter.totalRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
total: {
...where.total,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
total: {
...where.total,
[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,573 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Job_assignmentsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const job_assignments = await db.job_assignments.create(
{
id: data.id || undefined,
assignment_role: data.assignment_role
||
null
,
assigned_at: data.assigned_at
||
null
,
is_confirmed: data.is_confirmed
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await job_assignments.setWorkspace( data.workspace || null, {
transaction,
});
await job_assignments.setJob( data.job || null, {
transaction,
});
await job_assignments.setAssignee( data.assignee || null, {
transaction,
});
await job_assignments.setOrganizations( data.organizations || null, {
transaction,
});
return job_assignments;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const job_assignmentsData = data.map((item, index) => ({
id: item.id || undefined,
assignment_role: item.assignment_role
||
null
,
assigned_at: item.assigned_at
||
null
,
is_confirmed: item.is_confirmed
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const job_assignments = await db.job_assignments.bulkCreate(job_assignmentsData, { transaction });
// For each item created, replace relation files
return job_assignments;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const job_assignments = await db.job_assignments.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.assignment_role !== undefined) updatePayload.assignment_role = data.assignment_role;
if (data.assigned_at !== undefined) updatePayload.assigned_at = data.assigned_at;
if (data.is_confirmed !== undefined) updatePayload.is_confirmed = data.is_confirmed;
updatePayload.updatedById = currentUser.id;
await job_assignments.update(updatePayload, {transaction});
if (data.workspace !== undefined) {
await job_assignments.setWorkspace(
data.workspace,
{ transaction }
);
}
if (data.job !== undefined) {
await job_assignments.setJob(
data.job,
{ transaction }
);
}
if (data.assignee !== undefined) {
await job_assignments.setAssignee(
data.assignee,
{ transaction }
);
}
if (data.organizations !== undefined) {
await job_assignments.setOrganizations(
data.organizations,
{ transaction }
);
}
return job_assignments;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const job_assignments = await db.job_assignments.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of job_assignments) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of job_assignments) {
await record.destroy({transaction});
}
});
return job_assignments;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const job_assignments = await db.job_assignments.findByPk(id, options);
await job_assignments.update({
deletedBy: currentUser.id
}, {
transaction,
});
await job_assignments.destroy({
transaction
});
return job_assignments;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const job_assignments = await db.job_assignments.findOne(
{ where },
{ transaction },
);
if (!job_assignments) {
return job_assignments;
}
const output = job_assignments.get({plain: true});
output.workspace = await job_assignments.getWorkspace({
transaction
});
output.job = await job_assignments.getJob({
transaction
});
output.assignee = await job_assignments.getAssignee({
transaction
});
output.organizations = await job_assignments.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.workspaces,
as: 'workspace',
where: filter.workspace ? {
[Op.or]: [
{ id: { [Op.in]: filter.workspace.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.workspace.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.jobs,
as: 'job',
where: filter.job ? {
[Op.or]: [
{ id: { [Op.in]: filter.job.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.job.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'assignee',
where: filter.assignee ? {
[Op.or]: [
{ id: { [Op.in]: filter.assignee.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.assignee.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.assigned_atRange) {
const [start, end] = filter.assigned_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
assigned_at: {
...where.assigned_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
assigned_at: {
...where.assigned_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.assignment_role) {
where = {
...where,
assignment_role: filter.assignment_role,
};
}
if (filter.is_confirmed) {
where = {
...where,
is_confirmed: filter.is_confirmed,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.job_assignments.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'job_assignments',
'assignment_role',
query,
),
],
};
}
const records = await db.job_assignments.findAll({
attributes: [ 'id', 'assignment_role' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['assignment_role', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.assignment_role,
}));
}
};

View File

@ -0,0 +1,612 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Job_checklist_run_itemsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const job_checklist_run_items = await db.job_checklist_run_items.create(
{
id: data.id || undefined,
state: data.state
||
null
,
notes: data.notes
||
null
,
completed_at: data.completed_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await job_checklist_run_items.setWorkspace( data.workspace || null, {
transaction,
});
await job_checklist_run_items.setJob_checklist_run( data.job_checklist_run || null, {
transaction,
});
await job_checklist_run_items.setChecklist_item( data.checklist_item || null, {
transaction,
});
await job_checklist_run_items.setCompleted_by( data.completed_by || null, {
transaction,
});
await job_checklist_run_items.setOrganizations( data.organizations || null, {
transaction,
});
return job_checklist_run_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 job_checklist_run_itemsData = data.map((item, index) => ({
id: item.id || undefined,
state: item.state
||
null
,
notes: item.notes
||
null
,
completed_at: item.completed_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const job_checklist_run_items = await db.job_checklist_run_items.bulkCreate(job_checklist_run_itemsData, { transaction });
// For each item created, replace relation files
return job_checklist_run_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 job_checklist_run_items = await db.job_checklist_run_items.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.state !== undefined) updatePayload.state = data.state;
if (data.notes !== undefined) updatePayload.notes = data.notes;
if (data.completed_at !== undefined) updatePayload.completed_at = data.completed_at;
updatePayload.updatedById = currentUser.id;
await job_checklist_run_items.update(updatePayload, {transaction});
if (data.workspace !== undefined) {
await job_checklist_run_items.setWorkspace(
data.workspace,
{ transaction }
);
}
if (data.job_checklist_run !== undefined) {
await job_checklist_run_items.setJob_checklist_run(
data.job_checklist_run,
{ transaction }
);
}
if (data.checklist_item !== undefined) {
await job_checklist_run_items.setChecklist_item(
data.checklist_item,
{ transaction }
);
}
if (data.completed_by !== undefined) {
await job_checklist_run_items.setCompleted_by(
data.completed_by,
{ transaction }
);
}
if (data.organizations !== undefined) {
await job_checklist_run_items.setOrganizations(
data.organizations,
{ transaction }
);
}
return job_checklist_run_items;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const job_checklist_run_items = await db.job_checklist_run_items.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of job_checklist_run_items) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of job_checklist_run_items) {
await record.destroy({transaction});
}
});
return job_checklist_run_items;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const job_checklist_run_items = await db.job_checklist_run_items.findByPk(id, options);
await job_checklist_run_items.update({
deletedBy: currentUser.id
}, {
transaction,
});
await job_checklist_run_items.destroy({
transaction
});
return job_checklist_run_items;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const job_checklist_run_items = await db.job_checklist_run_items.findOne(
{ where },
{ transaction },
);
if (!job_checklist_run_items) {
return job_checklist_run_items;
}
const output = job_checklist_run_items.get({plain: true});
output.workspace = await job_checklist_run_items.getWorkspace({
transaction
});
output.job_checklist_run = await job_checklist_run_items.getJob_checklist_run({
transaction
});
output.checklist_item = await job_checklist_run_items.getChecklist_item({
transaction
});
output.completed_by = await job_checklist_run_items.getCompleted_by({
transaction
});
output.organizations = await job_checklist_run_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.workspaces,
as: 'workspace',
where: filter.workspace ? {
[Op.or]: [
{ id: { [Op.in]: filter.workspace.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.workspace.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.job_checklist_runs,
as: 'job_checklist_run',
where: filter.job_checklist_run ? {
[Op.or]: [
{ id: { [Op.in]: filter.job_checklist_run.split('|').map(term => Utils.uuid(term)) } },
{
status: {
[Op.or]: filter.job_checklist_run.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.checklist_items,
as: 'checklist_item',
where: filter.checklist_item ? {
[Op.or]: [
{ id: { [Op.in]: filter.checklist_item.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.checklist_item.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'completed_by',
where: filter.completed_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.completed_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.completed_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'job_checklist_run_items',
'notes',
filter.notes,
),
};
}
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.state) {
where = {
...where,
state: filter.state,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.job_checklist_run_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(
'job_checklist_run_items',
'state',
query,
),
],
};
}
const records = await db.job_checklist_run_items.findAll({
attributes: [ 'id', 'state' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['state', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.state,
}));
}
};

View File

@ -0,0 +1,592 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Job_checklist_runsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const job_checklist_runs = await db.job_checklist_runs.create(
{
id: data.id || undefined,
status: data.status
||
null
,
started_at: data.started_at
||
null
,
completed_at: data.completed_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await job_checklist_runs.setWorkspace( data.workspace || null, {
transaction,
});
await job_checklist_runs.setJob( data.job || null, {
transaction,
});
await job_checklist_runs.setChecklist( data.checklist || null, {
transaction,
});
await job_checklist_runs.setOrganizations( data.organizations || null, {
transaction,
});
return job_checklist_runs;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const job_checklist_runsData = data.map((item, index) => ({
id: item.id || undefined,
status: item.status
||
null
,
started_at: item.started_at
||
null
,
completed_at: item.completed_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const job_checklist_runs = await db.job_checklist_runs.bulkCreate(job_checklist_runsData, { transaction });
// For each item created, replace relation files
return job_checklist_runs;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const job_checklist_runs = await db.job_checklist_runs.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.status !== undefined) updatePayload.status = data.status;
if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
if (data.completed_at !== undefined) updatePayload.completed_at = data.completed_at;
updatePayload.updatedById = currentUser.id;
await job_checklist_runs.update(updatePayload, {transaction});
if (data.workspace !== undefined) {
await job_checklist_runs.setWorkspace(
data.workspace,
{ transaction }
);
}
if (data.job !== undefined) {
await job_checklist_runs.setJob(
data.job,
{ transaction }
);
}
if (data.checklist !== undefined) {
await job_checklist_runs.setChecklist(
data.checklist,
{ transaction }
);
}
if (data.organizations !== undefined) {
await job_checklist_runs.setOrganizations(
data.organizations,
{ transaction }
);
}
return job_checklist_runs;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const job_checklist_runs = await db.job_checklist_runs.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of job_checklist_runs) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of job_checklist_runs) {
await record.destroy({transaction});
}
});
return job_checklist_runs;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const job_checklist_runs = await db.job_checklist_runs.findByPk(id, options);
await job_checklist_runs.update({
deletedBy: currentUser.id
}, {
transaction,
});
await job_checklist_runs.destroy({
transaction
});
return job_checklist_runs;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const job_checklist_runs = await db.job_checklist_runs.findOne(
{ where },
{ transaction },
);
if (!job_checklist_runs) {
return job_checklist_runs;
}
const output = job_checklist_runs.get({plain: true});
output.job_checklist_run_items_job_checklist_run = await job_checklist_runs.getJob_checklist_run_items_job_checklist_run({
transaction
});
output.workspace = await job_checklist_runs.getWorkspace({
transaction
});
output.job = await job_checklist_runs.getJob({
transaction
});
output.checklist = await job_checklist_runs.getChecklist({
transaction
});
output.organizations = await job_checklist_runs.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.workspaces,
as: 'workspace',
where: filter.workspace ? {
[Op.or]: [
{ id: { [Op.in]: filter.workspace.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.workspace.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.jobs,
as: 'job',
where: filter.job ? {
[Op.or]: [
{ id: { [Op.in]: filter.job.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.job.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.checklists,
as: 'checklist',
where: filter.checklist ? {
[Op.or]: [
{ id: { [Op.in]: filter.checklist.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.checklist.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.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.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.job_checklist_runs.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'job_checklist_runs',
'status',
query,
),
],
};
}
const records = await db.job_checklist_runs.findAll({
attributes: [ 'id', 'status' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['status', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.status,
}));
}
};

View File

@ -0,0 +1,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 Job_mediaDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const job_media = await db.job_media.create(
{
id: data.id || undefined,
media_type: data.media_type
||
null
,
caption: data.caption
||
null
,
uploaded_at: data.uploaded_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await job_media.setWorkspace( data.workspace || null, {
transaction,
});
await job_media.setJob( data.job || null, {
transaction,
});
await job_media.setUploaded_by( data.uploaded_by || null, {
transaction,
});
await job_media.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.job_media.getTableName(),
belongsToColumn: 'photos',
belongsToId: job_media.id,
},
data.photos,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.job_media.getTableName(),
belongsToColumn: 'attachments',
belongsToId: job_media.id,
},
data.attachments,
options,
);
return job_media;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const job_mediaData = data.map((item, index) => ({
id: item.id || undefined,
media_type: item.media_type
||
null
,
caption: item.caption
||
null
,
uploaded_at: item.uploaded_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const job_media = await db.job_media.bulkCreate(job_mediaData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < job_media.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.job_media.getTableName(),
belongsToColumn: 'photos',
belongsToId: job_media[i].id,
},
data[i].photos,
options,
);
}
for (let i = 0; i < job_media.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.job_media.getTableName(),
belongsToColumn: 'attachments',
belongsToId: job_media[i].id,
},
data[i].attachments,
options,
);
}
return job_media;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const job_media = await db.job_media.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.media_type !== undefined) updatePayload.media_type = data.media_type;
if (data.caption !== undefined) updatePayload.caption = data.caption;
if (data.uploaded_at !== undefined) updatePayload.uploaded_at = data.uploaded_at;
updatePayload.updatedById = currentUser.id;
await job_media.update(updatePayload, {transaction});
if (data.workspace !== undefined) {
await job_media.setWorkspace(
data.workspace,
{ transaction }
);
}
if (data.job !== undefined) {
await job_media.setJob(
data.job,
{ transaction }
);
}
if (data.uploaded_by !== undefined) {
await job_media.setUploaded_by(
data.uploaded_by,
{ transaction }
);
}
if (data.organizations !== undefined) {
await job_media.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.job_media.getTableName(),
belongsToColumn: 'photos',
belongsToId: job_media.id,
},
data.photos,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.job_media.getTableName(),
belongsToColumn: 'attachments',
belongsToId: job_media.id,
},
data.attachments,
options,
);
return job_media;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const job_media = await db.job_media.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of job_media) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of job_media) {
await record.destroy({transaction});
}
});
return job_media;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const job_media = await db.job_media.findByPk(id, options);
await job_media.update({
deletedBy: currentUser.id
}, {
transaction,
});
await job_media.destroy({
transaction
});
return job_media;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const job_media = await db.job_media.findOne(
{ where },
{ transaction },
);
if (!job_media) {
return job_media;
}
const output = job_media.get({plain: true});
output.workspace = await job_media.getWorkspace({
transaction
});
output.job = await job_media.getJob({
transaction
});
output.photos = await job_media.getPhotos({
transaction
});
output.attachments = await job_media.getAttachments({
transaction
});
output.uploaded_by = await job_media.getUploaded_by({
transaction
});
output.organizations = await job_media.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.workspaces,
as: 'workspace',
where: filter.workspace ? {
[Op.or]: [
{ id: { [Op.in]: filter.workspace.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.workspace.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.jobs,
as: 'job',
where: filter.job ? {
[Op.or]: [
{ id: { [Op.in]: filter.job.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.job.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'uploaded_by',
where: filter.uploaded_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.uploaded_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.uploaded_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'photos',
},
{
model: db.file,
as: 'attachments',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.caption) {
where = {
...where,
[Op.and]: Utils.ilike(
'job_media',
'caption',
filter.caption,
),
};
}
if (filter.uploaded_atRange) {
const [start, end] = filter.uploaded_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
uploaded_at: {
...where.uploaded_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
uploaded_at: {
...where.uploaded_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.media_type) {
where = {
...where,
media_type: filter.media_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.job_media.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'job_media',
'caption',
query,
),
],
};
}
const records = await db.job_media.findAll({
attributes: [ 'id', 'caption' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['caption', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.caption,
}));
}
};

View File

@ -0,0 +1,601 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Job_templatesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const job_templates = await db.job_templates.create(
{
id: data.id || undefined,
name: data.name
||
null
,
default_price: data.default_price
||
null
,
default_duration_minutes: data.default_duration_minutes
||
null
,
default_instructions: data.default_instructions
||
null
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await job_templates.setWorkspace( data.workspace || null, {
transaction,
});
await job_templates.setService_catalog_item( data.service_catalog_item || null, {
transaction,
});
await job_templates.setOrganizations( data.organizations || null, {
transaction,
});
return job_templates;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const job_templatesData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
default_price: item.default_price
||
null
,
default_duration_minutes: item.default_duration_minutes
||
null
,
default_instructions: item.default_instructions
||
null
,
is_active: item.is_active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const job_templates = await db.job_templates.bulkCreate(job_templatesData, { transaction });
// For each item created, replace relation files
return job_templates;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const job_templates = await db.job_templates.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.default_price !== undefined) updatePayload.default_price = data.default_price;
if (data.default_duration_minutes !== undefined) updatePayload.default_duration_minutes = data.default_duration_minutes;
if (data.default_instructions !== undefined) updatePayload.default_instructions = data.default_instructions;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await job_templates.update(updatePayload, {transaction});
if (data.workspace !== undefined) {
await job_templates.setWorkspace(
data.workspace,
{ transaction }
);
}
if (data.service_catalog_item !== undefined) {
await job_templates.setService_catalog_item(
data.service_catalog_item,
{ transaction }
);
}
if (data.organizations !== undefined) {
await job_templates.setOrganizations(
data.organizations,
{ transaction }
);
}
return job_templates;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const job_templates = await db.job_templates.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of job_templates) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of job_templates) {
await record.destroy({transaction});
}
});
return job_templates;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const job_templates = await db.job_templates.findByPk(id, options);
await job_templates.update({
deletedBy: currentUser.id
}, {
transaction,
});
await job_templates.destroy({
transaction
});
return job_templates;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const job_templates = await db.job_templates.findOne(
{ where },
{ transaction },
);
if (!job_templates) {
return job_templates;
}
const output = job_templates.get({plain: true});
output.workspace = await job_templates.getWorkspace({
transaction
});
output.service_catalog_item = await job_templates.getService_catalog_item({
transaction
});
output.organizations = await job_templates.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.workspaces,
as: 'workspace',
where: filter.workspace ? {
[Op.or]: [
{ id: { [Op.in]: filter.workspace.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.workspace.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.service_catalog_items,
as: 'service_catalog_item',
where: filter.service_catalog_item ? {
[Op.or]: [
{ id: { [Op.in]: filter.service_catalog_item.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.service_catalog_item.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'job_templates',
'name',
filter.name,
),
};
}
if (filter.default_instructions) {
where = {
...where,
[Op.and]: Utils.ilike(
'job_templates',
'default_instructions',
filter.default_instructions,
),
};
}
if (filter.default_priceRange) {
const [start, end] = filter.default_priceRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
default_price: {
...where.default_price,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
default_price: {
...where.default_price,
[Op.lte]: end,
},
};
}
}
if (filter.default_duration_minutesRange) {
const [start, end] = filter.default_duration_minutesRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
default_duration_minutes: {
...where.default_duration_minutes,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
default_duration_minutes: {
...where.default_duration_minutes,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.job_templates.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'job_templates',
'name',
query,
),
],
};
}
const records = await db.job_templates.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,
}));
}
};

827
backend/src/db/api/jobs.js Normal file
View File

@ -0,0 +1,827 @@
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 JobsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const jobs = await db.jobs.create(
{
id: data.id || undefined,
title: data.title
||
null
,
status: data.status
||
null
,
start_at: data.start_at
||
null
,
end_at: data.end_at
||
null
,
estimated_duration_minutes: data.estimated_duration_minutes
||
null
,
price: data.price
||
null
,
instructions: data.instructions
||
null
,
internal_notes: data.internal_notes
||
null
,
requires_invoice: data.requires_invoice
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await jobs.setWorkspace( data.workspace || null, {
transaction,
});
await jobs.setCustomer( data.customer || null, {
transaction,
});
await jobs.setProperty( data.property || null, {
transaction,
});
await jobs.setService_catalog_item( data.service_catalog_item || null, {
transaction,
});
await jobs.setOrganizations( data.organizations || null, {
transaction,
});
return jobs;
}
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 jobsData = data.map((item, index) => ({
id: item.id || undefined,
title: item.title
||
null
,
status: item.status
||
null
,
start_at: item.start_at
||
null
,
end_at: item.end_at
||
null
,
estimated_duration_minutes: item.estimated_duration_minutes
||
null
,
price: item.price
||
null
,
instructions: item.instructions
||
null
,
internal_notes: item.internal_notes
||
null
,
requires_invoice: item.requires_invoice
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const jobs = await db.jobs.bulkCreate(jobsData, { transaction });
// For each item created, replace relation files
return jobs;
}
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 jobs = await db.jobs.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.title !== undefined) updatePayload.title = data.title;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.start_at !== undefined) updatePayload.start_at = data.start_at;
if (data.end_at !== undefined) updatePayload.end_at = data.end_at;
if (data.estimated_duration_minutes !== undefined) updatePayload.estimated_duration_minutes = data.estimated_duration_minutes;
if (data.price !== undefined) updatePayload.price = data.price;
if (data.instructions !== undefined) updatePayload.instructions = data.instructions;
if (data.internal_notes !== undefined) updatePayload.internal_notes = data.internal_notes;
if (data.requires_invoice !== undefined) updatePayload.requires_invoice = data.requires_invoice;
updatePayload.updatedById = currentUser.id;
await jobs.update(updatePayload, {transaction});
if (data.workspace !== undefined) {
await jobs.setWorkspace(
data.workspace,
{ transaction }
);
}
if (data.customer !== undefined) {
await jobs.setCustomer(
data.customer,
{ transaction }
);
}
if (data.property !== undefined) {
await jobs.setProperty(
data.property,
{ transaction }
);
}
if (data.service_catalog_item !== undefined) {
await jobs.setService_catalog_item(
data.service_catalog_item,
{ transaction }
);
}
if (data.organizations !== undefined) {
await jobs.setOrganizations(
data.organizations,
{ transaction }
);
}
return jobs;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const jobs = await db.jobs.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of jobs) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of jobs) {
await record.destroy({transaction});
}
});
return jobs;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const jobs = await db.jobs.findByPk(id, options);
await jobs.update({
deletedBy: currentUser.id
}, {
transaction,
});
await jobs.destroy({
transaction
});
return jobs;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const jobs = await db.jobs.findOne(
{ where },
{ transaction },
);
if (!jobs) {
return jobs;
}
const output = jobs.get({plain: true});
output.job_assignments_job = await jobs.getJob_assignments_job({
transaction
});
output.job_checklist_runs_job = await jobs.getJob_checklist_runs_job({
transaction
});
output.job_media_job = await jobs.getJob_media_job({
transaction
});
output.invoices_job = await jobs.getInvoices_job({
transaction
});
output.workspace = await jobs.getWorkspace({
transaction
});
output.customer = await jobs.getCustomer({
transaction
});
output.property = await jobs.getProperty({
transaction
});
output.service_catalog_item = await jobs.getService_catalog_item({
transaction
});
output.organizations = await jobs.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.workspaces,
as: 'workspace',
where: filter.workspace ? {
[Op.or]: [
{ id: { [Op.in]: filter.workspace.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.workspace.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.customers,
as: 'customer',
where: filter.customer ? {
[Op.or]: [
{ id: { [Op.in]: filter.customer.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.customer.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.properties,
as: 'property',
where: filter.property ? {
[Op.or]: [
{ id: { [Op.in]: filter.property.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.property.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.service_catalog_items,
as: 'service_catalog_item',
where: filter.service_catalog_item ? {
[Op.or]: [
{ id: { [Op.in]: filter.service_catalog_item.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.service_catalog_item.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.title) {
where = {
...where,
[Op.and]: Utils.ilike(
'jobs',
'title',
filter.title,
),
};
}
if (filter.instructions) {
where = {
...where,
[Op.and]: Utils.ilike(
'jobs',
'instructions',
filter.instructions,
),
};
}
if (filter.internal_notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'jobs',
'internal_notes',
filter.internal_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.estimated_duration_minutesRange) {
const [start, end] = filter.estimated_duration_minutesRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
estimated_duration_minutes: {
...where.estimated_duration_minutes,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
estimated_duration_minutes: {
...where.estimated_duration_minutes,
[Op.lte]: end,
},
};
}
}
if (filter.priceRange) {
const [start, end] = filter.priceRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
price: {
...where.price,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
price: {
...where.price,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.requires_invoice) {
where = {
...where,
requires_invoice: filter.requires_invoice,
};
}
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.jobs.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(
'jobs',
'title',
query,
),
],
};
}
const records = await db.jobs.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,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 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
,
event_type: data.event_type
||
null
,
subject: data.subject
||
null
,
message: data.message
||
null
,
scheduled_at: data.scheduled_at
||
null
,
sent_at: data.sent_at
||
null
,
status: data.status
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await notifications.setWorkspace( data.workspace || null, {
transaction,
});
await notifications.setUser( data.user || null, {
transaction,
});
await notifications.setOrganizations( data.organizations || null, {
transaction,
});
return notifications;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const notificationsData = data.map((item, index) => ({
id: item.id || undefined,
channel: item.channel
||
null
,
event_type: item.event_type
||
null
,
subject: item.subject
||
null
,
message: item.message
||
null
,
scheduled_at: item.scheduled_at
||
null
,
sent_at: item.sent_at
||
null
,
status: item.status
||
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.event_type !== undefined) updatePayload.event_type = data.event_type;
if (data.subject !== undefined) updatePayload.subject = data.subject;
if (data.message !== undefined) updatePayload.message = data.message;
if (data.scheduled_at !== undefined) updatePayload.scheduled_at = data.scheduled_at;
if (data.sent_at !== undefined) updatePayload.sent_at = data.sent_at;
if (data.status !== undefined) updatePayload.status = data.status;
updatePayload.updatedById = currentUser.id;
await notifications.update(updatePayload, {transaction});
if (data.workspace !== undefined) {
await notifications.setWorkspace(
data.workspace,
{ transaction }
);
}
if (data.user !== undefined) {
await notifications.setUser(
data.user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await notifications.setOrganizations(
data.organizations,
{ transaction }
);
}
return notifications;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const notifications = await db.notifications.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of notifications) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of notifications) {
await record.destroy({transaction});
}
});
return notifications;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const notifications = await db.notifications.findByPk(id, options);
await notifications.update({
deletedBy: currentUser.id
}, {
transaction,
});
await notifications.destroy({
transaction
});
return notifications;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const notifications = await db.notifications.findOne(
{ where },
{ transaction },
);
if (!notifications) {
return notifications;
}
const output = notifications.get({plain: true});
output.workspace = await notifications.getWorkspace({
transaction
});
output.user = await notifications.getUser({
transaction
});
output.organizations = await notifications.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.workspaces,
as: 'workspace',
where: filter.workspace ? {
[Op.or]: [
{ id: { [Op.in]: filter.workspace.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.workspace.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'user',
where: filter.user ? {
[Op.or]: [
{ id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.subject) {
where = {
...where,
[Op.and]: Utils.ilike(
'notifications',
'subject',
filter.subject,
),
};
}
if (filter.message) {
where = {
...where,
[Op.and]: Utils.ilike(
'notifications',
'message',
filter.message,
),
};
}
if (filter.scheduled_atRange) {
const [start, end] = filter.scheduled_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
scheduled_at: {
...where.scheduled_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
scheduled_at: {
...where.scheduled_at,
[Op.lte]: end,
},
};
}
}
if (filter.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.event_type) {
where = {
...where,
event_type: filter.event_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,466 @@
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.workspaces_organizations = await organizations.getWorkspaces_organizations({
transaction
});
output.workspace_memberships_organizations = await organizations.getWorkspace_memberships_organizations({
transaction
});
output.service_catalog_items_organizations = await organizations.getService_catalog_items_organizations({
transaction
});
output.customers_organizations = await organizations.getCustomers_organizations({
transaction
});
output.properties_organizations = await organizations.getProperties_organizations({
transaction
});
output.job_templates_organizations = await organizations.getJob_templates_organizations({
transaction
});
output.jobs_organizations = await organizations.getJobs_organizations({
transaction
});
output.job_assignments_organizations = await organizations.getJob_assignments_organizations({
transaction
});
output.checklists_organizations = await organizations.getChecklists_organizations({
transaction
});
output.checklist_items_organizations = await organizations.getChecklist_items_organizations({
transaction
});
output.job_checklist_runs_organizations = await organizations.getJob_checklist_runs_organizations({
transaction
});
output.job_checklist_run_items_organizations = await organizations.getJob_checklist_run_items_organizations({
transaction
});
output.job_media_organizations = await organizations.getJob_media_organizations({
transaction
});
output.invoices_organizations = await organizations.getInvoices_organizations({
transaction
});
output.invoice_line_items_organizations = await organizations.getInvoice_line_items_organizations({
transaction
});
output.payments_organizations = await organizations.getPayments_organizations({
transaction
});
output.estimates_organizations = await organizations.getEstimates_organizations({
transaction
});
output.estimate_line_items_organizations = await organizations.getEstimate_line_items_organizations({
transaction
});
output.recurring_schedules_organizations = await organizations.getRecurring_schedules_organizations({
transaction
});
output.notifications_organizations = await organizations.getNotifications_organizations({
transaction
});
output.support_tickets_organizations = await organizations.getSupport_tickets_organizations({
transaction
});
output.plans_organizations = await organizations.getPlans_organizations({
transaction
});
output.subscriptions_organizations = await organizations.getSubscriptions_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,656 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class 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,
amount: data.amount
||
null
,
method: data.method
||
null
,
status: data.status
||
null
,
paid_at: data.paid_at
||
null
,
reference: data.reference
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await payments.setWorkspace( data.workspace || null, {
transaction,
});
await payments.setInvoice( data.invoice || null, {
transaction,
});
await payments.setCustomer( data.customer || 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,
amount: item.amount
||
null
,
method: item.method
||
null
,
status: item.status
||
null
,
paid_at: item.paid_at
||
null
,
reference: item.reference
||
null
,
notes: item.notes
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const payments = await db.payments.bulkCreate(paymentsData, { transaction });
// For each item created, replace relation files
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.amount !== undefined) updatePayload.amount = data.amount;
if (data.method !== undefined) updatePayload.method = data.method;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.paid_at !== undefined) updatePayload.paid_at = data.paid_at;
if (data.reference !== undefined) updatePayload.reference = data.reference;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await payments.update(updatePayload, {transaction});
if (data.workspace !== undefined) {
await payments.setWorkspace(
data.workspace,
{ transaction }
);
}
if (data.invoice !== undefined) {
await payments.setInvoice(
data.invoice,
{ transaction }
);
}
if (data.customer !== undefined) {
await payments.setCustomer(
data.customer,
{ 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.workspace = await payments.getWorkspace({
transaction
});
output.invoice = await payments.getInvoice({
transaction
});
output.customer = await payments.getCustomer({
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.workspaces,
as: 'workspace',
where: filter.workspace ? {
[Op.or]: [
{ id: { [Op.in]: filter.workspace.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.workspace.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.invoices,
as: 'invoice',
where: filter.invoice ? {
[Op.or]: [
{ id: { [Op.in]: filter.invoice.split('|').map(term => Utils.uuid(term)) } },
{
invoice_number: {
[Op.or]: filter.invoice.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.customers,
as: 'customer',
where: filter.customer ? {
[Op.or]: [
{ id: { [Op.in]: filter.customer.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.customer.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.reference) {
where = {
...where,
[Op.and]: Utils.ilike(
'payments',
'reference',
filter.reference,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'payments',
'notes',
filter.notes,
),
};
}
if (filter.amountRange) {
const [start, end] = filter.amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
amount: {
...where.amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
amount: {
...where.amount,
[Op.lte]: end,
},
};
}
}
if (filter.paid_atRange) {
const [start, end] = filter.paid_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
paid_at: {
...where.paid_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
paid_at: {
...where.paid_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.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',
'reference',
query,
),
],
};
}
const records = await db.payments.findAll({
attributes: [ 'id', 'reference' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['reference', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.reference,
}));
}
};

View File

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

612
backend/src/db/api/plans.js Normal file
View File

@ -0,0 +1,612 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class PlansDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const plans = await db.plans.create(
{
id: data.id || undefined,
name: data.name
||
null
,
code: data.code
||
null
,
billing_interval: data.billing_interval
||
null
,
price: data.price
||
null
,
max_users: data.max_users
||
null
,
max_jobs_per_month: data.max_jobs_per_month
||
null
,
is_active: data.is_active
||
false
,
description: data.description
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await plans.setOrganizations( data.organizations || null, {
transaction,
});
return 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 plansData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
code: item.code
||
null
,
billing_interval: item.billing_interval
||
null
,
price: item.price
||
null
,
max_users: item.max_users
||
null
,
max_jobs_per_month: item.max_jobs_per_month
||
null
,
is_active: item.is_active
||
false
,
description: item.description
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const plans = await db.plans.bulkCreate(plansData, { transaction });
// For each item created, replace relation files
return 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 plans = await db.plans.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.code !== undefined) updatePayload.code = data.code;
if (data.billing_interval !== undefined) updatePayload.billing_interval = data.billing_interval;
if (data.price !== undefined) updatePayload.price = data.price;
if (data.max_users !== undefined) updatePayload.max_users = data.max_users;
if (data.max_jobs_per_month !== undefined) updatePayload.max_jobs_per_month = data.max_jobs_per_month;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
if (data.description !== undefined) updatePayload.description = data.description;
updatePayload.updatedById = currentUser.id;
await plans.update(updatePayload, {transaction});
if (data.organizations !== undefined) {
await plans.setOrganizations(
data.organizations,
{ transaction }
);
}
return plans;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const plans = await db.plans.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of plans) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of plans) {
await record.destroy({transaction});
}
});
return plans;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const plans = await db.plans.findByPk(id, options);
await plans.update({
deletedBy: currentUser.id
}, {
transaction,
});
await plans.destroy({
transaction
});
return plans;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const plans = await db.plans.findOne(
{ where },
{ transaction },
);
if (!plans) {
return plans;
}
const output = plans.get({plain: true});
output.subscriptions_plan = await plans.getSubscriptions_plan({
transaction
});
output.organizations = await 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.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'plans',
'name',
filter.name,
),
};
}
if (filter.code) {
where = {
...where,
[Op.and]: Utils.ilike(
'plans',
'code',
filter.code,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'plans',
'description',
filter.description,
),
};
}
if (filter.priceRange) {
const [start, end] = filter.priceRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
price: {
...where.price,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
price: {
...where.price,
[Op.lte]: end,
},
};
}
}
if (filter.max_usersRange) {
const [start, end] = filter.max_usersRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
max_users: {
...where.max_users,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
max_users: {
...where.max_users,
[Op.lte]: end,
},
};
}
}
if (filter.max_jobs_per_monthRange) {
const [start, end] = filter.max_jobs_per_monthRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
max_jobs_per_month: {
...where.max_jobs_per_month,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
max_jobs_per_month: {
...where.max_jobs_per_month,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.billing_interval) {
where = {
...where,
billing_interval: filter.billing_interval,
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.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(
'plans',
'name',
query,
),
],
};
}
const records = await db.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,770 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class PropertiesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const properties = await db.properties.create(
{
id: data.id || undefined,
name: data.name
||
null
,
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
,
access_instructions: data.access_instructions
||
null
,
bedrooms: data.bedrooms
||
null
,
bathrooms: data.bathrooms
||
null
,
square_feet: data.square_feet
||
null
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await properties.setWorkspace( data.workspace || null, {
transaction,
});
await properties.setCustomer( data.customer || null, {
transaction,
});
await properties.setOrganizations( data.organizations || null, {
transaction,
});
return properties;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const propertiesData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
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
,
access_instructions: item.access_instructions
||
null
,
bedrooms: item.bedrooms
||
null
,
bathrooms: item.bathrooms
||
null
,
square_feet: item.square_feet
||
null
,
is_active: item.is_active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const properties = await db.properties.bulkCreate(propertiesData, { transaction });
// For each item created, replace relation files
return properties;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const properties = await db.properties.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.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.access_instructions !== undefined) updatePayload.access_instructions = data.access_instructions;
if (data.bedrooms !== undefined) updatePayload.bedrooms = data.bedrooms;
if (data.bathrooms !== undefined) updatePayload.bathrooms = data.bathrooms;
if (data.square_feet !== undefined) updatePayload.square_feet = data.square_feet;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await properties.update(updatePayload, {transaction});
if (data.workspace !== undefined) {
await properties.setWorkspace(
data.workspace,
{ transaction }
);
}
if (data.customer !== undefined) {
await properties.setCustomer(
data.customer,
{ transaction }
);
}
if (data.organizations !== undefined) {
await properties.setOrganizations(
data.organizations,
{ transaction }
);
}
return properties;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const properties = await db.properties.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of properties) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of properties) {
await record.destroy({transaction});
}
});
return properties;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const properties = await db.properties.findByPk(id, options);
await properties.update({
deletedBy: currentUser.id
}, {
transaction,
});
await properties.destroy({
transaction
});
return properties;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const properties = await db.properties.findOne(
{ where },
{ transaction },
);
if (!properties) {
return properties;
}
const output = properties.get({plain: true});
output.jobs_property = await properties.getJobs_property({
transaction
});
output.estimates_property = await properties.getEstimates_property({
transaction
});
output.recurring_schedules_property = await properties.getRecurring_schedules_property({
transaction
});
output.workspace = await properties.getWorkspace({
transaction
});
output.customer = await properties.getCustomer({
transaction
});
output.organizations = await properties.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.workspaces,
as: 'workspace',
where: filter.workspace ? {
[Op.or]: [
{ id: { [Op.in]: filter.workspace.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.workspace.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.customers,
as: 'customer',
where: filter.customer ? {
[Op.or]: [
{ id: { [Op.in]: filter.customer.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.customer.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(
'properties',
'name',
filter.name,
),
};
}
if (filter.address_line1) {
where = {
...where,
[Op.and]: Utils.ilike(
'properties',
'address_line1',
filter.address_line1,
),
};
}
if (filter.address_line2) {
where = {
...where,
[Op.and]: Utils.ilike(
'properties',
'address_line2',
filter.address_line2,
),
};
}
if (filter.city) {
where = {
...where,
[Op.and]: Utils.ilike(
'properties',
'city',
filter.city,
),
};
}
if (filter.state_region) {
where = {
...where,
[Op.and]: Utils.ilike(
'properties',
'state_region',
filter.state_region,
),
};
}
if (filter.postal_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'properties',
'postal_code',
filter.postal_code,
),
};
}
if (filter.access_instructions) {
where = {
...where,
[Op.and]: Utils.ilike(
'properties',
'access_instructions',
filter.access_instructions,
),
};
}
if (filter.bedroomsRange) {
const [start, end] = filter.bedroomsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
bedrooms: {
...where.bedrooms,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
bedrooms: {
...where.bedrooms,
[Op.lte]: end,
},
};
}
}
if (filter.bathroomsRange) {
const [start, end] = filter.bathroomsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
bathrooms: {
...where.bathrooms,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
bathrooms: {
...where.bathrooms,
[Op.lte]: end,
},
};
}
}
if (filter.square_feetRange) {
const [start, end] = filter.square_feetRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
square_feet: {
...where.square_feet,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
square_feet: {
...where.square_feet,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
if (filter.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.properties.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'properties',
'name',
query,
),
],
};
}
const records = await db.properties.findAll({
attributes: [ 'id', 'name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.name,
}));
}
};

View File

@ -0,0 +1,807 @@
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 Recurring_schedulesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const recurring_schedules = await db.recurring_schedules.create(
{
id: data.id || undefined,
name: data.name
||
null
,
frequency: data.frequency
||
null
,
interval_count: data.interval_count
||
null
,
day_of_week: data.day_of_week
||
null
,
day_of_month: data.day_of_month
||
null
,
start_at: data.start_at
||
null
,
end_at: data.end_at
||
null
,
is_active: data.is_active
||
false
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await recurring_schedules.setWorkspace( data.workspace || null, {
transaction,
});
await recurring_schedules.setCustomer( data.customer || null, {
transaction,
});
await recurring_schedules.setProperty( data.property || null, {
transaction,
});
await recurring_schedules.setService_catalog_item( data.service_catalog_item || null, {
transaction,
});
await recurring_schedules.setOrganizations( data.organizations || null, {
transaction,
});
return recurring_schedules;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const recurring_schedulesData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
frequency: item.frequency
||
null
,
interval_count: item.interval_count
||
null
,
day_of_week: item.day_of_week
||
null
,
day_of_month: item.day_of_month
||
null
,
start_at: item.start_at
||
null
,
end_at: item.end_at
||
null
,
is_active: item.is_active
||
false
,
notes: item.notes
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const recurring_schedules = await db.recurring_schedules.bulkCreate(recurring_schedulesData, { transaction });
// For each item created, replace relation files
return recurring_schedules;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const recurring_schedules = await db.recurring_schedules.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.frequency !== undefined) updatePayload.frequency = data.frequency;
if (data.interval_count !== undefined) updatePayload.interval_count = data.interval_count;
if (data.day_of_week !== undefined) updatePayload.day_of_week = data.day_of_week;
if (data.day_of_month !== undefined) updatePayload.day_of_month = data.day_of_month;
if (data.start_at !== undefined) updatePayload.start_at = data.start_at;
if (data.end_at !== undefined) updatePayload.end_at = data.end_at;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await recurring_schedules.update(updatePayload, {transaction});
if (data.workspace !== undefined) {
await recurring_schedules.setWorkspace(
data.workspace,
{ transaction }
);
}
if (data.customer !== undefined) {
await recurring_schedules.setCustomer(
data.customer,
{ transaction }
);
}
if (data.property !== undefined) {
await recurring_schedules.setProperty(
data.property,
{ transaction }
);
}
if (data.service_catalog_item !== undefined) {
await recurring_schedules.setService_catalog_item(
data.service_catalog_item,
{ transaction }
);
}
if (data.organizations !== undefined) {
await recurring_schedules.setOrganizations(
data.organizations,
{ transaction }
);
}
return recurring_schedules;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const recurring_schedules = await db.recurring_schedules.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of recurring_schedules) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of recurring_schedules) {
await record.destroy({transaction});
}
});
return recurring_schedules;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const recurring_schedules = await db.recurring_schedules.findByPk(id, options);
await recurring_schedules.update({
deletedBy: currentUser.id
}, {
transaction,
});
await recurring_schedules.destroy({
transaction
});
return recurring_schedules;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const recurring_schedules = await db.recurring_schedules.findOne(
{ where },
{ transaction },
);
if (!recurring_schedules) {
return recurring_schedules;
}
const output = recurring_schedules.get({plain: true});
output.workspace = await recurring_schedules.getWorkspace({
transaction
});
output.customer = await recurring_schedules.getCustomer({
transaction
});
output.property = await recurring_schedules.getProperty({
transaction
});
output.service_catalog_item = await recurring_schedules.getService_catalog_item({
transaction
});
output.organizations = await recurring_schedules.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.workspaces,
as: 'workspace',
where: filter.workspace ? {
[Op.or]: [
{ id: { [Op.in]: filter.workspace.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.workspace.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.customers,
as: 'customer',
where: filter.customer ? {
[Op.or]: [
{ id: { [Op.in]: filter.customer.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.customer.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.properties,
as: 'property',
where: filter.property ? {
[Op.or]: [
{ id: { [Op.in]: filter.property.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.property.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.service_catalog_items,
as: 'service_catalog_item',
where: filter.service_catalog_item ? {
[Op.or]: [
{ id: { [Op.in]: filter.service_catalog_item.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.service_catalog_item.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'recurring_schedules',
'name',
filter.name,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'recurring_schedules',
'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.interval_countRange) {
const [start, end] = filter.interval_countRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
interval_count: {
...where.interval_count,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
interval_count: {
...where.interval_count,
[Op.lte]: end,
},
};
}
}
if (filter.day_of_monthRange) {
const [start, end] = filter.day_of_monthRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
day_of_month: {
...where.day_of_month,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
day_of_month: {
...where.day_of_month,
[Op.lte]: end,
},
};
}
}
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.frequency) {
where = {
...where,
frequency: filter.frequency,
};
}
if (filter.day_of_week) {
where = {
...where,
day_of_week: filter.day_of_week,
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.recurring_schedules.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'recurring_schedules',
'name',
query,
),
],
};
}
const records = await db.recurring_schedules.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,
}));
}
};

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

@ -0,0 +1,458 @@
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,596 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Service_catalog_itemsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const service_catalog_items = await db.service_catalog_items.create(
{
id: data.id || undefined,
name: data.name
||
null
,
description: data.description
||
null
,
pricing_model: data.pricing_model
||
null
,
base_price: data.base_price
||
null
,
hourly_rate: data.hourly_rate
||
null
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await service_catalog_items.setWorkspace( data.workspace || null, {
transaction,
});
await service_catalog_items.setOrganizations( data.organizations || null, {
transaction,
});
return service_catalog_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 service_catalog_itemsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
description: item.description
||
null
,
pricing_model: item.pricing_model
||
null
,
base_price: item.base_price
||
null
,
hourly_rate: item.hourly_rate
||
null
,
is_active: item.is_active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const service_catalog_items = await db.service_catalog_items.bulkCreate(service_catalog_itemsData, { transaction });
// For each item created, replace relation files
return service_catalog_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 service_catalog_items = await db.service_catalog_items.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.pricing_model !== undefined) updatePayload.pricing_model = data.pricing_model;
if (data.base_price !== undefined) updatePayload.base_price = data.base_price;
if (data.hourly_rate !== undefined) updatePayload.hourly_rate = data.hourly_rate;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await service_catalog_items.update(updatePayload, {transaction});
if (data.workspace !== undefined) {
await service_catalog_items.setWorkspace(
data.workspace,
{ transaction }
);
}
if (data.organizations !== undefined) {
await service_catalog_items.setOrganizations(
data.organizations,
{ transaction }
);
}
return service_catalog_items;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const service_catalog_items = await db.service_catalog_items.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of service_catalog_items) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of service_catalog_items) {
await record.destroy({transaction});
}
});
return service_catalog_items;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const service_catalog_items = await db.service_catalog_items.findByPk(id, options);
await service_catalog_items.update({
deletedBy: currentUser.id
}, {
transaction,
});
await service_catalog_items.destroy({
transaction
});
return service_catalog_items;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const service_catalog_items = await db.service_catalog_items.findOne(
{ where },
{ transaction },
);
if (!service_catalog_items) {
return service_catalog_items;
}
const output = service_catalog_items.get({plain: true});
output.job_templates_service_catalog_item = await service_catalog_items.getJob_templates_service_catalog_item({
transaction
});
output.jobs_service_catalog_item = await service_catalog_items.getJobs_service_catalog_item({
transaction
});
output.recurring_schedules_service_catalog_item = await service_catalog_items.getRecurring_schedules_service_catalog_item({
transaction
});
output.workspace = await service_catalog_items.getWorkspace({
transaction
});
output.organizations = await service_catalog_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.workspaces,
as: 'workspace',
where: filter.workspace ? {
[Op.or]: [
{ id: { [Op.in]: filter.workspace.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.workspace.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(
'service_catalog_items',
'name',
filter.name,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'service_catalog_items',
'description',
filter.description,
),
};
}
if (filter.base_priceRange) {
const [start, end] = filter.base_priceRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
base_price: {
...where.base_price,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
base_price: {
...where.base_price,
[Op.lte]: end,
},
};
}
}
if (filter.hourly_rateRange) {
const [start, end] = filter.hourly_rateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
hourly_rate: {
...where.hourly_rate,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
hourly_rate: {
...where.hourly_rate,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.pricing_model) {
where = {
...where,
pricing_model: filter.pricing_model,
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.service_catalog_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(
'service_catalog_items',
'name',
query,
),
],
};
}
const records = await db.service_catalog_items.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,636 @@
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,
status: data.status
||
null
,
current_period_start: data.current_period_start
||
null
,
current_period_end: data.current_period_end
||
null
,
canceled_at: data.canceled_at
||
null
,
provider: data.provider
||
null
,
provider_subscription_ref: data.provider_subscription_ref
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await subscriptions.setWorkspace( data.workspace || null, {
transaction,
});
await subscriptions.setPlan( data.plan || 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,
status: item.status
||
null
,
current_period_start: item.current_period_start
||
null
,
current_period_end: item.current_period_end
||
null
,
canceled_at: item.canceled_at
||
null
,
provider: item.provider
||
null
,
provider_subscription_ref: item.provider_subscription_ref
||
null
,
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.status !== undefined) updatePayload.status = data.status;
if (data.current_period_start !== undefined) updatePayload.current_period_start = data.current_period_start;
if (data.current_period_end !== undefined) updatePayload.current_period_end = data.current_period_end;
if (data.canceled_at !== undefined) updatePayload.canceled_at = data.canceled_at;
if (data.provider !== undefined) updatePayload.provider = data.provider;
if (data.provider_subscription_ref !== undefined) updatePayload.provider_subscription_ref = data.provider_subscription_ref;
updatePayload.updatedById = currentUser.id;
await subscriptions.update(updatePayload, {transaction});
if (data.workspace !== undefined) {
await subscriptions.setWorkspace(
data.workspace,
{ transaction }
);
}
if (data.plan !== undefined) {
await subscriptions.setPlan(
data.plan,
{ 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.workspace = await subscriptions.getWorkspace({
transaction
});
output.plan = await subscriptions.getPlan({
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.workspaces,
as: 'workspace',
where: filter.workspace ? {
[Op.or]: [
{ id: { [Op.in]: filter.workspace.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.workspace.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.plans,
as: 'plan',
where: filter.plan ? {
[Op.or]: [
{ id: { [Op.in]: filter.plan.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.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.provider) {
where = {
...where,
[Op.and]: Utils.ilike(
'subscriptions',
'provider',
filter.provider,
),
};
}
if (filter.provider_subscription_ref) {
where = {
...where,
[Op.and]: Utils.ilike(
'subscriptions',
'provider_subscription_ref',
filter.provider_subscription_ref,
),
};
}
if (filter.current_period_startRange) {
const [start, end] = filter.current_period_startRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
current_period_start: {
...where.current_period_start,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
current_period_start: {
...where.current_period_start,
[Op.lte]: end,
},
};
}
}
if (filter.current_period_endRange) {
const [start, end] = filter.current_period_endRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
current_period_end: {
...where.current_period_end,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
current_period_end: {
...where.current_period_end,
[Op.lte]: end,
},
};
}
}
if (filter.canceled_atRange) {
const [start, end] = filter.canceled_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
canceled_at: {
...where.canceled_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
canceled_at: {
...where.canceled_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.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',
'provider_subscription_ref',
query,
),
],
};
}
const records = await db.subscriptions.findAll({
attributes: [ 'id', 'provider_subscription_ref' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['provider_subscription_ref', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.provider_subscription_ref,
}));
}
};

View File

@ -0,0 +1,661 @@
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 Support_ticketsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const support_tickets = await db.support_tickets.create(
{
id: data.id || undefined,
status: data.status
||
null
,
priority: data.priority
||
null
,
subject: data.subject
||
null
,
description: data.description
||
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 support_tickets.setWorkspace( data.workspace || null, {
transaction,
});
await support_tickets.setRequester( data.requester || null, {
transaction,
});
await support_tickets.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.support_tickets.getTableName(),
belongsToColumn: 'attachments',
belongsToId: support_tickets.id,
},
data.attachments,
options,
);
return support_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 support_ticketsData = data.map((item, index) => ({
id: item.id || undefined,
status: item.status
||
null
,
priority: item.priority
||
null
,
subject: item.subject
||
null
,
description: item.description
||
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 support_tickets = await db.support_tickets.bulkCreate(support_ticketsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < support_tickets.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.support_tickets.getTableName(),
belongsToColumn: 'attachments',
belongsToId: support_tickets[i].id,
},
data[i].attachments,
options,
);
}
return support_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 support_tickets = await db.support_tickets.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.status !== undefined) updatePayload.status = data.status;
if (data.priority !== undefined) updatePayload.priority = data.priority;
if (data.subject !== undefined) updatePayload.subject = data.subject;
if (data.description !== undefined) updatePayload.description = data.description;
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 support_tickets.update(updatePayload, {transaction});
if (data.workspace !== undefined) {
await support_tickets.setWorkspace(
data.workspace,
{ transaction }
);
}
if (data.requester !== undefined) {
await support_tickets.setRequester(
data.requester,
{ transaction }
);
}
if (data.organizations !== undefined) {
await support_tickets.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.support_tickets.getTableName(),
belongsToColumn: 'attachments',
belongsToId: support_tickets.id,
},
data.attachments,
options,
);
return support_tickets;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const support_tickets = await db.support_tickets.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of support_tickets) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of support_tickets) {
await record.destroy({transaction});
}
});
return support_tickets;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const support_tickets = await db.support_tickets.findByPk(id, options);
await support_tickets.update({
deletedBy: currentUser.id
}, {
transaction,
});
await support_tickets.destroy({
transaction
});
return support_tickets;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const support_tickets = await db.support_tickets.findOne(
{ where },
{ transaction },
);
if (!support_tickets) {
return support_tickets;
}
const output = support_tickets.get({plain: true});
output.workspace = await support_tickets.getWorkspace({
transaction
});
output.requester = await support_tickets.getRequester({
transaction
});
output.attachments = await support_tickets.getAttachments({
transaction
});
output.organizations = await support_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.workspaces,
as: 'workspace',
where: filter.workspace ? {
[Op.or]: [
{ id: { [Op.in]: filter.workspace.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.workspace.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'requester',
where: filter.requester ? {
[Op.or]: [
{ id: { [Op.in]: filter.requester.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.requester.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.subject) {
where = {
...where,
[Op.and]: Utils.ilike(
'support_tickets',
'subject',
filter.subject,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'support_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.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.priority) {
where = {
...where,
priority: filter.priority,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.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.support_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(
'support_tickets',
'subject',
query,
),
],
};
}
const records = await db.support_tickets.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,
}));
}
};

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

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,573 @@
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 Workspace_membershipsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const workspace_memberships = await db.workspace_memberships.create(
{
id: data.id || undefined,
role: data.role
||
null
,
is_invited: data.is_invited
||
false
,
invited_at: data.invited_at
||
null
,
joined_at: data.joined_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await workspace_memberships.setWorkspace( data.workspace || null, {
transaction,
});
await workspace_memberships.setUser( data.user || null, {
transaction,
});
await workspace_memberships.setOrganizations( data.organizations || null, {
transaction,
});
return workspace_memberships;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const workspace_membershipsData = data.map((item, index) => ({
id: item.id || undefined,
role: item.role
||
null
,
is_invited: item.is_invited
||
false
,
invited_at: item.invited_at
||
null
,
joined_at: item.joined_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const workspace_memberships = await db.workspace_memberships.bulkCreate(workspace_membershipsData, { transaction });
// For each item created, replace relation files
return workspace_memberships;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const workspace_memberships = await db.workspace_memberships.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.role !== undefined) updatePayload.role = data.role;
if (data.is_invited !== undefined) updatePayload.is_invited = data.is_invited;
if (data.invited_at !== undefined) updatePayload.invited_at = data.invited_at;
if (data.joined_at !== undefined) updatePayload.joined_at = data.joined_at;
updatePayload.updatedById = currentUser.id;
await workspace_memberships.update(updatePayload, {transaction});
if (data.workspace !== undefined) {
await workspace_memberships.setWorkspace(
data.workspace,
{ transaction }
);
}
if (data.user !== undefined) {
await workspace_memberships.setUser(
data.user,
{ transaction }
);
}
if (data.organizations !== undefined) {
await workspace_memberships.setOrganizations(
data.organizations,
{ transaction }
);
}
return workspace_memberships;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const workspace_memberships = await db.workspace_memberships.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of workspace_memberships) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of workspace_memberships) {
await record.destroy({transaction});
}
});
return workspace_memberships;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const workspace_memberships = await db.workspace_memberships.findByPk(id, options);
await workspace_memberships.update({
deletedBy: currentUser.id
}, {
transaction,
});
await workspace_memberships.destroy({
transaction
});
return workspace_memberships;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const workspace_memberships = await db.workspace_memberships.findOne(
{ where },
{ transaction },
);
if (!workspace_memberships) {
return workspace_memberships;
}
const output = workspace_memberships.get({plain: true});
output.workspace = await workspace_memberships.getWorkspace({
transaction
});
output.user = await workspace_memberships.getUser({
transaction
});
output.organizations = await workspace_memberships.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.workspaces,
as: 'workspace',
where: filter.workspace ? {
[Op.or]: [
{ id: { [Op.in]: filter.workspace.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.workspace.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'user',
where: filter.user ? {
[Op.or]: [
{ id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.invited_atRange) {
const [start, end] = filter.invited_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
invited_at: {
...where.invited_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
invited_at: {
...where.invited_at,
[Op.lte]: end,
},
};
}
}
if (filter.joined_atRange) {
const [start, end] = filter.joined_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
joined_at: {
...where.joined_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
joined_at: {
...where.joined_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.role) {
where = {
...where,
role: filter.role,
};
}
if (filter.is_invited) {
where = {
...where,
is_invited: filter.is_invited,
};
}
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.workspace_memberships.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'workspace_memberships',
'role',
query,
),
],
};
}
const records = await db.workspace_memberships.findAll({
attributes: [ 'id', 'role' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['role', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.role,
}));
}
};

View File

@ -0,0 +1,657 @@
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 WorkspacesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const workspaces = await db.workspaces.create(
{
id: data.id || undefined,
name: data.name
||
null
,
slug: data.slug
||
null
,
status: data.status
||
null
,
trial_ends_at: data.trial_ends_at
||
null
,
timezone: data.timezone
||
null
,
currency: data.currency
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await workspaces.setOwner( data.owner || null, {
transaction,
});
await workspaces.setOrganizations( data.organizations || null, {
transaction,
});
return workspaces;
}
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 workspacesData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
slug: item.slug
||
null
,
status: item.status
||
null
,
trial_ends_at: item.trial_ends_at
||
null
,
timezone: item.timezone
||
null
,
currency: item.currency
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const workspaces = await db.workspaces.bulkCreate(workspacesData, { transaction });
// For each item created, replace relation files
return workspaces;
}
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 workspaces = await db.workspaces.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.slug !== undefined) updatePayload.slug = data.slug;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.trial_ends_at !== undefined) updatePayload.trial_ends_at = data.trial_ends_at;
if (data.timezone !== undefined) updatePayload.timezone = data.timezone;
if (data.currency !== undefined) updatePayload.currency = data.currency;
updatePayload.updatedById = currentUser.id;
await workspaces.update(updatePayload, {transaction});
if (data.owner !== undefined) {
await workspaces.setOwner(
data.owner,
{ transaction }
);
}
if (data.organizations !== undefined) {
await workspaces.setOrganizations(
data.organizations,
{ transaction }
);
}
return workspaces;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const workspaces = await db.workspaces.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of workspaces) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of workspaces) {
await record.destroy({transaction});
}
});
return workspaces;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const workspaces = await db.workspaces.findByPk(id, options);
await workspaces.update({
deletedBy: currentUser.id
}, {
transaction,
});
await workspaces.destroy({
transaction
});
return workspaces;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const workspaces = await db.workspaces.findOne(
{ where },
{ transaction },
);
if (!workspaces) {
return workspaces;
}
const output = workspaces.get({plain: true});
output.workspace_memberships_workspace = await workspaces.getWorkspace_memberships_workspace({
transaction
});
output.service_catalog_items_workspace = await workspaces.getService_catalog_items_workspace({
transaction
});
output.customers_workspace = await workspaces.getCustomers_workspace({
transaction
});
output.properties_workspace = await workspaces.getProperties_workspace({
transaction
});
output.job_templates_workspace = await workspaces.getJob_templates_workspace({
transaction
});
output.jobs_workspace = await workspaces.getJobs_workspace({
transaction
});
output.job_assignments_workspace = await workspaces.getJob_assignments_workspace({
transaction
});
output.checklists_workspace = await workspaces.getChecklists_workspace({
transaction
});
output.checklist_items_workspace = await workspaces.getChecklist_items_workspace({
transaction
});
output.job_checklist_runs_workspace = await workspaces.getJob_checklist_runs_workspace({
transaction
});
output.job_checklist_run_items_workspace = await workspaces.getJob_checklist_run_items_workspace({
transaction
});
output.job_media_workspace = await workspaces.getJob_media_workspace({
transaction
});
output.invoices_workspace = await workspaces.getInvoices_workspace({
transaction
});
output.invoice_line_items_workspace = await workspaces.getInvoice_line_items_workspace({
transaction
});
output.payments_workspace = await workspaces.getPayments_workspace({
transaction
});
output.estimates_workspace = await workspaces.getEstimates_workspace({
transaction
});
output.estimate_line_items_workspace = await workspaces.getEstimate_line_items_workspace({
transaction
});
output.recurring_schedules_workspace = await workspaces.getRecurring_schedules_workspace({
transaction
});
output.notifications_workspace = await workspaces.getNotifications_workspace({
transaction
});
output.support_tickets_workspace = await workspaces.getSupport_tickets_workspace({
transaction
});
output.subscriptions_workspace = await workspaces.getSubscriptions_workspace({
transaction
});
output.owner = await workspaces.getOwner({
transaction
});
output.organizations = await workspaces.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.users,
as: 'owner',
where: filter.owner ? {
[Op.or]: [
{ id: { [Op.in]: filter.owner.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.owner.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(
'workspaces',
'name',
filter.name,
),
};
}
if (filter.slug) {
where = {
...where,
[Op.and]: Utils.ilike(
'workspaces',
'slug',
filter.slug,
),
};
}
if (filter.timezone) {
where = {
...where,
[Op.and]: Utils.ilike(
'workspaces',
'timezone',
filter.timezone,
),
};
}
if (filter.currency) {
where = {
...where,
[Op.and]: Utils.ilike(
'workspaces',
'currency',
filter.currency,
),
};
}
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.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.workspaces.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(
'workspaces',
'name',
query,
),
],
};
}
const records = await db.workspaces.findAll({
attributes: [ 'id', 'name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.name,
}));
}
};

View File

@ -0,0 +1,33 @@
module.exports = {
production: {
dialect: 'postgres',
username: process.env.DB_USER,
password: process.env.DB_PASS,
database: process.env.DB_NAME,
host: process.env.DB_HOST,
port: process.env.DB_PORT,
logging: console.log,
seederStorage: 'sequelize',
},
development: {
username: 'postgres',
dialect: 'postgres',
password: '',
database: 'db_cleanerops_saas',
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,148 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const checklist_items = sequelize.define(
'checklist_items',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
title: {
type: DataTypes.TEXT,
},
details: {
type: DataTypes.TEXT,
},
sort_order: {
type: DataTypes.INTEGER,
},
is_required: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
checklist_items.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.checklist_items.hasMany(db.job_checklist_run_items, {
as: 'job_checklist_run_items_checklist_item',
foreignKey: {
name: 'checklist_itemId',
},
constraints: false,
});
//end loop
db.checklist_items.belongsTo(db.workspaces, {
as: 'workspace',
foreignKey: {
name: 'workspaceId',
},
constraints: false,
});
db.checklist_items.belongsTo(db.checklists, {
as: 'checklist',
foreignKey: {
name: 'checklistId',
},
constraints: false,
});
db.checklist_items.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.checklist_items.belongsTo(db.users, {
as: 'createdBy',
});
db.checklist_items.belongsTo(db.users, {
as: 'updatedBy',
});
};
return checklist_items;
};

View File

@ -0,0 +1,160 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const checklists = sequelize.define(
'checklists',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
scope: {
type: DataTypes.ENUM,
values: [
"job",
"property",
"service"
],
},
description: {
type: DataTypes.TEXT,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
checklists.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.checklists.hasMany(db.checklist_items, {
as: 'checklist_items_checklist',
foreignKey: {
name: 'checklistId',
},
constraints: false,
});
db.checklists.hasMany(db.job_checklist_runs, {
as: 'job_checklist_runs_checklist',
foreignKey: {
name: 'checklistId',
},
constraints: false,
});
//end loop
db.checklists.belongsTo(db.workspaces, {
as: 'workspace',
foreignKey: {
name: 'workspaceId',
},
constraints: false,
});
db.checklists.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.checklists.belongsTo(db.users, {
as: 'createdBy',
});
db.checklists.belongsTo(db.users, {
as: 'updatedBy',
});
};
return checklists;
};

View File

@ -0,0 +1,210 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const customers = sequelize.define(
'customers',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
customer_type: {
type: DataTypes.ENUM,
values: [
"residential",
"commercial"
],
},
email: {
type: DataTypes.TEXT,
},
phone: {
type: DataTypes.TEXT,
},
billing_address: {
type: DataTypes.TEXT,
},
notes: {
type: DataTypes.TEXT,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
customers.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.customers.hasMany(db.properties, {
as: 'properties_customer',
foreignKey: {
name: 'customerId',
},
constraints: false,
});
db.customers.hasMany(db.jobs, {
as: 'jobs_customer',
foreignKey: {
name: 'customerId',
},
constraints: false,
});
db.customers.hasMany(db.invoices, {
as: 'invoices_customer',
foreignKey: {
name: 'customerId',
},
constraints: false,
});
db.customers.hasMany(db.payments, {
as: 'payments_customer',
foreignKey: {
name: 'customerId',
},
constraints: false,
});
db.customers.hasMany(db.estimates, {
as: 'estimates_customer',
foreignKey: {
name: 'customerId',
},
constraints: false,
});
db.customers.hasMany(db.recurring_schedules, {
as: 'recurring_schedules_customer',
foreignKey: {
name: 'customerId',
},
constraints: false,
});
//end loop
db.customers.belongsTo(db.workspaces, {
as: 'workspace',
foreignKey: {
name: 'workspaceId',
},
constraints: false,
});
db.customers.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.customers.belongsTo(db.users, {
as: 'createdBy',
});
db.customers.belongsTo(db.users, {
as: 'updatedBy',
});
};
return customers;
};

View File

@ -0,0 +1,144 @@
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 estimate_line_items = sequelize.define(
'estimate_line_items',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
description: {
type: DataTypes.TEXT,
},
quantity: {
type: DataTypes.INTEGER,
},
unit_price: {
type: DataTypes.DECIMAL,
},
line_total: {
type: DataTypes.DECIMAL,
},
sort_order: {
type: DataTypes.INTEGER,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
estimate_line_items.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.estimate_line_items.belongsTo(db.workspaces, {
as: 'workspace',
foreignKey: {
name: 'workspaceId',
},
constraints: false,
});
db.estimate_line_items.belongsTo(db.estimates, {
as: 'estimate',
foreignKey: {
name: 'estimateId',
},
constraints: false,
});
db.estimate_line_items.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.estimate_line_items.belongsTo(db.users, {
as: 'createdBy',
});
db.estimate_line_items.belongsTo(db.users, {
as: 'updatedBy',
});
};
return estimate_line_items;
};

View File

@ -0,0 +1,206 @@
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 estimates = sequelize.define(
'estimates',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
estimate_number: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"draft",
"sent",
"accepted",
"declined",
"expired"
],
},
issue_date: {
type: DataTypes.DATE,
},
expires_at: {
type: DataTypes.DATE,
},
subtotal: {
type: DataTypes.DECIMAL,
},
tax_amount: {
type: DataTypes.DECIMAL,
},
discount_amount: {
type: DataTypes.DECIMAL,
},
total: {
type: DataTypes.DECIMAL,
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
estimates.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.estimates.hasMany(db.estimate_line_items, {
as: 'estimate_line_items_estimate',
foreignKey: {
name: 'estimateId',
},
constraints: false,
});
//end loop
db.estimates.belongsTo(db.workspaces, {
as: 'workspace',
foreignKey: {
name: 'workspaceId',
},
constraints: false,
});
db.estimates.belongsTo(db.customers, {
as: 'customer',
foreignKey: {
name: 'customerId',
},
constraints: false,
});
db.estimates.belongsTo(db.properties, {
as: 'property',
foreignKey: {
name: 'propertyId',
},
constraints: false,
});
db.estimates.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.estimates.belongsTo(db.users, {
as: 'createdBy',
});
db.estimates.belongsTo(db.users, {
as: 'updatedBy',
});
};
return estimates;
};

View File

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

View File

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

View File

@ -0,0 +1,144 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const invoice_line_items = sequelize.define(
'invoice_line_items',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
description: {
type: DataTypes.TEXT,
},
quantity: {
type: DataTypes.INTEGER,
},
unit_price: {
type: DataTypes.DECIMAL,
},
line_total: {
type: DataTypes.DECIMAL,
},
sort_order: {
type: DataTypes.INTEGER,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
invoice_line_items.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.invoice_line_items.belongsTo(db.workspaces, {
as: 'workspace',
foreignKey: {
name: 'workspaceId',
},
constraints: false,
});
db.invoice_line_items.belongsTo(db.invoices, {
as: 'invoice',
foreignKey: {
name: 'invoiceId',
},
constraints: false,
});
db.invoice_line_items.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.invoice_line_items.belongsTo(db.users, {
as: 'createdBy',
});
db.invoice_line_items.belongsTo(db.users, {
as: 'updatedBy',
});
};
return invoice_line_items;
};

View File

@ -0,0 +1,217 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const invoices = sequelize.define(
'invoices',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
invoice_number: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"draft",
"sent",
"paid",
"partially_paid",
"void",
"overdue"
],
},
issue_date: {
type: DataTypes.DATE,
},
due_date: {
type: DataTypes.DATE,
},
subtotal: {
type: DataTypes.DECIMAL,
},
tax_amount: {
type: DataTypes.DECIMAL,
},
discount_amount: {
type: DataTypes.DECIMAL,
},
total: {
type: DataTypes.DECIMAL,
},
notes: {
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
db.invoices.hasMany(db.invoice_line_items, {
as: 'invoice_line_items_invoice',
foreignKey: {
name: 'invoiceId',
},
constraints: false,
});
db.invoices.hasMany(db.payments, {
as: 'payments_invoice',
foreignKey: {
name: 'invoiceId',
},
constraints: false,
});
//end loop
db.invoices.belongsTo(db.workspaces, {
as: 'workspace',
foreignKey: {
name: 'workspaceId',
},
constraints: false,
});
db.invoices.belongsTo(db.customers, {
as: 'customer',
foreignKey: {
name: 'customerId',
},
constraints: false,
});
db.invoices.belongsTo(db.jobs, {
as: 'job',
foreignKey: {
name: 'jobId',
},
constraints: false,
});
db.invoices.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.invoices.belongsTo(db.users, {
as: 'createdBy',
});
db.invoices.belongsTo(db.users, {
as: 'updatedBy',
});
};
return invoices;
};

View File

@ -0,0 +1,153 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const job_assignments = sequelize.define(
'job_assignments',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
assignment_role: {
type: DataTypes.ENUM,
values: [
"lead",
"cleaner",
"helper"
],
},
assigned_at: {
type: DataTypes.DATE,
},
is_confirmed: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
job_assignments.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.job_assignments.belongsTo(db.workspaces, {
as: 'workspace',
foreignKey: {
name: 'workspaceId',
},
constraints: false,
});
db.job_assignments.belongsTo(db.jobs, {
as: 'job',
foreignKey: {
name: 'jobId',
},
constraints: false,
});
db.job_assignments.belongsTo(db.users, {
as: 'assignee',
foreignKey: {
name: 'assigneeId',
},
constraints: false,
});
db.job_assignments.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.job_assignments.belongsTo(db.users, {
as: 'createdBy',
});
db.job_assignments.belongsTo(db.users, {
as: 'updatedBy',
});
};
return job_assignments;
};

View File

@ -0,0 +1,161 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const job_checklist_run_items = sequelize.define(
'job_checklist_run_items',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
state: {
type: DataTypes.ENUM,
values: [
"pending",
"done",
"skipped",
"failed"
],
},
notes: {
type: DataTypes.TEXT,
},
completed_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
job_checklist_run_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.job_checklist_run_items.belongsTo(db.workspaces, {
as: 'workspace',
foreignKey: {
name: 'workspaceId',
},
constraints: false,
});
db.job_checklist_run_items.belongsTo(db.job_checklist_runs, {
as: 'job_checklist_run',
foreignKey: {
name: 'job_checklist_runId',
},
constraints: false,
});
db.job_checklist_run_items.belongsTo(db.checklist_items, {
as: 'checklist_item',
foreignKey: {
name: 'checklist_itemId',
},
constraints: false,
});
db.job_checklist_run_items.belongsTo(db.users, {
as: 'completed_by',
foreignKey: {
name: 'completed_byId',
},
constraints: false,
});
db.job_checklist_run_items.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.job_checklist_run_items.belongsTo(db.users, {
as: 'createdBy',
});
db.job_checklist_run_items.belongsTo(db.users, {
as: 'updatedBy',
});
};
return job_checklist_run_items;
};

View File

@ -0,0 +1,158 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const job_checklist_runs = sequelize.define(
'job_checklist_runs',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
status: {
type: DataTypes.ENUM,
values: [
"not_started",
"in_progress",
"completed"
],
},
started_at: {
type: DataTypes.DATE,
},
completed_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
job_checklist_runs.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.job_checklist_runs.hasMany(db.job_checklist_run_items, {
as: 'job_checklist_run_items_job_checklist_run',
foreignKey: {
name: 'job_checklist_runId',
},
constraints: false,
});
//end loop
db.job_checklist_runs.belongsTo(db.workspaces, {
as: 'workspace',
foreignKey: {
name: 'workspaceId',
},
constraints: false,
});
db.job_checklist_runs.belongsTo(db.jobs, {
as: 'job',
foreignKey: {
name: 'jobId',
},
constraints: false,
});
db.job_checklist_runs.belongsTo(db.checklists, {
as: 'checklist',
foreignKey: {
name: 'checklistId',
},
constraints: false,
});
db.job_checklist_runs.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.job_checklist_runs.belongsTo(db.users, {
as: 'createdBy',
});
db.job_checklist_runs.belongsTo(db.users, {
as: 'updatedBy',
});
};
return job_checklist_runs;
};

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 job_media = sequelize.define(
'job_media',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
media_type: {
type: DataTypes.ENUM,
values: [
"before",
"after",
"issue",
"other"
],
},
caption: {
type: DataTypes.TEXT,
},
uploaded_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
job_media.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.job_media.belongsTo(db.workspaces, {
as: 'workspace',
foreignKey: {
name: 'workspaceId',
},
constraints: false,
});
db.job_media.belongsTo(db.jobs, {
as: 'job',
foreignKey: {
name: 'jobId',
},
constraints: false,
});
db.job_media.belongsTo(db.users, {
as: 'uploaded_by',
foreignKey: {
name: 'uploaded_byId',
},
constraints: false,
});
db.job_media.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.job_media.hasMany(db.file, {
as: 'photos',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.job_media.getTableName(),
belongsToColumn: 'photos',
},
});
db.job_media.hasMany(db.file, {
as: 'attachments',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.job_media.getTableName(),
belongsToColumn: 'attachments',
},
});
db.job_media.belongsTo(db.users, {
as: 'createdBy',
});
db.job_media.belongsTo(db.users, {
as: 'updatedBy',
});
};
return job_media;
};

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 job_templates = sequelize.define(
'job_templates',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
default_price: {
type: DataTypes.DECIMAL,
},
default_duration_minutes: {
type: DataTypes.INTEGER,
},
default_instructions: {
type: DataTypes.TEXT,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
job_templates.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.job_templates.belongsTo(db.workspaces, {
as: 'workspace',
foreignKey: {
name: 'workspaceId',
},
constraints: false,
});
db.job_templates.belongsTo(db.service_catalog_items, {
as: 'service_catalog_item',
foreignKey: {
name: 'service_catalog_itemId',
},
constraints: false,
});
db.job_templates.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.job_templates.belongsTo(db.users, {
as: 'createdBy',
});
db.job_templates.belongsTo(db.users, {
as: 'updatedBy',
});
};
return job_templates;
};

View File

@ -0,0 +1,244 @@
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 jobs = sequelize.define(
'jobs',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
title: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"draft",
"scheduled",
"in_progress",
"completed",
"canceled",
"no_show"
],
},
start_at: {
type: DataTypes.DATE,
},
end_at: {
type: DataTypes.DATE,
},
estimated_duration_minutes: {
type: DataTypes.INTEGER,
},
price: {
type: DataTypes.DECIMAL,
},
instructions: {
type: DataTypes.TEXT,
},
internal_notes: {
type: DataTypes.TEXT,
},
requires_invoice: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
jobs.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.jobs.hasMany(db.job_assignments, {
as: 'job_assignments_job',
foreignKey: {
name: 'jobId',
},
constraints: false,
});
db.jobs.hasMany(db.job_checklist_runs, {
as: 'job_checklist_runs_job',
foreignKey: {
name: 'jobId',
},
constraints: false,
});
db.jobs.hasMany(db.job_media, {
as: 'job_media_job',
foreignKey: {
name: 'jobId',
},
constraints: false,
});
db.jobs.hasMany(db.invoices, {
as: 'invoices_job',
foreignKey: {
name: 'jobId',
},
constraints: false,
});
//end loop
db.jobs.belongsTo(db.workspaces, {
as: 'workspace',
foreignKey: {
name: 'workspaceId',
},
constraints: false,
});
db.jobs.belongsTo(db.customers, {
as: 'customer',
foreignKey: {
name: 'customerId',
},
constraints: false,
});
db.jobs.belongsTo(db.properties, {
as: 'property',
foreignKey: {
name: 'propertyId',
},
constraints: false,
});
db.jobs.belongsTo(db.service_catalog_items, {
as: 'service_catalog_item',
foreignKey: {
name: 'service_catalog_itemId',
},
constraints: false,
});
db.jobs.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.jobs.belongsTo(db.users, {
as: 'createdBy',
});
db.jobs.belongsTo(db.users, {
as: 'updatedBy',
});
};
return jobs;
};

View File

@ -0,0 +1,206 @@
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",
"in_app"
],
},
event_type: {
type: DataTypes.ENUM,
values: [
"job_assigned",
"job_reminder",
"job_completed",
"invoice_sent",
"invoice_overdue",
"payment_received",
"membership_invited"
],
},
subject: {
type: DataTypes.TEXT,
},
message: {
type: DataTypes.TEXT,
},
scheduled_at: {
type: DataTypes.DATE,
},
sent_at: {
type: DataTypes.DATE,
},
status: {
type: DataTypes.ENUM,
values: [
"queued",
"sent",
"failed"
],
},
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.workspaces, {
as: 'workspace',
foreignKey: {
name: 'workspaceId',
},
constraints: false,
});
db.notifications.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.notifications.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.notifications.belongsTo(db.users, {
as: 'createdBy',
});
db.notifications.belongsTo(db.users, {
as: 'updatedBy',
});
};
return notifications;
};

View File

@ -0,0 +1,284 @@
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.workspaces, {
as: 'workspaces_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.workspace_memberships, {
as: 'workspace_memberships_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.service_catalog_items, {
as: 'service_catalog_items_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.customers, {
as: 'customers_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.properties, {
as: 'properties_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.job_templates, {
as: 'job_templates_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.jobs, {
as: 'jobs_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.job_assignments, {
as: 'job_assignments_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.checklists, {
as: 'checklists_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.checklist_items, {
as: 'checklist_items_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.job_checklist_runs, {
as: 'job_checklist_runs_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.job_checklist_run_items, {
as: 'job_checklist_run_items_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.job_media, {
as: 'job_media_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.invoices, {
as: 'invoices_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.invoice_line_items, {
as: 'invoice_line_items_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.payments, {
as: 'payments_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.estimates, {
as: 'estimates_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.estimate_line_items, {
as: 'estimate_line_items_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.recurring_schedules, {
as: 'recurring_schedules_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.notifications, {
as: 'notifications_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.support_tickets, {
as: 'support_tickets_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.plans, {
as: 'plans_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.subscriptions, {
as: 'subscriptions_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,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 payments = sequelize.define(
'payments',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
amount: {
type: DataTypes.DECIMAL,
},
method: {
type: DataTypes.ENUM,
values: [
"cash",
"card",
"bank_transfer",
"check",
"other"
],
},
status: {
type: DataTypes.ENUM,
values: [
"pending",
"succeeded",
"failed",
"refunded"
],
},
paid_at: {
type: DataTypes.DATE,
},
reference: {
type: DataTypes.TEXT,
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
payments.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.payments.belongsTo(db.workspaces, {
as: 'workspace',
foreignKey: {
name: 'workspaceId',
},
constraints: false,
});
db.payments.belongsTo(db.invoices, {
as: 'invoice',
foreignKey: {
name: 'invoiceId',
},
constraints: false,
});
db.payments.belongsTo(db.customers, {
as: 'customer',
foreignKey: {
name: 'customerId',
},
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,92 @@
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,169 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const plans = sequelize.define(
'plans',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
code: {
type: DataTypes.TEXT,
},
billing_interval: {
type: DataTypes.ENUM,
values: [
"monthly",
"yearly"
],
},
price: {
type: DataTypes.DECIMAL,
},
max_users: {
type: DataTypes.INTEGER,
},
max_jobs_per_month: {
type: DataTypes.INTEGER,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
description: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
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.plans.hasMany(db.subscriptions, {
as: 'subscriptions_plan',
foreignKey: {
name: 'planId',
},
constraints: false,
});
//end loop
db.plans.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.plans.belongsTo(db.users, {
as: 'createdBy',
});
db.plans.belongsTo(db.users, {
as: 'updatedBy',
});
};
return plans;
};

View File

@ -0,0 +1,213 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const properties = sequelize.define(
'properties',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
address_line1: {
type: DataTypes.TEXT,
},
address_line2: {
type: DataTypes.TEXT,
},
city: {
type: DataTypes.TEXT,
},
state_region: {
type: DataTypes.TEXT,
},
postal_code: {
type: DataTypes.TEXT,
},
access_instructions: {
type: DataTypes.TEXT,
},
bedrooms: {
type: DataTypes.INTEGER,
},
bathrooms: {
type: DataTypes.INTEGER,
},
square_feet: {
type: DataTypes.INTEGER,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
properties.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.properties.hasMany(db.jobs, {
as: 'jobs_property',
foreignKey: {
name: 'propertyId',
},
constraints: false,
});
db.properties.hasMany(db.estimates, {
as: 'estimates_property',
foreignKey: {
name: 'propertyId',
},
constraints: false,
});
db.properties.hasMany(db.recurring_schedules, {
as: 'recurring_schedules_property',
foreignKey: {
name: 'propertyId',
},
constraints: false,
});
//end loop
db.properties.belongsTo(db.workspaces, {
as: 'workspace',
foreignKey: {
name: 'workspaceId',
},
constraints: false,
});
db.properties.belongsTo(db.customers, {
as: 'customer',
foreignKey: {
name: 'customerId',
},
constraints: false,
});
db.properties.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.properties.belongsTo(db.users, {
as: 'createdBy',
});
db.properties.belongsTo(db.users, {
as: 'updatedBy',
});
};
return properties;
};

View File

@ -0,0 +1,227 @@
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 recurring_schedules = sequelize.define(
'recurring_schedules',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
frequency: {
type: DataTypes.ENUM,
values: [
"weekly",
"biweekly",
"monthly"
],
},
interval_count: {
type: DataTypes.INTEGER,
},
day_of_week: {
type: DataTypes.ENUM,
values: [
"mon",
"tue",
"wed",
"thu",
"fri",
"sat",
"sun"
],
},
day_of_month: {
type: DataTypes.INTEGER,
},
start_at: {
type: DataTypes.DATE,
},
end_at: {
type: DataTypes.DATE,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
recurring_schedules.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.recurring_schedules.belongsTo(db.workspaces, {
as: 'workspace',
foreignKey: {
name: 'workspaceId',
},
constraints: false,
});
db.recurring_schedules.belongsTo(db.customers, {
as: 'customer',
foreignKey: {
name: 'customerId',
},
constraints: false,
});
db.recurring_schedules.belongsTo(db.properties, {
as: 'property',
foreignKey: {
name: 'propertyId',
},
constraints: false,
});
db.recurring_schedules.belongsTo(db.service_catalog_items, {
as: 'service_catalog_item',
foreignKey: {
name: 'service_catalog_itemId',
},
constraints: false,
});
db.recurring_schedules.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.recurring_schedules.belongsTo(db.users, {
as: 'createdBy',
});
db.recurring_schedules.belongsTo(db.users, {
as: 'updatedBy',
});
};
return recurring_schedules;
};

View File

@ -0,0 +1,135 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const 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,185 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const service_catalog_items = sequelize.define(
'service_catalog_items',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
description: {
type: DataTypes.TEXT,
},
pricing_model: {
type: DataTypes.ENUM,
values: [
"flat",
"hourly",
"per_room",
"per_sqft"
],
},
base_price: {
type: DataTypes.DECIMAL,
},
hourly_rate: {
type: DataTypes.DECIMAL,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
service_catalog_items.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.service_catalog_items.hasMany(db.job_templates, {
as: 'job_templates_service_catalog_item',
foreignKey: {
name: 'service_catalog_itemId',
},
constraints: false,
});
db.service_catalog_items.hasMany(db.jobs, {
as: 'jobs_service_catalog_item',
foreignKey: {
name: 'service_catalog_itemId',
},
constraints: false,
});
db.service_catalog_items.hasMany(db.recurring_schedules, {
as: 'recurring_schedules_service_catalog_item',
foreignKey: {
name: 'service_catalog_itemId',
},
constraints: false,
});
//end loop
db.service_catalog_items.belongsTo(db.workspaces, {
as: 'workspace',
foreignKey: {
name: 'workspaceId',
},
constraints: false,
});
db.service_catalog_items.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.service_catalog_items.belongsTo(db.users, {
as: 'createdBy',
});
db.service_catalog_items.belongsTo(db.users, {
as: 'updatedBy',
});
};
return service_catalog_items;
};

View File

@ -0,0 +1,166 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const subscriptions = sequelize.define(
'subscriptions',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
status: {
type: DataTypes.ENUM,
values: [
"trialing",
"active",
"past_due",
"canceled"
],
},
current_period_start: {
type: DataTypes.DATE,
},
current_period_end: {
type: DataTypes.DATE,
},
canceled_at: {
type: DataTypes.DATE,
},
provider: {
type: DataTypes.TEXT,
},
provider_subscription_ref: {
type: DataTypes.TEXT,
},
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.workspaces, {
as: 'workspace',
foreignKey: {
name: 'workspaceId',
},
constraints: false,
});
db.subscriptions.belongsTo(db.plans, {
as: 'plan',
foreignKey: {
name: 'planId',
},
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,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 support_tickets = sequelize.define(
'support_tickets',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
status: {
type: DataTypes.ENUM,
values: [
"open",
"pending",
"resolved",
"closed"
],
},
priority: {
type: DataTypes.ENUM,
values: [
"low",
"normal",
"high",
"urgent"
],
},
subject: {
type: DataTypes.TEXT,
},
description: {
type: DataTypes.TEXT,
},
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,
},
);
support_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.support_tickets.belongsTo(db.workspaces, {
as: 'workspace',
foreignKey: {
name: 'workspaceId',
},
constraints: false,
});
db.support_tickets.belongsTo(db.users, {
as: 'requester',
foreignKey: {
name: 'requesterId',
},
constraints: false,
});
db.support_tickets.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.support_tickets.hasMany(db.file, {
as: 'attachments',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.support_tickets.getTableName(),
belongsToColumn: 'attachments',
},
});
db.support_tickets.belongsTo(db.users, {
as: 'createdBy',
});
db.support_tickets.belongsTo(db.users, {
as: 'updatedBy',
});
};
return support_tickets;
};

View File

@ -0,0 +1,314 @@
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.workspaces, {
as: 'workspaces_owner',
foreignKey: {
name: 'ownerId',
},
constraints: false,
});
db.users.hasMany(db.workspace_memberships, {
as: 'workspace_memberships_user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.users.hasMany(db.job_assignments, {
as: 'job_assignments_assignee',
foreignKey: {
name: 'assigneeId',
},
constraints: false,
});
db.users.hasMany(db.job_checklist_run_items, {
as: 'job_checklist_run_items_completed_by',
foreignKey: {
name: 'completed_byId',
},
constraints: false,
});
db.users.hasMany(db.job_media, {
as: 'job_media_uploaded_by',
foreignKey: {
name: 'uploaded_byId',
},
constraints: false,
});
db.users.hasMany(db.notifications, {
as: 'notifications_user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.users.hasMany(db.support_tickets, {
as: 'support_tickets_requester',
foreignKey: {
name: 'requesterId',
},
constraints: false,
});
//end loop
db.users.belongsTo(db.roles, {
as: 'app_role',
foreignKey: {
name: 'app_roleId',
},
constraints: false,
});
db.users.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.users.hasMany(db.file, {
as: 'avatar',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.users.getTableName(),
belongsToColumn: 'avatar',
},
});
db.users.belongsTo(db.users, {
as: 'createdBy',
});
db.users.belongsTo(db.users, {
as: 'updatedBy',
});
};
users.beforeCreate((users, options) => {
users = trimStringFields(users);
if (users.provider !== providers.LOCAL && Object.values(providers).indexOf(users.provider) > -1) {
users.emailVerified = true;
if (!users.password) {
const password = crypto
.randomBytes(20)
.toString('hex');
const hashedPassword = bcrypt.hashSync(
password,
config.bcrypt.saltRounds,
);
users.password = hashedPassword
}
}
});
users.beforeUpdate((users, options) => {
users = trimStringFields(users);
});
return users;
};
function trimStringFields(users) {
users.email = users.email.trim();
users.firstName = users.firstName
? users.firstName.trim()
: null;
users.lastName = users.lastName
? users.lastName.trim()
: null;
return users;
}

View File

@ -0,0 +1,152 @@
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 workspace_memberships = sequelize.define(
'workspace_memberships',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
role: {
type: DataTypes.ENUM,
values: [
"owner",
"admin",
"staff"
],
},
is_invited: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
invited_at: {
type: DataTypes.DATE,
},
joined_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
workspace_memberships.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.workspace_memberships.belongsTo(db.workspaces, {
as: 'workspace',
foreignKey: {
name: 'workspaceId',
},
constraints: false,
});
db.workspace_memberships.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.workspace_memberships.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.workspace_memberships.belongsTo(db.users, {
as: 'createdBy',
});
db.workspace_memberships.belongsTo(db.users, {
as: 'updatedBy',
});
};
return workspace_memberships;
};

View File

@ -0,0 +1,326 @@
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 workspaces = sequelize.define(
'workspaces',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
slug: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"trial",
"active",
"past_due",
"canceled"
],
},
trial_ends_at: {
type: DataTypes.DATE,
},
timezone: {
type: DataTypes.TEXT,
},
currency: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
workspaces.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.workspaces.hasMany(db.workspace_memberships, {
as: 'workspace_memberships_workspace',
foreignKey: {
name: 'workspaceId',
},
constraints: false,
});
db.workspaces.hasMany(db.service_catalog_items, {
as: 'service_catalog_items_workspace',
foreignKey: {
name: 'workspaceId',
},
constraints: false,
});
db.workspaces.hasMany(db.customers, {
as: 'customers_workspace',
foreignKey: {
name: 'workspaceId',
},
constraints: false,
});
db.workspaces.hasMany(db.properties, {
as: 'properties_workspace',
foreignKey: {
name: 'workspaceId',
},
constraints: false,
});
db.workspaces.hasMany(db.job_templates, {
as: 'job_templates_workspace',
foreignKey: {
name: 'workspaceId',
},
constraints: false,
});
db.workspaces.hasMany(db.jobs, {
as: 'jobs_workspace',
foreignKey: {
name: 'workspaceId',
},
constraints: false,
});
db.workspaces.hasMany(db.job_assignments, {
as: 'job_assignments_workspace',
foreignKey: {
name: 'workspaceId',
},
constraints: false,
});
db.workspaces.hasMany(db.checklists, {
as: 'checklists_workspace',
foreignKey: {
name: 'workspaceId',
},
constraints: false,
});
db.workspaces.hasMany(db.checklist_items, {
as: 'checklist_items_workspace',
foreignKey: {
name: 'workspaceId',
},
constraints: false,
});
db.workspaces.hasMany(db.job_checklist_runs, {
as: 'job_checklist_runs_workspace',
foreignKey: {
name: 'workspaceId',
},
constraints: false,
});
db.workspaces.hasMany(db.job_checklist_run_items, {
as: 'job_checklist_run_items_workspace',
foreignKey: {
name: 'workspaceId',
},
constraints: false,
});
db.workspaces.hasMany(db.job_media, {
as: 'job_media_workspace',
foreignKey: {
name: 'workspaceId',
},
constraints: false,
});
db.workspaces.hasMany(db.invoices, {
as: 'invoices_workspace',
foreignKey: {
name: 'workspaceId',
},
constraints: false,
});
db.workspaces.hasMany(db.invoice_line_items, {
as: 'invoice_line_items_workspace',
foreignKey: {
name: 'workspaceId',
},
constraints: false,
});
db.workspaces.hasMany(db.payments, {
as: 'payments_workspace',
foreignKey: {
name: 'workspaceId',
},
constraints: false,
});
db.workspaces.hasMany(db.estimates, {
as: 'estimates_workspace',
foreignKey: {
name: 'workspaceId',
},
constraints: false,
});
db.workspaces.hasMany(db.estimate_line_items, {
as: 'estimate_line_items_workspace',
foreignKey: {
name: 'workspaceId',
},
constraints: false,
});
db.workspaces.hasMany(db.recurring_schedules, {
as: 'recurring_schedules_workspace',
foreignKey: {
name: 'workspaceId',
},
constraints: false,
});
db.workspaces.hasMany(db.notifications, {
as: 'notifications_workspace',
foreignKey: {
name: 'workspaceId',
},
constraints: false,
});
db.workspaces.hasMany(db.support_tickets, {
as: 'support_tickets_workspace',
foreignKey: {
name: 'workspaceId',
},
constraints: false,
});
db.workspaces.hasMany(db.subscriptions, {
as: 'subscriptions_workspace',
foreignKey: {
name: 'workspaceId',
},
constraints: false,
});
//end loop
db.workspaces.belongsTo(db.users, {
as: 'owner',
foreignKey: {
name: 'ownerId',
},
constraints: false,
});
db.workspaces.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.workspaces.belongsTo(db.users, {
as: 'createdBy',
});
db.workspaces.belongsTo(db.users, {
as: 'updatedBy',
});
};
return workspaces;
};

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

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

@ -0,0 +1,241 @@
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 workspacesRoutes = require('./routes/workspaces');
const workspace_membershipsRoutes = require('./routes/workspace_memberships');
const service_catalog_itemsRoutes = require('./routes/service_catalog_items');
const customersRoutes = require('./routes/customers');
const propertiesRoutes = require('./routes/properties');
const job_templatesRoutes = require('./routes/job_templates');
const jobsRoutes = require('./routes/jobs');
const job_assignmentsRoutes = require('./routes/job_assignments');
const checklistsRoutes = require('./routes/checklists');
const checklist_itemsRoutes = require('./routes/checklist_items');
const job_checklist_runsRoutes = require('./routes/job_checklist_runs');
const job_checklist_run_itemsRoutes = require('./routes/job_checklist_run_items');
const job_mediaRoutes = require('./routes/job_media');
const invoicesRoutes = require('./routes/invoices');
const invoice_line_itemsRoutes = require('./routes/invoice_line_items');
const paymentsRoutes = require('./routes/payments');
const estimatesRoutes = require('./routes/estimates');
const estimate_line_itemsRoutes = require('./routes/estimate_line_items');
const recurring_schedulesRoutes = require('./routes/recurring_schedules');
const notificationsRoutes = require('./routes/notifications');
const support_ticketsRoutes = require('./routes/support_tickets');
const plansRoutes = require('./routes/plans');
const subscriptionsRoutes = require('./routes/subscriptions');
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: "CleanerOps SaaS",
description: "CleanerOps SaaS 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/workspaces', passport.authenticate('jwt', {session: false}), workspacesRoutes);
app.use('/api/workspace_memberships', passport.authenticate('jwt', {session: false}), workspace_membershipsRoutes);
app.use('/api/service_catalog_items', passport.authenticate('jwt', {session: false}), service_catalog_itemsRoutes);
app.use('/api/customers', passport.authenticate('jwt', {session: false}), customersRoutes);
app.use('/api/properties', passport.authenticate('jwt', {session: false}), propertiesRoutes);
app.use('/api/job_templates', passport.authenticate('jwt', {session: false}), job_templatesRoutes);
app.use('/api/jobs', passport.authenticate('jwt', {session: false}), jobsRoutes);
app.use('/api/job_assignments', passport.authenticate('jwt', {session: false}), job_assignmentsRoutes);
app.use('/api/checklists', passport.authenticate('jwt', {session: false}), checklistsRoutes);
app.use('/api/checklist_items', passport.authenticate('jwt', {session: false}), checklist_itemsRoutes);
app.use('/api/job_checklist_runs', passport.authenticate('jwt', {session: false}), job_checklist_runsRoutes);
app.use('/api/job_checklist_run_items', passport.authenticate('jwt', {session: false}), job_checklist_run_itemsRoutes);
app.use('/api/job_media', passport.authenticate('jwt', {session: false}), job_mediaRoutes);
app.use('/api/invoices', passport.authenticate('jwt', {session: false}), invoicesRoutes);
app.use('/api/invoice_line_items', passport.authenticate('jwt', {session: false}), invoice_line_itemsRoutes);
app.use('/api/payments', passport.authenticate('jwt', {session: false}), paymentsRoutes);
app.use('/api/estimates', passport.authenticate('jwt', {session: false}), estimatesRoutes);
app.use('/api/estimate_line_items', passport.authenticate('jwt', {session: false}), estimate_line_itemsRoutes);
app.use('/api/recurring_schedules', passport.authenticate('jwt', {session: false}), recurring_schedulesRoutes);
app.use('/api/notifications', passport.authenticate('jwt', {session: false}), notificationsRoutes);
app.use('/api/support_tickets', passport.authenticate('jwt', {session: false}), support_ticketsRoutes);
app.use('/api/plans', passport.authenticate('jwt', {session: false}), plansRoutes);
app.use('/api/subscriptions', passport.authenticate('jwt', {session: false}), subscriptionsRoutes);
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;
db.sequelize.sync().then(function () {
app.listen(PORT, () => {
console.log(`Listening on port ${PORT}`);
});
});
module.exports = app;

View File

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

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;

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

View File

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

View File

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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