Initial version

This commit is contained in:
Flatlogic Bot 2026-02-16 10:17:11 +00:00
commit 8748428f58
524 changed files with 195108 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>Multi-tenant Billing Ops SaaS</h2>
<p>Multi-tenant SaaS to manage clients, projects, estimates, invoices, and payables to vendors and freelancers.</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 @@
# Multi-tenant Billing Ops 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_38473
DB_USER=app_38473
DB_PASS=98805a63-eae2-4c42-9f22-1487610ae0a7
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 @@
#Multi-tenant Billing Ops 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_multi_tenant_billing_ops_saas;`
- Then give that new user privileges to the new database then quit the `psql`.
- `postgres=> GRANT ALL PRIVILEGES ON DATABASE db_multi_tenant_billing_ops_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": "multitenantbillingopssaas",
"description": "Multi-tenant Billing Ops 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: "98805a63",
user_pass: "1487610ae0a7",
admin_email: "admin@flatlogic.com",
providers: {
LOCAL: 'local',
GOOGLE: 'google',
MICROSOFT: 'microsoft'
},
secret_key: process.env.SECRET_KEY || '98805a63-eae2-4c42-9f22-1487610ae0a7',
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: 'Multi-tenant Billing Ops 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: 'Project Contributor',
},
project_uuid: '98805a63-eae2-4c42-9f22-1487610ae0a7',
flHost: process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'dev_stage' ? 'https://flatlogic.com/projects' : 'http://localhost:3000/projects',
gpt_key: process.env.GPT_KEY || '',
};
config.pexelsKey = process.env.PEXELS_KEY || '';
config.pexelsQuery = 'lighthouse guiding ships at dusk';
config.host = process.env.NODE_ENV === "production" ? config.remote : "http://localhost";
config.apiUrl = `${config.host}${config.port ? `:${config.port}` : ``}/api`;
config.swaggerUrl = `${config.swaggerUI}${config.swaggerPort}`;
config.uiUrl = `${config.hostUI}${config.portUI ? `:${config.portUI}` : ``}/#`;
config.backUrl = `${config.hostUI}${config.portUI ? `:${config.portUI}` : ``}`;
module.exports = config;

View File

@ -0,0 +1,929 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class ClientsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const clients = await db.clients.create(
{
id: data.id || undefined,
name: data.name
||
null
,
type: data.type
||
null
,
primary_contact_name: data.primary_contact_name
||
null
,
primary_email: data.primary_email
||
null
,
primary_phone: data.primary_phone
||
null
,
website: data.website
||
null
,
billing_address_line1: data.billing_address_line1
||
null
,
billing_address_line2: data.billing_address_line2
||
null
,
billing_city: data.billing_city
||
null
,
billing_region: data.billing_region
||
null
,
billing_postal_code: data.billing_postal_code
||
null
,
billing_country: data.billing_country
||
null
,
shipping_address_line1: data.shipping_address_line1
||
null
,
shipping_address_line2: data.shipping_address_line2
||
null
,
shipping_city: data.shipping_city
||
null
,
shipping_region: data.shipping_region
||
null
,
shipping_postal_code: data.shipping_postal_code
||
null
,
shipping_country: data.shipping_country
||
null
,
tax_number: data.tax_number
||
null
,
status: data.status
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await clients.setTenant( data.tenant || null, {
transaction,
});
await clients.setOrganizations( data.organizations || null, {
transaction,
});
return clients;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const clientsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
type: item.type
||
null
,
primary_contact_name: item.primary_contact_name
||
null
,
primary_email: item.primary_email
||
null
,
primary_phone: item.primary_phone
||
null
,
website: item.website
||
null
,
billing_address_line1: item.billing_address_line1
||
null
,
billing_address_line2: item.billing_address_line2
||
null
,
billing_city: item.billing_city
||
null
,
billing_region: item.billing_region
||
null
,
billing_postal_code: item.billing_postal_code
||
null
,
billing_country: item.billing_country
||
null
,
shipping_address_line1: item.shipping_address_line1
||
null
,
shipping_address_line2: item.shipping_address_line2
||
null
,
shipping_city: item.shipping_city
||
null
,
shipping_region: item.shipping_region
||
null
,
shipping_postal_code: item.shipping_postal_code
||
null
,
shipping_country: item.shipping_country
||
null
,
tax_number: item.tax_number
||
null
,
status: item.status
||
null
,
notes: item.notes
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const clients = await db.clients.bulkCreate(clientsData, { transaction });
// For each item created, replace relation files
return clients;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const clients = await db.clients.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.type !== undefined) updatePayload.type = data.type;
if (data.primary_contact_name !== undefined) updatePayload.primary_contact_name = data.primary_contact_name;
if (data.primary_email !== undefined) updatePayload.primary_email = data.primary_email;
if (data.primary_phone !== undefined) updatePayload.primary_phone = data.primary_phone;
if (data.website !== undefined) updatePayload.website = data.website;
if (data.billing_address_line1 !== undefined) updatePayload.billing_address_line1 = data.billing_address_line1;
if (data.billing_address_line2 !== undefined) updatePayload.billing_address_line2 = data.billing_address_line2;
if (data.billing_city !== undefined) updatePayload.billing_city = data.billing_city;
if (data.billing_region !== undefined) updatePayload.billing_region = data.billing_region;
if (data.billing_postal_code !== undefined) updatePayload.billing_postal_code = data.billing_postal_code;
if (data.billing_country !== undefined) updatePayload.billing_country = data.billing_country;
if (data.shipping_address_line1 !== undefined) updatePayload.shipping_address_line1 = data.shipping_address_line1;
if (data.shipping_address_line2 !== undefined) updatePayload.shipping_address_line2 = data.shipping_address_line2;
if (data.shipping_city !== undefined) updatePayload.shipping_city = data.shipping_city;
if (data.shipping_region !== undefined) updatePayload.shipping_region = data.shipping_region;
if (data.shipping_postal_code !== undefined) updatePayload.shipping_postal_code = data.shipping_postal_code;
if (data.shipping_country !== undefined) updatePayload.shipping_country = data.shipping_country;
if (data.tax_number !== undefined) updatePayload.tax_number = data.tax_number;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await clients.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await clients.setTenant(
data.tenant,
{ transaction }
);
}
if (data.organizations !== undefined) {
await clients.setOrganizations(
data.organizations,
{ transaction }
);
}
return clients;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const clients = await db.clients.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of clients) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of clients) {
await record.destroy({transaction});
}
});
return clients;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const clients = await db.clients.findByPk(id, options);
await clients.update({
deletedBy: currentUser.id
}, {
transaction,
});
await clients.destroy({
transaction
});
return clients;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const clients = await db.clients.findOne(
{ where },
{ transaction },
);
if (!clients) {
return clients;
}
const output = clients.get({plain: true});
output.projects_client = await clients.getProjects_client({
transaction
});
output.estimates_client = await clients.getEstimates_client({
transaction
});
output.invoices_client = await clients.getInvoices_client({
transaction
});
output.payments_client = await clients.getPayments_client({
transaction
});
output.time_entries_client = await clients.getTime_entries_client({
transaction
});
output.tenant = await clients.getTenant({
transaction
});
output.organizations = await clients.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.tenants,
as: 'tenant',
where: filter.tenant ? {
[Op.or]: [
{ id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'clients',
'name',
filter.name,
),
};
}
if (filter.primary_contact_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'clients',
'primary_contact_name',
filter.primary_contact_name,
),
};
}
if (filter.primary_email) {
where = {
...where,
[Op.and]: Utils.ilike(
'clients',
'primary_email',
filter.primary_email,
),
};
}
if (filter.primary_phone) {
where = {
...where,
[Op.and]: Utils.ilike(
'clients',
'primary_phone',
filter.primary_phone,
),
};
}
if (filter.website) {
where = {
...where,
[Op.and]: Utils.ilike(
'clients',
'website',
filter.website,
),
};
}
if (filter.billing_address_line1) {
where = {
...where,
[Op.and]: Utils.ilike(
'clients',
'billing_address_line1',
filter.billing_address_line1,
),
};
}
if (filter.billing_address_line2) {
where = {
...where,
[Op.and]: Utils.ilike(
'clients',
'billing_address_line2',
filter.billing_address_line2,
),
};
}
if (filter.billing_city) {
where = {
...where,
[Op.and]: Utils.ilike(
'clients',
'billing_city',
filter.billing_city,
),
};
}
if (filter.billing_region) {
where = {
...where,
[Op.and]: Utils.ilike(
'clients',
'billing_region',
filter.billing_region,
),
};
}
if (filter.billing_postal_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'clients',
'billing_postal_code',
filter.billing_postal_code,
),
};
}
if (filter.billing_country) {
where = {
...where,
[Op.and]: Utils.ilike(
'clients',
'billing_country',
filter.billing_country,
),
};
}
if (filter.shipping_address_line1) {
where = {
...where,
[Op.and]: Utils.ilike(
'clients',
'shipping_address_line1',
filter.shipping_address_line1,
),
};
}
if (filter.shipping_address_line2) {
where = {
...where,
[Op.and]: Utils.ilike(
'clients',
'shipping_address_line2',
filter.shipping_address_line2,
),
};
}
if (filter.shipping_city) {
where = {
...where,
[Op.and]: Utils.ilike(
'clients',
'shipping_city',
filter.shipping_city,
),
};
}
if (filter.shipping_region) {
where = {
...where,
[Op.and]: Utils.ilike(
'clients',
'shipping_region',
filter.shipping_region,
),
};
}
if (filter.shipping_postal_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'clients',
'shipping_postal_code',
filter.shipping_postal_code,
),
};
}
if (filter.shipping_country) {
where = {
...where,
[Op.and]: Utils.ilike(
'clients',
'shipping_country',
filter.shipping_country,
),
};
}
if (filter.tax_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'clients',
'tax_number',
filter.tax_number,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'clients',
'notes',
filter.notes,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.type) {
where = {
...where,
type: filter.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.clients.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'clients',
'name',
query,
),
],
};
}
const records = await db.clients.findAll({
attributes: [ 'id', 'name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.name,
}));
}
};

View File

@ -0,0 +1,703 @@
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,
name: data.name
||
null
,
description: data.description
||
null
,
quantity: data.quantity
||
null
,
unit_price: data.unit_price
||
null
,
unit_type: data.unit_type
||
null
,
tax_rate: data.tax_rate
||
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.setTenant( data.tenant || 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,
name: item.name
||
null
,
description: item.description
||
null
,
quantity: item.quantity
||
null
,
unit_price: item.unit_price
||
null
,
unit_type: item.unit_type
||
null
,
tax_rate: item.tax_rate
||
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.name !== undefined) updatePayload.name = data.name;
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.unit_type !== undefined) updatePayload.unit_type = data.unit_type;
if (data.tax_rate !== undefined) updatePayload.tax_rate = data.tax_rate;
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.tenant !== undefined) {
await estimate_line_items.setTenant(
data.tenant,
{ 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.tenant = await estimate_line_items.getTenant({
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.tenants,
as: 'tenant',
where: filter.tenant ? {
[Op.or]: [
{ id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.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.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'estimate_line_items',
'name',
filter.name,
),
};
}
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.tax_rateRange) {
const [start, end] = filter.tax_rateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
tax_rate: {
...where.tax_rate,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
tax_rate: {
...where.tax_rate,
[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.unit_type) {
where = {
...where,
unit_type: filter.unit_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.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',
'name',
query,
),
],
};
}
const records = await db.estimate_line_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,912 @@
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
,
valid_until: data.valid_until
||
null
,
currency_code: data.currency_code
||
null
,
subtotal_amount: data.subtotal_amount
||
null
,
discount_amount: data.discount_amount
||
null
,
tax_amount: data.tax_amount
||
null
,
total_amount: data.total_amount
||
null
,
notes: data.notes
||
null
,
terms: data.terms
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await estimates.setTenant( data.tenant || null, {
transaction,
});
await estimates.setClient( data.client || null, {
transaction,
});
await estimates.setProject( data.project || null, {
transaction,
});
await estimates.setIssued_by( data.issued_by || null, {
transaction,
});
await estimates.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.estimates.getTableName(),
belongsToColumn: 'attachments',
belongsToId: estimates.id,
},
data.attachments,
options,
);
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
,
valid_until: item.valid_until
||
null
,
currency_code: item.currency_code
||
null
,
subtotal_amount: item.subtotal_amount
||
null
,
discount_amount: item.discount_amount
||
null
,
tax_amount: item.tax_amount
||
null
,
total_amount: item.total_amount
||
null
,
notes: item.notes
||
null
,
terms: item.terms
||
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
for (let i = 0; i < estimates.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.estimates.getTableName(),
belongsToColumn: 'attachments',
belongsToId: estimates[i].id,
},
data[i].attachments,
options,
);
}
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.valid_until !== undefined) updatePayload.valid_until = data.valid_until;
if (data.currency_code !== undefined) updatePayload.currency_code = data.currency_code;
if (data.subtotal_amount !== undefined) updatePayload.subtotal_amount = data.subtotal_amount;
if (data.discount_amount !== undefined) updatePayload.discount_amount = data.discount_amount;
if (data.tax_amount !== undefined) updatePayload.tax_amount = data.tax_amount;
if (data.total_amount !== undefined) updatePayload.total_amount = data.total_amount;
if (data.notes !== undefined) updatePayload.notes = data.notes;
if (data.terms !== undefined) updatePayload.terms = data.terms;
updatePayload.updatedById = currentUser.id;
await estimates.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await estimates.setTenant(
data.tenant,
{ transaction }
);
}
if (data.client !== undefined) {
await estimates.setClient(
data.client,
{ transaction }
);
}
if (data.project !== undefined) {
await estimates.setProject(
data.project,
{ transaction }
);
}
if (data.issued_by !== undefined) {
await estimates.setIssued_by(
data.issued_by,
{ transaction }
);
}
if (data.organizations !== undefined) {
await estimates.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.estimates.getTableName(),
belongsToColumn: 'attachments',
belongsToId: estimates.id,
},
data.attachments,
options,
);
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.invoices_estimate = await estimates.getInvoices_estimate({
transaction
});
output.tenant = await estimates.getTenant({
transaction
});
output.client = await estimates.getClient({
transaction
});
output.project = await estimates.getProject({
transaction
});
output.attachments = await estimates.getAttachments({
transaction
});
output.issued_by = await estimates.getIssued_by({
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.tenants,
as: 'tenant',
where: filter.tenant ? {
[Op.or]: [
{ id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.clients,
as: 'client',
where: filter.client ? {
[Op.or]: [
{ id: { [Op.in]: filter.client.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.client.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.projects,
as: 'project',
where: filter.project ? {
[Op.or]: [
{ id: { [Op.in]: filter.project.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.project.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'issued_by',
where: filter.issued_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.issued_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.issued_by.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.estimate_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'estimates',
'estimate_number',
filter.estimate_number,
),
};
}
if (filter.currency_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'estimates',
'currency_code',
filter.currency_code,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'estimates',
'notes',
filter.notes,
),
};
}
if (filter.terms) {
where = {
...where,
[Op.and]: Utils.ilike(
'estimates',
'terms',
filter.terms,
),
};
}
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.valid_untilRange) {
const [start, end] = filter.valid_untilRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
valid_until: {
...where.valid_until,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
valid_until: {
...where.valid_until,
[Op.lte]: end,
},
};
}
}
if (filter.subtotal_amountRange) {
const [start, end] = filter.subtotal_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
subtotal_amount: {
...where.subtotal_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
subtotal_amount: {
...where.subtotal_amount,
[Op.lte]: end,
},
};
}
}
if (filter.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.tax_amountRange) {
const [start, end] = filter.tax_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
tax_amount: {
...where.tax_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
tax_amount: {
...where.tax_amount,
[Op.lte]: end,
},
};
}
}
if (filter.total_amountRange) {
const [start, end] = filter.total_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
total_amount: {
...where.total_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
total_amount: {
...where.total_amount,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.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,745 @@
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 Freelancer_assignmentsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const freelancer_assignments = await db.freelancer_assignments.create(
{
id: data.id || undefined,
role_on_project: data.role_on_project
||
null
,
rate_type: data.rate_type
||
null
,
rate: data.rate
||
null
,
start_at: data.start_at
||
null
,
end_at: data.end_at
||
null
,
status: data.status
||
null
,
estimated_hours: data.estimated_hours
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await freelancer_assignments.setTenant( data.tenant || null, {
transaction,
});
await freelancer_assignments.setFreelancer( data.freelancer || null, {
transaction,
});
await freelancer_assignments.setProject( data.project || null, {
transaction,
});
await freelancer_assignments.setOrganizations( data.organizations || null, {
transaction,
});
return freelancer_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 freelancer_assignmentsData = data.map((item, index) => ({
id: item.id || undefined,
role_on_project: item.role_on_project
||
null
,
rate_type: item.rate_type
||
null
,
rate: item.rate
||
null
,
start_at: item.start_at
||
null
,
end_at: item.end_at
||
null
,
status: item.status
||
null
,
estimated_hours: item.estimated_hours
||
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 freelancer_assignments = await db.freelancer_assignments.bulkCreate(freelancer_assignmentsData, { transaction });
// For each item created, replace relation files
return freelancer_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 freelancer_assignments = await db.freelancer_assignments.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.role_on_project !== undefined) updatePayload.role_on_project = data.role_on_project;
if (data.rate_type !== undefined) updatePayload.rate_type = data.rate_type;
if (data.rate !== undefined) updatePayload.rate = data.rate;
if (data.start_at !== undefined) updatePayload.start_at = data.start_at;
if (data.end_at !== undefined) updatePayload.end_at = data.end_at;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.estimated_hours !== undefined) updatePayload.estimated_hours = data.estimated_hours;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await freelancer_assignments.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await freelancer_assignments.setTenant(
data.tenant,
{ transaction }
);
}
if (data.freelancer !== undefined) {
await freelancer_assignments.setFreelancer(
data.freelancer,
{ transaction }
);
}
if (data.project !== undefined) {
await freelancer_assignments.setProject(
data.project,
{ transaction }
);
}
if (data.organizations !== undefined) {
await freelancer_assignments.setOrganizations(
data.organizations,
{ transaction }
);
}
return freelancer_assignments;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const freelancer_assignments = await db.freelancer_assignments.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of freelancer_assignments) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of freelancer_assignments) {
await record.destroy({transaction});
}
});
return freelancer_assignments;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const freelancer_assignments = await db.freelancer_assignments.findByPk(id, options);
await freelancer_assignments.update({
deletedBy: currentUser.id
}, {
transaction,
});
await freelancer_assignments.destroy({
transaction
});
return freelancer_assignments;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const freelancer_assignments = await db.freelancer_assignments.findOne(
{ where },
{ transaction },
);
if (!freelancer_assignments) {
return freelancer_assignments;
}
const output = freelancer_assignments.get({plain: true});
output.freelancer_payments_freelancer_assignment = await freelancer_assignments.getFreelancer_payments_freelancer_assignment({
transaction
});
output.time_entries_freelancer_assignment = await freelancer_assignments.getTime_entries_freelancer_assignment({
transaction
});
output.tenant = await freelancer_assignments.getTenant({
transaction
});
output.freelancer = await freelancer_assignments.getFreelancer({
transaction
});
output.project = await freelancer_assignments.getProject({
transaction
});
output.organizations = await freelancer_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.tenants,
as: 'tenant',
where: filter.tenant ? {
[Op.or]: [
{ id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.freelancers,
as: 'freelancer',
where: filter.freelancer ? {
[Op.or]: [
{ id: { [Op.in]: filter.freelancer.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.freelancer.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.projects,
as: 'project',
where: filter.project ? {
[Op.or]: [
{ id: { [Op.in]: filter.project.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.project.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(
'freelancer_assignments',
'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.rateRange) {
const [start, end] = filter.rateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
rate: {
...where.rate,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
rate: {
...where.rate,
[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.estimated_hoursRange) {
const [start, end] = filter.estimated_hoursRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
estimated_hours: {
...where.estimated_hours,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
estimated_hours: {
...where.estimated_hours,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.role_on_project) {
where = {
...where,
role_on_project: filter.role_on_project,
};
}
if (filter.rate_type) {
where = {
...where,
rate_type: filter.rate_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.freelancer_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(
'freelancer_assignments',
'role_on_project',
query,
),
],
};
}
const records = await db.freelancer_assignments.findAll({
attributes: [ 'id', 'role_on_project' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['role_on_project', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.role_on_project,
}));
}
};

View File

@ -0,0 +1,826 @@
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 Freelancer_paymentsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const freelancer_payments = await db.freelancer_payments.create(
{
id: data.id || undefined,
amount: data.amount
||
null
,
currency_code: data.currency_code
||
null
,
paid_at: data.paid_at
||
null
,
method: data.method
||
null
,
status: data.status
||
null
,
reference: data.reference
||
null
,
hours_billed: data.hours_billed
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await freelancer_payments.setTenant( data.tenant || null, {
transaction,
});
await freelancer_payments.setFreelancer( data.freelancer || null, {
transaction,
});
await freelancer_payments.setFreelancer_assignment( data.freelancer_assignment || null, {
transaction,
});
await freelancer_payments.setProject( data.project || null, {
transaction,
});
await freelancer_payments.setRecorded_by( data.recorded_by || null, {
transaction,
});
await freelancer_payments.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.freelancer_payments.getTableName(),
belongsToColumn: 'receipt_files',
belongsToId: freelancer_payments.id,
},
data.receipt_files,
options,
);
return freelancer_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 freelancer_paymentsData = data.map((item, index) => ({
id: item.id || undefined,
amount: item.amount
||
null
,
currency_code: item.currency_code
||
null
,
paid_at: item.paid_at
||
null
,
method: item.method
||
null
,
status: item.status
||
null
,
reference: item.reference
||
null
,
hours_billed: item.hours_billed
||
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 freelancer_payments = await db.freelancer_payments.bulkCreate(freelancer_paymentsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < freelancer_payments.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.freelancer_payments.getTableName(),
belongsToColumn: 'receipt_files',
belongsToId: freelancer_payments[i].id,
},
data[i].receipt_files,
options,
);
}
return freelancer_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 freelancer_payments = await db.freelancer_payments.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.amount !== undefined) updatePayload.amount = data.amount;
if (data.currency_code !== undefined) updatePayload.currency_code = data.currency_code;
if (data.paid_at !== undefined) updatePayload.paid_at = data.paid_at;
if (data.method !== undefined) updatePayload.method = data.method;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.reference !== undefined) updatePayload.reference = data.reference;
if (data.hours_billed !== undefined) updatePayload.hours_billed = data.hours_billed;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await freelancer_payments.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await freelancer_payments.setTenant(
data.tenant,
{ transaction }
);
}
if (data.freelancer !== undefined) {
await freelancer_payments.setFreelancer(
data.freelancer,
{ transaction }
);
}
if (data.freelancer_assignment !== undefined) {
await freelancer_payments.setFreelancer_assignment(
data.freelancer_assignment,
{ transaction }
);
}
if (data.project !== undefined) {
await freelancer_payments.setProject(
data.project,
{ transaction }
);
}
if (data.recorded_by !== undefined) {
await freelancer_payments.setRecorded_by(
data.recorded_by,
{ transaction }
);
}
if (data.organizations !== undefined) {
await freelancer_payments.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.freelancer_payments.getTableName(),
belongsToColumn: 'receipt_files',
belongsToId: freelancer_payments.id,
},
data.receipt_files,
options,
);
return freelancer_payments;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const freelancer_payments = await db.freelancer_payments.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of freelancer_payments) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of freelancer_payments) {
await record.destroy({transaction});
}
});
return freelancer_payments;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const freelancer_payments = await db.freelancer_payments.findByPk(id, options);
await freelancer_payments.update({
deletedBy: currentUser.id
}, {
transaction,
});
await freelancer_payments.destroy({
transaction
});
return freelancer_payments;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const freelancer_payments = await db.freelancer_payments.findOne(
{ where },
{ transaction },
);
if (!freelancer_payments) {
return freelancer_payments;
}
const output = freelancer_payments.get({plain: true});
output.tenant = await freelancer_payments.getTenant({
transaction
});
output.freelancer = await freelancer_payments.getFreelancer({
transaction
});
output.freelancer_assignment = await freelancer_payments.getFreelancer_assignment({
transaction
});
output.project = await freelancer_payments.getProject({
transaction
});
output.receipt_files = await freelancer_payments.getReceipt_files({
transaction
});
output.recorded_by = await freelancer_payments.getRecorded_by({
transaction
});
output.organizations = await freelancer_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.tenants,
as: 'tenant',
where: filter.tenant ? {
[Op.or]: [
{ id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.freelancers,
as: 'freelancer',
where: filter.freelancer ? {
[Op.or]: [
{ id: { [Op.in]: filter.freelancer.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.freelancer.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.freelancer_assignments,
as: 'freelancer_assignment',
where: filter.freelancer_assignment ? {
[Op.or]: [
{ id: { [Op.in]: filter.freelancer_assignment.split('|').map(term => Utils.uuid(term)) } },
{
role_on_project: {
[Op.or]: filter.freelancer_assignment.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.projects,
as: 'project',
where: filter.project ? {
[Op.or]: [
{ id: { [Op.in]: filter.project.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.project.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'recorded_by',
where: filter.recorded_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.recorded_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.recorded_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'receipt_files',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.currency_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'freelancer_payments',
'currency_code',
filter.currency_code,
),
};
}
if (filter.reference) {
where = {
...where,
[Op.and]: Utils.ilike(
'freelancer_payments',
'reference',
filter.reference,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'freelancer_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.hours_billedRange) {
const [start, end] = filter.hours_billedRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
hours_billed: {
...where.hours_billed,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
hours_billed: {
...where.hours_billed,
[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.freelancer_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(
'freelancer_payments',
'reference',
query,
),
],
};
}
const records = await db.freelancer_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,708 @@
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 FreelancersDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const freelancers = await db.freelancers.create(
{
id: data.id || undefined,
name: data.name
||
null
,
email: data.email
||
null
,
phone: data.phone
||
null
,
website: data.website
||
null
,
status: data.status
||
null
,
default_rate_type: data.default_rate_type
||
null
,
default_rate: data.default_rate
||
null
,
currency_code: data.currency_code
||
null
,
skills: data.skills
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await freelancers.setTenant( data.tenant || null, {
transaction,
});
await freelancers.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.freelancers.getTableName(),
belongsToColumn: 'contracts_files',
belongsToId: freelancers.id,
},
data.contracts_files,
options,
);
return freelancers;
}
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 freelancersData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
email: item.email
||
null
,
phone: item.phone
||
null
,
website: item.website
||
null
,
status: item.status
||
null
,
default_rate_type: item.default_rate_type
||
null
,
default_rate: item.default_rate
||
null
,
currency_code: item.currency_code
||
null
,
skills: item.skills
||
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 freelancers = await db.freelancers.bulkCreate(freelancersData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < freelancers.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.freelancers.getTableName(),
belongsToColumn: 'contracts_files',
belongsToId: freelancers[i].id,
},
data[i].contracts_files,
options,
);
}
return freelancers;
}
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 freelancers = await db.freelancers.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.email !== undefined) updatePayload.email = data.email;
if (data.phone !== undefined) updatePayload.phone = data.phone;
if (data.website !== undefined) updatePayload.website = data.website;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.default_rate_type !== undefined) updatePayload.default_rate_type = data.default_rate_type;
if (data.default_rate !== undefined) updatePayload.default_rate = data.default_rate;
if (data.currency_code !== undefined) updatePayload.currency_code = data.currency_code;
if (data.skills !== undefined) updatePayload.skills = data.skills;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await freelancers.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await freelancers.setTenant(
data.tenant,
{ transaction }
);
}
if (data.organizations !== undefined) {
await freelancers.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.freelancers.getTableName(),
belongsToColumn: 'contracts_files',
belongsToId: freelancers.id,
},
data.contracts_files,
options,
);
return freelancers;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const freelancers = await db.freelancers.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of freelancers) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of freelancers) {
await record.destroy({transaction});
}
});
return freelancers;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const freelancers = await db.freelancers.findByPk(id, options);
await freelancers.update({
deletedBy: currentUser.id
}, {
transaction,
});
await freelancers.destroy({
transaction
});
return freelancers;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const freelancers = await db.freelancers.findOne(
{ where },
{ transaction },
);
if (!freelancers) {
return freelancers;
}
const output = freelancers.get({plain: true});
output.freelancer_assignments_freelancer = await freelancers.getFreelancer_assignments_freelancer({
transaction
});
output.freelancer_payments_freelancer = await freelancers.getFreelancer_payments_freelancer({
transaction
});
output.tenant = await freelancers.getTenant({
transaction
});
output.contracts_files = await freelancers.getContracts_files({
transaction
});
output.organizations = await freelancers.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.tenants,
as: 'tenant',
where: filter.tenant ? {
[Op.or]: [
{ id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'contracts_files',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'freelancers',
'name',
filter.name,
),
};
}
if (filter.email) {
where = {
...where,
[Op.and]: Utils.ilike(
'freelancers',
'email',
filter.email,
),
};
}
if (filter.phone) {
where = {
...where,
[Op.and]: Utils.ilike(
'freelancers',
'phone',
filter.phone,
),
};
}
if (filter.website) {
where = {
...where,
[Op.and]: Utils.ilike(
'freelancers',
'website',
filter.website,
),
};
}
if (filter.currency_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'freelancers',
'currency_code',
filter.currency_code,
),
};
}
if (filter.skills) {
where = {
...where,
[Op.and]: Utils.ilike(
'freelancers',
'skills',
filter.skills,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'freelancers',
'notes',
filter.notes,
),
};
}
if (filter.default_rateRange) {
const [start, end] = filter.default_rateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
default_rate: {
...where.default_rate,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
default_rate: {
...where.default_rate,
[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.default_rate_type) {
where = {
...where,
default_rate_type: filter.default_rate_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.freelancers.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(
'freelancers',
'name',
query,
),
],
};
}
const records = await db.freelancers.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,703 @@
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,
name: data.name
||
null
,
description: data.description
||
null
,
quantity: data.quantity
||
null
,
unit_price: data.unit_price
||
null
,
unit_type: data.unit_type
||
null
,
tax_rate: data.tax_rate
||
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.setTenant( data.tenant || 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,
name: item.name
||
null
,
description: item.description
||
null
,
quantity: item.quantity
||
null
,
unit_price: item.unit_price
||
null
,
unit_type: item.unit_type
||
null
,
tax_rate: item.tax_rate
||
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.name !== undefined) updatePayload.name = data.name;
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.unit_type !== undefined) updatePayload.unit_type = data.unit_type;
if (data.tax_rate !== undefined) updatePayload.tax_rate = data.tax_rate;
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.tenant !== undefined) {
await invoice_line_items.setTenant(
data.tenant,
{ 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.tenant = await invoice_line_items.getTenant({
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.tenants,
as: 'tenant',
where: filter.tenant ? {
[Op.or]: [
{ id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.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.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'invoice_line_items',
'name',
filter.name,
),
};
}
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.tax_rateRange) {
const [start, end] = filter.tax_rateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
tax_rate: {
...where.tax_rate,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
tax_rate: {
...where.tax_rate,
[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.unit_type) {
where = {
...where,
unit_type: filter.unit_type,
};
}
if (filter.organizations) {
const listItems = filter.organizations.split('|').map(item => {
return Utils.uuid(item)
});
where = {
...where,
organizationsId: {[Op.or]: listItems}
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
if (globalAccess) {
delete where.organizationsId;
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.invoice_line_items.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'invoice_line_items',
'name',
query,
),
],
};
}
const records = await db.invoice_line_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,
}));
}
};

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,431 @@
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.tenants_organizations = await organizations.getTenants_organizations({
transaction
});
output.clients_organizations = await organizations.getClients_organizations({
transaction
});
output.projects_organizations = await organizations.getProjects_organizations({
transaction
});
output.estimates_organizations = await organizations.getEstimates_organizations({
transaction
});
output.estimate_line_items_organizations = await organizations.getEstimate_line_items_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.vendors_organizations = await organizations.getVendors_organizations({
transaction
});
output.vendor_bills_organizations = await organizations.getVendor_bills_organizations({
transaction
});
output.vendor_bill_line_items_organizations = await organizations.getVendor_bill_line_items_organizations({
transaction
});
output.vendor_payments_organizations = await organizations.getVendor_payments_organizations({
transaction
});
output.freelancers_organizations = await organizations.getFreelancers_organizations({
transaction
});
output.freelancer_assignments_organizations = await organizations.getFreelancer_assignments_organizations({
transaction
});
output.freelancer_payments_organizations = await organizations.getFreelancer_payments_organizations({
transaction
});
output.time_entries_organizations = await organizations.getTime_entries_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,752 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class 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
,
currency_code: data.currency_code
||
null
,
paid_at: data.paid_at
||
null
,
method: data.method
||
null
,
status: data.status
||
null
,
reference: data.reference
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await payments.setTenant( data.tenant || null, {
transaction,
});
await payments.setInvoice( data.invoice || null, {
transaction,
});
await payments.setClient( data.client || null, {
transaction,
});
await payments.setRecorded_by( data.recorded_by || null, {
transaction,
});
await payments.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.payments.getTableName(),
belongsToColumn: 'receipt_files',
belongsToId: payments.id,
},
data.receipt_files,
options,
);
return payments;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const paymentsData = data.map((item, index) => ({
id: item.id || undefined,
amount: item.amount
||
null
,
currency_code: item.currency_code
||
null
,
paid_at: item.paid_at
||
null
,
method: item.method
||
null
,
status: item.status
||
null
,
reference: item.reference
||
null
,
notes: item.notes
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const payments = await db.payments.bulkCreate(paymentsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < payments.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.payments.getTableName(),
belongsToColumn: 'receipt_files',
belongsToId: payments[i].id,
},
data[i].receipt_files,
options,
);
}
return payments;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const payments = await db.payments.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.amount !== undefined) updatePayload.amount = data.amount;
if (data.currency_code !== undefined) updatePayload.currency_code = data.currency_code;
if (data.paid_at !== undefined) updatePayload.paid_at = data.paid_at;
if (data.method !== undefined) updatePayload.method = data.method;
if (data.status !== undefined) updatePayload.status = data.status;
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.tenant !== undefined) {
await payments.setTenant(
data.tenant,
{ transaction }
);
}
if (data.invoice !== undefined) {
await payments.setInvoice(
data.invoice,
{ transaction }
);
}
if (data.client !== undefined) {
await payments.setClient(
data.client,
{ transaction }
);
}
if (data.recorded_by !== undefined) {
await payments.setRecorded_by(
data.recorded_by,
{ transaction }
);
}
if (data.organizations !== undefined) {
await payments.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.payments.getTableName(),
belongsToColumn: 'receipt_files',
belongsToId: payments.id,
},
data.receipt_files,
options,
);
return payments;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const payments = await db.payments.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of payments) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of payments) {
await record.destroy({transaction});
}
});
return payments;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const payments = await db.payments.findByPk(id, options);
await payments.update({
deletedBy: currentUser.id
}, {
transaction,
});
await payments.destroy({
transaction
});
return payments;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const payments = await db.payments.findOne(
{ where },
{ transaction },
);
if (!payments) {
return payments;
}
const output = payments.get({plain: true});
output.tenant = await payments.getTenant({
transaction
});
output.invoice = await payments.getInvoice({
transaction
});
output.client = await payments.getClient({
transaction
});
output.receipt_files = await payments.getReceipt_files({
transaction
});
output.recorded_by = await payments.getRecorded_by({
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.tenants,
as: 'tenant',
where: filter.tenant ? {
[Op.or]: [
{ id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.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.clients,
as: 'client',
where: filter.client ? {
[Op.or]: [
{ id: { [Op.in]: filter.client.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.client.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'recorded_by',
where: filter.recorded_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.recorded_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.recorded_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'receipt_files',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.currency_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'payments',
'currency_code',
filter.currency_code,
),
};
}
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,349 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class PermissionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const permissions = await db.permissions.create(
{
id: data.id || undefined,
name: data.name
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return permissions;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const permissionsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const permissions = await db.permissions.bulkCreate(permissionsData, { transaction });
// For each item created, replace relation files
return permissions;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const permissions = await db.permissions.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
updatePayload.updatedById = currentUser.id;
await permissions.update(updatePayload, {transaction});
return permissions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const permissions = await db.permissions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of permissions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of permissions) {
await record.destroy({transaction});
}
});
return permissions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const permissions = await db.permissions.findByPk(id, options);
await permissions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await permissions.destroy({
transaction
});
return permissions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const permissions = await db.permissions.findOne(
{ where },
{ transaction },
);
if (!permissions) {
return permissions;
}
const output = permissions.get({plain: true});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'permissions',
'name',
filter.name,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.permissions.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'permissions',
'name',
query,
),
],
};
}
const records = await db.permissions.findAll({
attributes: [ 'id', 'name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.name,
}));
}
};

View File

@ -0,0 +1,774 @@
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 ProjectsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const projects = await db.projects.create(
{
id: data.id || undefined,
name: data.name
||
null
,
code: data.code
||
null
,
status: data.status
||
null
,
start_at: data.start_at
||
null
,
end_at: data.end_at
||
null
,
budget_amount: data.budget_amount
||
null
,
billing_method: data.billing_method
||
null
,
billable: data.billable
||
false
,
description: data.description
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await projects.setTenant( data.tenant || null, {
transaction,
});
await projects.setClient( data.client || null, {
transaction,
});
await projects.setOwner( data.owner || null, {
transaction,
});
await projects.setOrganizations( data.organizations || null, {
transaction,
});
return projects;
}
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 projectsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
code: item.code
||
null
,
status: item.status
||
null
,
start_at: item.start_at
||
null
,
end_at: item.end_at
||
null
,
budget_amount: item.budget_amount
||
null
,
billing_method: item.billing_method
||
null
,
billable: item.billable
||
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 projects = await db.projects.bulkCreate(projectsData, { transaction });
// For each item created, replace relation files
return projects;
}
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 projects = await db.projects.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.code !== undefined) updatePayload.code = data.code;
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.budget_amount !== undefined) updatePayload.budget_amount = data.budget_amount;
if (data.billing_method !== undefined) updatePayload.billing_method = data.billing_method;
if (data.billable !== undefined) updatePayload.billable = data.billable;
if (data.description !== undefined) updatePayload.description = data.description;
updatePayload.updatedById = currentUser.id;
await projects.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await projects.setTenant(
data.tenant,
{ transaction }
);
}
if (data.client !== undefined) {
await projects.setClient(
data.client,
{ transaction }
);
}
if (data.owner !== undefined) {
await projects.setOwner(
data.owner,
{ transaction }
);
}
if (data.organizations !== undefined) {
await projects.setOrganizations(
data.organizations,
{ transaction }
);
}
return projects;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const projects = await db.projects.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of projects) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of projects) {
await record.destroy({transaction});
}
});
return projects;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const projects = await db.projects.findByPk(id, options);
await projects.update({
deletedBy: currentUser.id
}, {
transaction,
});
await projects.destroy({
transaction
});
return projects;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const projects = await db.projects.findOne(
{ where },
{ transaction },
);
if (!projects) {
return projects;
}
const output = projects.get({plain: true});
output.estimates_project = await projects.getEstimates_project({
transaction
});
output.invoices_project = await projects.getInvoices_project({
transaction
});
output.vendor_bills_project = await projects.getVendor_bills_project({
transaction
});
output.freelancer_assignments_project = await projects.getFreelancer_assignments_project({
transaction
});
output.freelancer_payments_project = await projects.getFreelancer_payments_project({
transaction
});
output.time_entries_project = await projects.getTime_entries_project({
transaction
});
output.tenant = await projects.getTenant({
transaction
});
output.client = await projects.getClient({
transaction
});
output.owner = await projects.getOwner({
transaction
});
output.organizations = await projects.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.tenants,
as: 'tenant',
where: filter.tenant ? {
[Op.or]: [
{ id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.clients,
as: 'client',
where: filter.client ? {
[Op.or]: [
{ id: { [Op.in]: filter.client.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.client.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.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(
'projects',
'name',
filter.name,
),
};
}
if (filter.code) {
where = {
...where,
[Op.and]: Utils.ilike(
'projects',
'code',
filter.code,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'projects',
'description',
filter.description,
),
};
}
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.budget_amountRange) {
const [start, end] = filter.budget_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
budget_amount: {
...where.budget_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
budget_amount: {
...where.budget_amount,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.billing_method) {
where = {
...where,
billing_method: filter.billing_method,
};
}
if (filter.billable) {
where = {
...where,
billable: filter.billable,
};
}
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.projects.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(
'projects',
'name',
query,
),
],
};
}
const records = await db.projects.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,
}));
}
};

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

@ -0,0 +1,451 @@
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,908 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class TenantsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const tenants = await db.tenants.create(
{
id: data.id || undefined,
name: data.name
||
null
,
slug: data.slug
||
null
,
status: data.status
||
null
,
primary_email: data.primary_email
||
null
,
primary_phone: data.primary_phone
||
null
,
website: data.website
||
null
,
timezone: data.timezone
||
null
,
currency_code: data.currency_code
||
null
,
address_line1: data.address_line1
||
null
,
address_line2: data.address_line2
||
null
,
city: data.city
||
null
,
region: data.region
||
null
,
postal_code: data.postal_code
||
null
,
country: data.country
||
null
,
tax_number: data.tax_number
||
null
,
trial_ends_on: data.trial_ends_on
||
null
,
subscription_ends_on: data.subscription_ends_on
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await tenants.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.tenants.getTableName(),
belongsToColumn: 'logo',
belongsToId: tenants.id,
},
data.logo,
options,
);
return tenants;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const tenantsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
slug: item.slug
||
null
,
status: item.status
||
null
,
primary_email: item.primary_email
||
null
,
primary_phone: item.primary_phone
||
null
,
website: item.website
||
null
,
timezone: item.timezone
||
null
,
currency_code: item.currency_code
||
null
,
address_line1: item.address_line1
||
null
,
address_line2: item.address_line2
||
null
,
city: item.city
||
null
,
region: item.region
||
null
,
postal_code: item.postal_code
||
null
,
country: item.country
||
null
,
tax_number: item.tax_number
||
null
,
trial_ends_on: item.trial_ends_on
||
null
,
subscription_ends_on: item.subscription_ends_on
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const tenants = await db.tenants.bulkCreate(tenantsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < tenants.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.tenants.getTableName(),
belongsToColumn: 'logo',
belongsToId: tenants[i].id,
},
data[i].logo,
options,
);
}
return tenants;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const tenants = await db.tenants.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.slug !== undefined) updatePayload.slug = data.slug;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.primary_email !== undefined) updatePayload.primary_email = data.primary_email;
if (data.primary_phone !== undefined) updatePayload.primary_phone = data.primary_phone;
if (data.website !== undefined) updatePayload.website = data.website;
if (data.timezone !== undefined) updatePayload.timezone = data.timezone;
if (data.currency_code !== undefined) updatePayload.currency_code = data.currency_code;
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.region !== undefined) updatePayload.region = data.region;
if (data.postal_code !== undefined) updatePayload.postal_code = data.postal_code;
if (data.country !== undefined) updatePayload.country = data.country;
if (data.tax_number !== undefined) updatePayload.tax_number = data.tax_number;
if (data.trial_ends_on !== undefined) updatePayload.trial_ends_on = data.trial_ends_on;
if (data.subscription_ends_on !== undefined) updatePayload.subscription_ends_on = data.subscription_ends_on;
updatePayload.updatedById = currentUser.id;
await tenants.update(updatePayload, {transaction});
if (data.organizations !== undefined) {
await tenants.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.tenants.getTableName(),
belongsToColumn: 'logo',
belongsToId: tenants.id,
},
data.logo,
options,
);
return tenants;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const tenants = await db.tenants.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of tenants) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of tenants) {
await record.destroy({transaction});
}
});
return tenants;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const tenants = await db.tenants.findByPk(id, options);
await tenants.update({
deletedBy: currentUser.id
}, {
transaction,
});
await tenants.destroy({
transaction
});
return tenants;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const tenants = await db.tenants.findOne(
{ where },
{ transaction },
);
if (!tenants) {
return tenants;
}
const output = tenants.get({plain: true});
output.clients_tenant = await tenants.getClients_tenant({
transaction
});
output.projects_tenant = await tenants.getProjects_tenant({
transaction
});
output.estimates_tenant = await tenants.getEstimates_tenant({
transaction
});
output.estimate_line_items_tenant = await tenants.getEstimate_line_items_tenant({
transaction
});
output.invoices_tenant = await tenants.getInvoices_tenant({
transaction
});
output.invoice_line_items_tenant = await tenants.getInvoice_line_items_tenant({
transaction
});
output.payments_tenant = await tenants.getPayments_tenant({
transaction
});
output.vendors_tenant = await tenants.getVendors_tenant({
transaction
});
output.vendor_bills_tenant = await tenants.getVendor_bills_tenant({
transaction
});
output.vendor_bill_line_items_tenant = await tenants.getVendor_bill_line_items_tenant({
transaction
});
output.vendor_payments_tenant = await tenants.getVendor_payments_tenant({
transaction
});
output.freelancers_tenant = await tenants.getFreelancers_tenant({
transaction
});
output.freelancer_assignments_tenant = await tenants.getFreelancer_assignments_tenant({
transaction
});
output.freelancer_payments_tenant = await tenants.getFreelancer_payments_tenant({
transaction
});
output.time_entries_tenant = await tenants.getTime_entries_tenant({
transaction
});
output.logo = await tenants.getLogo({
transaction
});
output.organizations = await tenants.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',
},
{
model: db.file,
as: 'logo',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'tenants',
'name',
filter.name,
),
};
}
if (filter.slug) {
where = {
...where,
[Op.and]: Utils.ilike(
'tenants',
'slug',
filter.slug,
),
};
}
if (filter.primary_email) {
where = {
...where,
[Op.and]: Utils.ilike(
'tenants',
'primary_email',
filter.primary_email,
),
};
}
if (filter.primary_phone) {
where = {
...where,
[Op.and]: Utils.ilike(
'tenants',
'primary_phone',
filter.primary_phone,
),
};
}
if (filter.website) {
where = {
...where,
[Op.and]: Utils.ilike(
'tenants',
'website',
filter.website,
),
};
}
if (filter.timezone) {
where = {
...where,
[Op.and]: Utils.ilike(
'tenants',
'timezone',
filter.timezone,
),
};
}
if (filter.currency_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'tenants',
'currency_code',
filter.currency_code,
),
};
}
if (filter.address_line1) {
where = {
...where,
[Op.and]: Utils.ilike(
'tenants',
'address_line1',
filter.address_line1,
),
};
}
if (filter.address_line2) {
where = {
...where,
[Op.and]: Utils.ilike(
'tenants',
'address_line2',
filter.address_line2,
),
};
}
if (filter.city) {
where = {
...where,
[Op.and]: Utils.ilike(
'tenants',
'city',
filter.city,
),
};
}
if (filter.region) {
where = {
...where,
[Op.and]: Utils.ilike(
'tenants',
'region',
filter.region,
),
};
}
if (filter.postal_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'tenants',
'postal_code',
filter.postal_code,
),
};
}
if (filter.country) {
where = {
...where,
[Op.and]: Utils.ilike(
'tenants',
'country',
filter.country,
),
};
}
if (filter.tax_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'tenants',
'tax_number',
filter.tax_number,
),
};
}
if (filter.trial_ends_onRange) {
const [start, end] = filter.trial_ends_onRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
trial_ends_on: {
...where.trial_ends_on,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
trial_ends_on: {
...where.trial_ends_on,
[Op.lte]: end,
},
};
}
}
if (filter.subscription_ends_onRange) {
const [start, end] = filter.subscription_ends_onRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
subscription_ends_on: {
...where.subscription_ends_on,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
subscription_ends_on: {
...where.subscription_ends_on,
[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.tenants.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, globalAccess, organizationId,) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'tenants',
'name',
query,
),
],
};
}
const records = await db.tenants.findAll({
attributes: [ 'id', 'name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.name,
}));
}
};

View File

@ -0,0 +1,830 @@
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 Time_entriesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const time_entries = await db.time_entries.create(
{
id: data.id || undefined,
started_at: data.started_at
||
null
,
ended_at: data.ended_at
||
null
,
duration_hours: data.duration_hours
||
null
,
billable: data.billable
||
false
,
bill_rate: data.bill_rate
||
null
,
cost_rate: data.cost_rate
||
null
,
description: data.description
||
null
,
status: data.status
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await time_entries.setTenant( data.tenant || null, {
transaction,
});
await time_entries.setProject( data.project || null, {
transaction,
});
await time_entries.setClient( data.client || null, {
transaction,
});
await time_entries.setUser( data.user || null, {
transaction,
});
await time_entries.setFreelancer_assignment( data.freelancer_assignment || null, {
transaction,
});
await time_entries.setOrganizations( data.organizations || null, {
transaction,
});
return time_entries;
}
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 time_entriesData = data.map((item, index) => ({
id: item.id || undefined,
started_at: item.started_at
||
null
,
ended_at: item.ended_at
||
null
,
duration_hours: item.duration_hours
||
null
,
billable: item.billable
||
false
,
bill_rate: item.bill_rate
||
null
,
cost_rate: item.cost_rate
||
null
,
description: item.description
||
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 time_entries = await db.time_entries.bulkCreate(time_entriesData, { transaction });
// For each item created, replace relation files
return time_entries;
}
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 time_entries = await db.time_entries.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
if (data.ended_at !== undefined) updatePayload.ended_at = data.ended_at;
if (data.duration_hours !== undefined) updatePayload.duration_hours = data.duration_hours;
if (data.billable !== undefined) updatePayload.billable = data.billable;
if (data.bill_rate !== undefined) updatePayload.bill_rate = data.bill_rate;
if (data.cost_rate !== undefined) updatePayload.cost_rate = data.cost_rate;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.status !== undefined) updatePayload.status = data.status;
updatePayload.updatedById = currentUser.id;
await time_entries.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await time_entries.setTenant(
data.tenant,
{ transaction }
);
}
if (data.project !== undefined) {
await time_entries.setProject(
data.project,
{ transaction }
);
}
if (data.client !== undefined) {
await time_entries.setClient(
data.client,
{ transaction }
);
}
if (data.user !== undefined) {
await time_entries.setUser(
data.user,
{ transaction }
);
}
if (data.freelancer_assignment !== undefined) {
await time_entries.setFreelancer_assignment(
data.freelancer_assignment,
{ transaction }
);
}
if (data.organizations !== undefined) {
await time_entries.setOrganizations(
data.organizations,
{ transaction }
);
}
return time_entries;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const time_entries = await db.time_entries.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of time_entries) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of time_entries) {
await record.destroy({transaction});
}
});
return time_entries;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const time_entries = await db.time_entries.findByPk(id, options);
await time_entries.update({
deletedBy: currentUser.id
}, {
transaction,
});
await time_entries.destroy({
transaction
});
return time_entries;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const time_entries = await db.time_entries.findOne(
{ where },
{ transaction },
);
if (!time_entries) {
return time_entries;
}
const output = time_entries.get({plain: true});
output.tenant = await time_entries.getTenant({
transaction
});
output.project = await time_entries.getProject({
transaction
});
output.client = await time_entries.getClient({
transaction
});
output.user = await time_entries.getUser({
transaction
});
output.freelancer_assignment = await time_entries.getFreelancer_assignment({
transaction
});
output.organizations = await time_entries.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.tenants,
as: 'tenant',
where: filter.tenant ? {
[Op.or]: [
{ id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.projects,
as: 'project',
where: filter.project ? {
[Op.or]: [
{ id: { [Op.in]: filter.project.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.project.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.clients,
as: 'client',
where: filter.client ? {
[Op.or]: [
{ id: { [Op.in]: filter.client.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.client.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.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.freelancer_assignments,
as: 'freelancer_assignment',
where: filter.freelancer_assignment ? {
[Op.or]: [
{ id: { [Op.in]: filter.freelancer_assignment.split('|').map(term => Utils.uuid(term)) } },
{
role_on_project: {
[Op.or]: filter.freelancer_assignment.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(
'time_entries',
'description',
filter.description,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
started_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
ended_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.started_atRange) {
const [start, end] = filter.started_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
started_at: {
...where.started_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
started_at: {
...where.started_at,
[Op.lte]: end,
},
};
}
}
if (filter.ended_atRange) {
const [start, end] = filter.ended_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
ended_at: {
...where.ended_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
ended_at: {
...where.ended_at,
[Op.lte]: end,
},
};
}
}
if (filter.duration_hoursRange) {
const [start, end] = filter.duration_hoursRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
duration_hours: {
...where.duration_hours,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
duration_hours: {
...where.duration_hours,
[Op.lte]: end,
},
};
}
}
if (filter.bill_rateRange) {
const [start, end] = filter.bill_rateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
bill_rate: {
...where.bill_rate,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
bill_rate: {
...where.bill_rate,
[Op.lte]: end,
},
};
}
}
if (filter.cost_rateRange) {
const [start, end] = filter.cost_rateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
cost_rate: {
...where.cost_rate,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
cost_rate: {
...where.cost_rate,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.billable) {
where = {
...where,
billable: filter.billable,
};
}
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.time_entries.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(
'time_entries',
'description',
query,
),
],
};
}
const records = await db.time_entries.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,
}));
}
};

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

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,703 @@
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 Vendor_bill_line_itemsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const vendor_bill_line_items = await db.vendor_bill_line_items.create(
{
id: data.id || undefined,
name: data.name
||
null
,
description: data.description
||
null
,
quantity: data.quantity
||
null
,
unit_cost: data.unit_cost
||
null
,
unit_type: data.unit_type
||
null
,
tax_rate: data.tax_rate
||
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 vendor_bill_line_items.setTenant( data.tenant || null, {
transaction,
});
await vendor_bill_line_items.setVendor_bill( data.vendor_bill || null, {
transaction,
});
await vendor_bill_line_items.setOrganizations( data.organizations || null, {
transaction,
});
return vendor_bill_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 vendor_bill_line_itemsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
description: item.description
||
null
,
quantity: item.quantity
||
null
,
unit_cost: item.unit_cost
||
null
,
unit_type: item.unit_type
||
null
,
tax_rate: item.tax_rate
||
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 vendor_bill_line_items = await db.vendor_bill_line_items.bulkCreate(vendor_bill_line_itemsData, { transaction });
// For each item created, replace relation files
return vendor_bill_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 vendor_bill_line_items = await db.vendor_bill_line_items.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.quantity !== undefined) updatePayload.quantity = data.quantity;
if (data.unit_cost !== undefined) updatePayload.unit_cost = data.unit_cost;
if (data.unit_type !== undefined) updatePayload.unit_type = data.unit_type;
if (data.tax_rate !== undefined) updatePayload.tax_rate = data.tax_rate;
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 vendor_bill_line_items.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await vendor_bill_line_items.setTenant(
data.tenant,
{ transaction }
);
}
if (data.vendor_bill !== undefined) {
await vendor_bill_line_items.setVendor_bill(
data.vendor_bill,
{ transaction }
);
}
if (data.organizations !== undefined) {
await vendor_bill_line_items.setOrganizations(
data.organizations,
{ transaction }
);
}
return vendor_bill_line_items;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const vendor_bill_line_items = await db.vendor_bill_line_items.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of vendor_bill_line_items) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of vendor_bill_line_items) {
await record.destroy({transaction});
}
});
return vendor_bill_line_items;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const vendor_bill_line_items = await db.vendor_bill_line_items.findByPk(id, options);
await vendor_bill_line_items.update({
deletedBy: currentUser.id
}, {
transaction,
});
await vendor_bill_line_items.destroy({
transaction
});
return vendor_bill_line_items;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const vendor_bill_line_items = await db.vendor_bill_line_items.findOne(
{ where },
{ transaction },
);
if (!vendor_bill_line_items) {
return vendor_bill_line_items;
}
const output = vendor_bill_line_items.get({plain: true});
output.tenant = await vendor_bill_line_items.getTenant({
transaction
});
output.vendor_bill = await vendor_bill_line_items.getVendor_bill({
transaction
});
output.organizations = await vendor_bill_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.tenants,
as: 'tenant',
where: filter.tenant ? {
[Op.or]: [
{ id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.vendor_bills,
as: 'vendor_bill',
where: filter.vendor_bill ? {
[Op.or]: [
{ id: { [Op.in]: filter.vendor_bill.split('|').map(term => Utils.uuid(term)) } },
{
bill_number: {
[Op.or]: filter.vendor_bill.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(
'vendor_bill_line_items',
'name',
filter.name,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'vendor_bill_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_costRange) {
const [start, end] = filter.unit_costRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
unit_cost: {
...where.unit_cost,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
unit_cost: {
...where.unit_cost,
[Op.lte]: end,
},
};
}
}
if (filter.tax_rateRange) {
const [start, end] = filter.tax_rateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
tax_rate: {
...where.tax_rate,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
tax_rate: {
...where.tax_rate,
[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.unit_type) {
where = {
...where,
unit_type: filter.unit_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.vendor_bill_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(
'vendor_bill_line_items',
'name',
query,
),
],
};
}
const records = await db.vendor_bill_line_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,925 @@
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 Vendor_billsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const vendor_bills = await db.vendor_bills.create(
{
id: data.id || undefined,
bill_number: data.bill_number
||
null
,
status: data.status
||
null
,
bill_date: data.bill_date
||
null
,
due_date: data.due_date
||
null
,
currency_code: data.currency_code
||
null
,
subtotal_amount: data.subtotal_amount
||
null
,
tax_amount: data.tax_amount
||
null
,
total_amount: data.total_amount
||
null
,
amount_paid: data.amount_paid
||
null
,
amount_due: data.amount_due
||
null
,
memo: data.memo
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await vendor_bills.setTenant( data.tenant || null, {
transaction,
});
await vendor_bills.setVendor( data.vendor || null, {
transaction,
});
await vendor_bills.setProject( data.project || null, {
transaction,
});
await vendor_bills.setEntered_by( data.entered_by || null, {
transaction,
});
await vendor_bills.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.vendor_bills.getTableName(),
belongsToColumn: 'attachments',
belongsToId: vendor_bills.id,
},
data.attachments,
options,
);
return vendor_bills;
}
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 vendor_billsData = data.map((item, index) => ({
id: item.id || undefined,
bill_number: item.bill_number
||
null
,
status: item.status
||
null
,
bill_date: item.bill_date
||
null
,
due_date: item.due_date
||
null
,
currency_code: item.currency_code
||
null
,
subtotal_amount: item.subtotal_amount
||
null
,
tax_amount: item.tax_amount
||
null
,
total_amount: item.total_amount
||
null
,
amount_paid: item.amount_paid
||
null
,
amount_due: item.amount_due
||
null
,
memo: item.memo
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const vendor_bills = await db.vendor_bills.bulkCreate(vendor_billsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < vendor_bills.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.vendor_bills.getTableName(),
belongsToColumn: 'attachments',
belongsToId: vendor_bills[i].id,
},
data[i].attachments,
options,
);
}
return vendor_bills;
}
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 vendor_bills = await db.vendor_bills.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.bill_number !== undefined) updatePayload.bill_number = data.bill_number;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.bill_date !== undefined) updatePayload.bill_date = data.bill_date;
if (data.due_date !== undefined) updatePayload.due_date = data.due_date;
if (data.currency_code !== undefined) updatePayload.currency_code = data.currency_code;
if (data.subtotal_amount !== undefined) updatePayload.subtotal_amount = data.subtotal_amount;
if (data.tax_amount !== undefined) updatePayload.tax_amount = data.tax_amount;
if (data.total_amount !== undefined) updatePayload.total_amount = data.total_amount;
if (data.amount_paid !== undefined) updatePayload.amount_paid = data.amount_paid;
if (data.amount_due !== undefined) updatePayload.amount_due = data.amount_due;
if (data.memo !== undefined) updatePayload.memo = data.memo;
updatePayload.updatedById = currentUser.id;
await vendor_bills.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await vendor_bills.setTenant(
data.tenant,
{ transaction }
);
}
if (data.vendor !== undefined) {
await vendor_bills.setVendor(
data.vendor,
{ transaction }
);
}
if (data.project !== undefined) {
await vendor_bills.setProject(
data.project,
{ transaction }
);
}
if (data.entered_by !== undefined) {
await vendor_bills.setEntered_by(
data.entered_by,
{ transaction }
);
}
if (data.organizations !== undefined) {
await vendor_bills.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.vendor_bills.getTableName(),
belongsToColumn: 'attachments',
belongsToId: vendor_bills.id,
},
data.attachments,
options,
);
return vendor_bills;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const vendor_bills = await db.vendor_bills.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of vendor_bills) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of vendor_bills) {
await record.destroy({transaction});
}
});
return vendor_bills;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const vendor_bills = await db.vendor_bills.findByPk(id, options);
await vendor_bills.update({
deletedBy: currentUser.id
}, {
transaction,
});
await vendor_bills.destroy({
transaction
});
return vendor_bills;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const vendor_bills = await db.vendor_bills.findOne(
{ where },
{ transaction },
);
if (!vendor_bills) {
return vendor_bills;
}
const output = vendor_bills.get({plain: true});
output.vendor_bill_line_items_vendor_bill = await vendor_bills.getVendor_bill_line_items_vendor_bill({
transaction
});
output.vendor_payments_vendor_bill = await vendor_bills.getVendor_payments_vendor_bill({
transaction
});
output.tenant = await vendor_bills.getTenant({
transaction
});
output.vendor = await vendor_bills.getVendor({
transaction
});
output.project = await vendor_bills.getProject({
transaction
});
output.attachments = await vendor_bills.getAttachments({
transaction
});
output.entered_by = await vendor_bills.getEntered_by({
transaction
});
output.organizations = await vendor_bills.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.tenants,
as: 'tenant',
where: filter.tenant ? {
[Op.or]: [
{ id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.vendors,
as: 'vendor',
where: filter.vendor ? {
[Op.or]: [
{ id: { [Op.in]: filter.vendor.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.vendor.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.projects,
as: 'project',
where: filter.project ? {
[Op.or]: [
{ id: { [Op.in]: filter.project.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.project.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'entered_by',
where: filter.entered_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.entered_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.entered_by.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.bill_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'vendor_bills',
'bill_number',
filter.bill_number,
),
};
}
if (filter.currency_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'vendor_bills',
'currency_code',
filter.currency_code,
),
};
}
if (filter.memo) {
where = {
...where,
[Op.and]: Utils.ilike(
'vendor_bills',
'memo',
filter.memo,
),
};
}
if (filter.bill_dateRange) {
const [start, end] = filter.bill_dateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
bill_date: {
...where.bill_date,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
bill_date: {
...where.bill_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.subtotal_amountRange) {
const [start, end] = filter.subtotal_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
subtotal_amount: {
...where.subtotal_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
subtotal_amount: {
...where.subtotal_amount,
[Op.lte]: end,
},
};
}
}
if (filter.tax_amountRange) {
const [start, end] = filter.tax_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
tax_amount: {
...where.tax_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
tax_amount: {
...where.tax_amount,
[Op.lte]: end,
},
};
}
}
if (filter.total_amountRange) {
const [start, end] = filter.total_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
total_amount: {
...where.total_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
total_amount: {
...where.total_amount,
[Op.lte]: end,
},
};
}
}
if (filter.amount_paidRange) {
const [start, end] = filter.amount_paidRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
amount_paid: {
...where.amount_paid,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
amount_paid: {
...where.amount_paid,
[Op.lte]: end,
},
};
}
}
if (filter.amount_dueRange) {
const [start, end] = filter.amount_dueRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
amount_due: {
...where.amount_due,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
amount_due: {
...where.amount_due,
[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.vendor_bills.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(
'vendor_bills',
'bill_number',
query,
),
],
};
}
const records = await db.vendor_bills.findAll({
attributes: [ 'id', 'bill_number' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['bill_number', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.bill_number,
}));
}
};

View File

@ -0,0 +1,752 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Vendor_paymentsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const vendor_payments = await db.vendor_payments.create(
{
id: data.id || undefined,
amount: data.amount
||
null
,
currency_code: data.currency_code
||
null
,
paid_at: data.paid_at
||
null
,
method: data.method
||
null
,
status: data.status
||
null
,
reference: data.reference
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await vendor_payments.setTenant( data.tenant || null, {
transaction,
});
await vendor_payments.setVendor_bill( data.vendor_bill || null, {
transaction,
});
await vendor_payments.setVendor( data.vendor || null, {
transaction,
});
await vendor_payments.setRecorded_by( data.recorded_by || null, {
transaction,
});
await vendor_payments.setOrganizations( data.organizations || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.vendor_payments.getTableName(),
belongsToColumn: 'receipt_files',
belongsToId: vendor_payments.id,
},
data.receipt_files,
options,
);
return vendor_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 vendor_paymentsData = data.map((item, index) => ({
id: item.id || undefined,
amount: item.amount
||
null
,
currency_code: item.currency_code
||
null
,
paid_at: item.paid_at
||
null
,
method: item.method
||
null
,
status: item.status
||
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 vendor_payments = await db.vendor_payments.bulkCreate(vendor_paymentsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < vendor_payments.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.vendor_payments.getTableName(),
belongsToColumn: 'receipt_files',
belongsToId: vendor_payments[i].id,
},
data[i].receipt_files,
options,
);
}
return vendor_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 vendor_payments = await db.vendor_payments.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.amount !== undefined) updatePayload.amount = data.amount;
if (data.currency_code !== undefined) updatePayload.currency_code = data.currency_code;
if (data.paid_at !== undefined) updatePayload.paid_at = data.paid_at;
if (data.method !== undefined) updatePayload.method = data.method;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.reference !== undefined) updatePayload.reference = data.reference;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await vendor_payments.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await vendor_payments.setTenant(
data.tenant,
{ transaction }
);
}
if (data.vendor_bill !== undefined) {
await vendor_payments.setVendor_bill(
data.vendor_bill,
{ transaction }
);
}
if (data.vendor !== undefined) {
await vendor_payments.setVendor(
data.vendor,
{ transaction }
);
}
if (data.recorded_by !== undefined) {
await vendor_payments.setRecorded_by(
data.recorded_by,
{ transaction }
);
}
if (data.organizations !== undefined) {
await vendor_payments.setOrganizations(
data.organizations,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.vendor_payments.getTableName(),
belongsToColumn: 'receipt_files',
belongsToId: vendor_payments.id,
},
data.receipt_files,
options,
);
return vendor_payments;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const vendor_payments = await db.vendor_payments.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of vendor_payments) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of vendor_payments) {
await record.destroy({transaction});
}
});
return vendor_payments;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const vendor_payments = await db.vendor_payments.findByPk(id, options);
await vendor_payments.update({
deletedBy: currentUser.id
}, {
transaction,
});
await vendor_payments.destroy({
transaction
});
return vendor_payments;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const vendor_payments = await db.vendor_payments.findOne(
{ where },
{ transaction },
);
if (!vendor_payments) {
return vendor_payments;
}
const output = vendor_payments.get({plain: true});
output.tenant = await vendor_payments.getTenant({
transaction
});
output.vendor_bill = await vendor_payments.getVendor_bill({
transaction
});
output.vendor = await vendor_payments.getVendor({
transaction
});
output.receipt_files = await vendor_payments.getReceipt_files({
transaction
});
output.recorded_by = await vendor_payments.getRecorded_by({
transaction
});
output.organizations = await vendor_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.tenants,
as: 'tenant',
where: filter.tenant ? {
[Op.or]: [
{ id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.vendor_bills,
as: 'vendor_bill',
where: filter.vendor_bill ? {
[Op.or]: [
{ id: { [Op.in]: filter.vendor_bill.split('|').map(term => Utils.uuid(term)) } },
{
bill_number: {
[Op.or]: filter.vendor_bill.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.vendors,
as: 'vendor',
where: filter.vendor ? {
[Op.or]: [
{ id: { [Op.in]: filter.vendor.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.vendor.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'recorded_by',
where: filter.recorded_by ? {
[Op.or]: [
{ id: { [Op.in]: filter.recorded_by.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.recorded_by.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
{
model: db.file,
as: 'receipt_files',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.currency_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'vendor_payments',
'currency_code',
filter.currency_code,
),
};
}
if (filter.reference) {
where = {
...where,
[Op.and]: Utils.ilike(
'vendor_payments',
'reference',
filter.reference,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'vendor_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.vendor_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(
'vendor_payments',
'reference',
query,
),
],
};
}
const records = await db.vendor_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,753 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class VendorsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const vendors = await db.vendors.create(
{
id: data.id || undefined,
name: data.name
||
null
,
contact_name: data.contact_name
||
null
,
email: data.email
||
null
,
phone: data.phone
||
null
,
website: data.website
||
null
,
address_line1: data.address_line1
||
null
,
address_line2: data.address_line2
||
null
,
city: data.city
||
null
,
region: data.region
||
null
,
postal_code: data.postal_code
||
null
,
country: data.country
||
null
,
tax_number: data.tax_number
||
null
,
status: data.status
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await vendors.setTenant( data.tenant || null, {
transaction,
});
await vendors.setOrganizations( data.organizations || null, {
transaction,
});
return vendors;
}
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 vendorsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
contact_name: item.contact_name
||
null
,
email: item.email
||
null
,
phone: item.phone
||
null
,
website: item.website
||
null
,
address_line1: item.address_line1
||
null
,
address_line2: item.address_line2
||
null
,
city: item.city
||
null
,
region: item.region
||
null
,
postal_code: item.postal_code
||
null
,
country: item.country
||
null
,
tax_number: item.tax_number
||
null
,
status: item.status
||
null
,
notes: item.notes
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const vendors = await db.vendors.bulkCreate(vendorsData, { transaction });
// For each item created, replace relation files
return vendors;
}
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 vendors = await db.vendors.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.contact_name !== undefined) updatePayload.contact_name = data.contact_name;
if (data.email !== undefined) updatePayload.email = data.email;
if (data.phone !== undefined) updatePayload.phone = data.phone;
if (data.website !== undefined) updatePayload.website = data.website;
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.region !== undefined) updatePayload.region = data.region;
if (data.postal_code !== undefined) updatePayload.postal_code = data.postal_code;
if (data.country !== undefined) updatePayload.country = data.country;
if (data.tax_number !== undefined) updatePayload.tax_number = data.tax_number;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await vendors.update(updatePayload, {transaction});
if (data.tenant !== undefined) {
await vendors.setTenant(
data.tenant,
{ transaction }
);
}
if (data.organizations !== undefined) {
await vendors.setOrganizations(
data.organizations,
{ transaction }
);
}
return vendors;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const vendors = await db.vendors.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of vendors) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of vendors) {
await record.destroy({transaction});
}
});
return vendors;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const vendors = await db.vendors.findByPk(id, options);
await vendors.update({
deletedBy: currentUser.id
}, {
transaction,
});
await vendors.destroy({
transaction
});
return vendors;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const vendors = await db.vendors.findOne(
{ where },
{ transaction },
);
if (!vendors) {
return vendors;
}
const output = vendors.get({plain: true});
output.vendor_bills_vendor = await vendors.getVendor_bills_vendor({
transaction
});
output.vendor_payments_vendor = await vendors.getVendor_payments_vendor({
transaction
});
output.tenant = await vendors.getTenant({
transaction
});
output.organizations = await vendors.getOrganizations({
transaction
});
return output;
}
static async findAll(
filter,
globalAccess, options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userOrganizations = (user && user.organizations?.id) || null;
if (userOrganizations) {
if (options?.currentUser?.organizationsId) {
where.organizationsId = options.currentUser.organizationsId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.tenants,
as: 'tenant',
where: filter.tenant ? {
[Op.or]: [
{ id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.organizations,
as: 'organizations',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'vendors',
'name',
filter.name,
),
};
}
if (filter.contact_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'vendors',
'contact_name',
filter.contact_name,
),
};
}
if (filter.email) {
where = {
...where,
[Op.and]: Utils.ilike(
'vendors',
'email',
filter.email,
),
};
}
if (filter.phone) {
where = {
...where,
[Op.and]: Utils.ilike(
'vendors',
'phone',
filter.phone,
),
};
}
if (filter.website) {
where = {
...where,
[Op.and]: Utils.ilike(
'vendors',
'website',
filter.website,
),
};
}
if (filter.address_line1) {
where = {
...where,
[Op.and]: Utils.ilike(
'vendors',
'address_line1',
filter.address_line1,
),
};
}
if (filter.address_line2) {
where = {
...where,
[Op.and]: Utils.ilike(
'vendors',
'address_line2',
filter.address_line2,
),
};
}
if (filter.city) {
where = {
...where,
[Op.and]: Utils.ilike(
'vendors',
'city',
filter.city,
),
};
}
if (filter.region) {
where = {
...where,
[Op.and]: Utils.ilike(
'vendors',
'region',
filter.region,
),
};
}
if (filter.postal_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'vendors',
'postal_code',
filter.postal_code,
),
};
}
if (filter.country) {
where = {
...where,
[Op.and]: Utils.ilike(
'vendors',
'country',
filter.country,
),
};
}
if (filter.tax_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'vendors',
'tax_number',
filter.tax_number,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'vendors',
'notes',
filter.notes,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.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.vendors.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(
'vendors',
'name',
query,
),
],
};
}
const records = await db.vendors.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_multi_tenant_billing_ops_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,299 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const clients = sequelize.define(
'clients',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
type: {
type: DataTypes.ENUM,
values: [
"company",
"individual"
],
},
primary_contact_name: {
type: DataTypes.TEXT,
},
primary_email: {
type: DataTypes.TEXT,
},
primary_phone: {
type: DataTypes.TEXT,
},
website: {
type: DataTypes.TEXT,
},
billing_address_line1: {
type: DataTypes.TEXT,
},
billing_address_line2: {
type: DataTypes.TEXT,
},
billing_city: {
type: DataTypes.TEXT,
},
billing_region: {
type: DataTypes.TEXT,
},
billing_postal_code: {
type: DataTypes.TEXT,
},
billing_country: {
type: DataTypes.TEXT,
},
shipping_address_line1: {
type: DataTypes.TEXT,
},
shipping_address_line2: {
type: DataTypes.TEXT,
},
shipping_city: {
type: DataTypes.TEXT,
},
shipping_region: {
type: DataTypes.TEXT,
},
shipping_postal_code: {
type: DataTypes.TEXT,
},
shipping_country: {
type: DataTypes.TEXT,
},
tax_number: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"active",
"inactive"
],
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
clients.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.clients.hasMany(db.projects, {
as: 'projects_client',
foreignKey: {
name: 'clientId',
},
constraints: false,
});
db.clients.hasMany(db.estimates, {
as: 'estimates_client',
foreignKey: {
name: 'clientId',
},
constraints: false,
});
db.clients.hasMany(db.invoices, {
as: 'invoices_client',
foreignKey: {
name: 'clientId',
},
constraints: false,
});
db.clients.hasMany(db.payments, {
as: 'payments_client',
foreignKey: {
name: 'clientId',
},
constraints: false,
});
db.clients.hasMany(db.time_entries, {
as: 'time_entries_client',
foreignKey: {
name: 'clientId',
},
constraints: false,
});
//end loop
db.clients.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.clients.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.clients.belongsTo(db.users, {
as: 'createdBy',
});
db.clients.belongsTo(db.users, {
as: 'updatedBy',
});
};
return clients;
};

View File

@ -0,0 +1,176 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const estimate_line_items = sequelize.define(
'estimate_line_items',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
description: {
type: DataTypes.TEXT,
},
quantity: {
type: DataTypes.DECIMAL,
},
unit_price: {
type: DataTypes.DECIMAL,
},
unit_type: {
type: DataTypes.ENUM,
values: [
"each",
"hour",
"day",
"week",
"month"
],
},
tax_rate: {
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.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
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,242 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const 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",
"cancelled"
],
},
issue_date: {
type: DataTypes.DATE,
},
valid_until: {
type: DataTypes.DATE,
},
currency_code: {
type: DataTypes.TEXT,
},
subtotal_amount: {
type: DataTypes.DECIMAL,
},
discount_amount: {
type: DataTypes.DECIMAL,
},
tax_amount: {
type: DataTypes.DECIMAL,
},
total_amount: {
type: DataTypes.DECIMAL,
},
notes: {
type: DataTypes.TEXT,
},
terms: {
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,
});
db.estimates.hasMany(db.invoices, {
as: 'invoices_estimate',
foreignKey: {
name: 'estimateId',
},
constraints: false,
});
//end loop
db.estimates.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.estimates.belongsTo(db.clients, {
as: 'client',
foreignKey: {
name: 'clientId',
},
constraints: false,
});
db.estimates.belongsTo(db.projects, {
as: 'project',
foreignKey: {
name: 'projectId',
},
constraints: false,
});
db.estimates.belongsTo(db.users, {
as: 'issued_by',
foreignKey: {
name: 'issued_byId',
},
constraints: false,
});
db.estimates.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.estimates.hasMany(db.file, {
as: 'attachments',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.estimates.getTableName(),
belongsToColumn: 'attachments',
},
});
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,230 @@
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 freelancer_assignments = sequelize.define(
'freelancer_assignments',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
role_on_project: {
type: DataTypes.ENUM,
values: [
"designer",
"developer",
"writer",
"qa",
"pm",
"other"
],
},
rate_type: {
type: DataTypes.ENUM,
values: [
"hourly",
"fixed"
],
},
rate: {
type: DataTypes.DECIMAL,
},
start_at: {
type: DataTypes.DATE,
},
end_at: {
type: DataTypes.DATE,
},
status: {
type: DataTypes.ENUM,
values: [
"planned",
"active",
"paused",
"completed",
"cancelled"
],
},
estimated_hours: {
type: DataTypes.DECIMAL,
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
freelancer_assignments.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.freelancer_assignments.hasMany(db.freelancer_payments, {
as: 'freelancer_payments_freelancer_assignment',
foreignKey: {
name: 'freelancer_assignmentId',
},
constraints: false,
});
db.freelancer_assignments.hasMany(db.time_entries, {
as: 'time_entries_freelancer_assignment',
foreignKey: {
name: 'freelancer_assignmentId',
},
constraints: false,
});
//end loop
db.freelancer_assignments.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.freelancer_assignments.belongsTo(db.freelancers, {
as: 'freelancer',
foreignKey: {
name: 'freelancerId',
},
constraints: false,
});
db.freelancer_assignments.belongsTo(db.projects, {
as: 'project',
foreignKey: {
name: 'projectId',
},
constraints: false,
});
db.freelancer_assignments.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.freelancer_assignments.belongsTo(db.users, {
as: 'createdBy',
});
db.freelancer_assignments.belongsTo(db.users, {
as: 'updatedBy',
});
};
return freelancer_assignments;
};

View File

@ -0,0 +1,228 @@
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 freelancer_payments = sequelize.define(
'freelancer_payments',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
amount: {
type: DataTypes.DECIMAL,
},
currency_code: {
type: DataTypes.TEXT,
},
paid_at: {
type: DataTypes.DATE,
},
method: {
type: DataTypes.ENUM,
values: [
"bank_transfer",
"card",
"cash",
"check",
"paypal",
"other"
],
},
status: {
type: DataTypes.ENUM,
values: [
"pending",
"succeeded",
"failed",
"voided"
],
},
reference: {
type: DataTypes.TEXT,
},
hours_billed: {
type: DataTypes.DECIMAL,
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
freelancer_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.freelancer_payments.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.freelancer_payments.belongsTo(db.freelancers, {
as: 'freelancer',
foreignKey: {
name: 'freelancerId',
},
constraints: false,
});
db.freelancer_payments.belongsTo(db.freelancer_assignments, {
as: 'freelancer_assignment',
foreignKey: {
name: 'freelancer_assignmentId',
},
constraints: false,
});
db.freelancer_payments.belongsTo(db.projects, {
as: 'project',
foreignKey: {
name: 'projectId',
},
constraints: false,
});
db.freelancer_payments.belongsTo(db.users, {
as: 'recorded_by',
foreignKey: {
name: 'recorded_byId',
},
constraints: false,
});
db.freelancer_payments.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.freelancer_payments.hasMany(db.file, {
as: 'receipt_files',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.freelancer_payments.getTableName(),
belongsToColumn: 'receipt_files',
},
});
db.freelancer_payments.belongsTo(db.users, {
as: 'createdBy',
});
db.freelancer_payments.belongsTo(db.users, {
as: 'updatedBy',
});
};
return freelancer_payments;
};

View File

@ -0,0 +1,208 @@
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 freelancers = sequelize.define(
'freelancers',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
email: {
type: DataTypes.TEXT,
},
phone: {
type: DataTypes.TEXT,
},
website: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"active",
"inactive"
],
},
default_rate_type: {
type: DataTypes.ENUM,
values: [
"hourly",
"fixed"
],
},
default_rate: {
type: DataTypes.DECIMAL,
},
currency_code: {
type: DataTypes.TEXT,
},
skills: {
type: DataTypes.TEXT,
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
freelancers.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.freelancers.hasMany(db.freelancer_assignments, {
as: 'freelancer_assignments_freelancer',
foreignKey: {
name: 'freelancerId',
},
constraints: false,
});
db.freelancers.hasMany(db.freelancer_payments, {
as: 'freelancer_payments_freelancer',
foreignKey: {
name: 'freelancerId',
},
constraints: false,
});
//end loop
db.freelancers.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.freelancers.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.freelancers.hasMany(db.file, {
as: 'contracts_files',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.freelancers.getTableName(),
belongsToColumn: 'contracts_files',
},
});
db.freelancers.belongsTo(db.users, {
as: 'createdBy',
});
db.freelancers.belongsTo(db.users, {
as: 'updatedBy',
});
};
return freelancers;
};

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,176 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const invoice_line_items = sequelize.define(
'invoice_line_items',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
description: {
type: DataTypes.TEXT,
},
quantity: {
type: DataTypes.DECIMAL,
},
unit_price: {
type: DataTypes.DECIMAL,
},
unit_type: {
type: DataTypes.ENUM,
values: [
"each",
"hour",
"day",
"week",
"month"
],
},
tax_rate: {
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.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
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,271 @@
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",
"partially_paid",
"paid",
"overdue",
"void"
],
},
issue_date: {
type: DataTypes.DATE,
},
due_date: {
type: DataTypes.DATE,
},
currency_code: {
type: DataTypes.TEXT,
},
subtotal_amount: {
type: DataTypes.DECIMAL,
},
discount_amount: {
type: DataTypes.DECIMAL,
},
tax_amount: {
type: DataTypes.DECIMAL,
},
total_amount: {
type: DataTypes.DECIMAL,
},
amount_paid: {
type: DataTypes.DECIMAL,
},
amount_due: {
type: DataTypes.DECIMAL,
},
purchase_order_number: {
type: DataTypes.TEXT,
},
notes: {
type: DataTypes.TEXT,
},
terms: {
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.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.invoices.belongsTo(db.clients, {
as: 'client',
foreignKey: {
name: 'clientId',
},
constraints: false,
});
db.invoices.belongsTo(db.projects, {
as: 'project',
foreignKey: {
name: 'projectId',
},
constraints: false,
});
db.invoices.belongsTo(db.estimates, {
as: 'estimate',
foreignKey: {
name: 'estimateId',
},
constraints: false,
});
db.invoices.belongsTo(db.users, {
as: 'issued_by',
foreignKey: {
name: 'issued_byId',
},
constraints: false,
});
db.invoices.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.invoices.hasMany(db.file, {
as: 'attachments',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.invoices.getTableName(),
belongsToColumn: 'attachments',
},
});
db.invoices.belongsTo(db.users, {
as: 'createdBy',
});
db.invoices.belongsTo(db.users, {
as: 'updatedBy',
});
};
return invoices;
};

View File

@ -0,0 +1,221 @@
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.tenants, {
as: 'tenants_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.clients, {
as: 'clients_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.projects, {
as: 'projects_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.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.vendors, {
as: 'vendors_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.vendor_bills, {
as: 'vendor_bills_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.vendor_bill_line_items, {
as: 'vendor_bill_line_items_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.vendor_payments, {
as: 'vendor_payments_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.freelancers, {
as: 'freelancers_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.freelancer_assignments, {
as: 'freelancer_assignments_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.freelancer_payments, {
as: 'freelancer_payments_organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.organizations.hasMany(db.time_entries, {
as: 'time_entries_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,216 @@
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,
},
currency_code: {
type: DataTypes.TEXT,
},
paid_at: {
type: DataTypes.DATE,
},
method: {
type: DataTypes.ENUM,
values: [
"bank_transfer",
"card",
"cash",
"check",
"paypal",
"stripe",
"other"
],
},
status: {
type: DataTypes.ENUM,
values: [
"pending",
"succeeded",
"failed",
"refunded"
],
},
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.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.payments.belongsTo(db.invoices, {
as: 'invoice',
foreignKey: {
name: 'invoiceId',
},
constraints: false,
});
db.payments.belongsTo(db.clients, {
as: 'client',
foreignKey: {
name: 'clientId',
},
constraints: false,
});
db.payments.belongsTo(db.users, {
as: 'recorded_by',
foreignKey: {
name: 'recorded_byId',
},
constraints: false,
});
db.payments.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.payments.hasMany(db.file, {
as: 'receipt_files',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.payments.getTableName(),
belongsToColumn: 'receipt_files',
},
});
db.payments.belongsTo(db.users, {
as: 'createdBy',
});
db.payments.belongsTo(db.users, {
as: 'updatedBy',
});
};
return payments;
};

View File

@ -0,0 +1,85 @@
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,254 @@
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 projects = sequelize.define(
'projects',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
code: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"planned",
"active",
"on_hold",
"completed",
"cancelled"
],
},
start_at: {
type: DataTypes.DATE,
},
end_at: {
type: DataTypes.DATE,
},
budget_amount: {
type: DataTypes.DECIMAL,
},
billing_method: {
type: DataTypes.ENUM,
values: [
"fixed_fee",
"time_and_materials",
"retainer"
],
},
billable: {
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,
},
);
projects.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.projects.hasMany(db.estimates, {
as: 'estimates_project',
foreignKey: {
name: 'projectId',
},
constraints: false,
});
db.projects.hasMany(db.invoices, {
as: 'invoices_project',
foreignKey: {
name: 'projectId',
},
constraints: false,
});
db.projects.hasMany(db.vendor_bills, {
as: 'vendor_bills_project',
foreignKey: {
name: 'projectId',
},
constraints: false,
});
db.projects.hasMany(db.freelancer_assignments, {
as: 'freelancer_assignments_project',
foreignKey: {
name: 'projectId',
},
constraints: false,
});
db.projects.hasMany(db.freelancer_payments, {
as: 'freelancer_payments_project',
foreignKey: {
name: 'projectId',
},
constraints: false,
});
db.projects.hasMany(db.time_entries, {
as: 'time_entries_project',
foreignKey: {
name: 'projectId',
},
constraints: false,
});
//end loop
db.projects.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.projects.belongsTo(db.clients, {
as: 'client',
foreignKey: {
name: 'clientId',
},
constraints: false,
});
db.projects.belongsTo(db.users, {
as: 'owner',
foreignKey: {
name: 'ownerId',
},
constraints: false,
});
db.projects.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.projects.belongsTo(db.users, {
as: 'createdBy',
});
db.projects.belongsTo(db.users, {
as: 'updatedBy',
});
};
return projects;
};

View File

@ -0,0 +1,128 @@
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,347 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const tenants = sequelize.define(
'tenants',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
slug: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"active",
"suspended",
"disabled"
],
},
primary_email: {
type: DataTypes.TEXT,
},
primary_phone: {
type: DataTypes.TEXT,
},
website: {
type: DataTypes.TEXT,
},
timezone: {
type: DataTypes.TEXT,
},
currency_code: {
type: DataTypes.TEXT,
},
address_line1: {
type: DataTypes.TEXT,
},
address_line2: {
type: DataTypes.TEXT,
},
city: {
type: DataTypes.TEXT,
},
region: {
type: DataTypes.TEXT,
},
postal_code: {
type: DataTypes.TEXT,
},
country: {
type: DataTypes.TEXT,
},
tax_number: {
type: DataTypes.TEXT,
},
trial_ends_on: {
type: DataTypes.DATE,
},
subscription_ends_on: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
tenants.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.tenants.hasMany(db.clients, {
as: 'clients_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.projects, {
as: 'projects_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.estimates, {
as: 'estimates_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.estimate_line_items, {
as: 'estimate_line_items_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.invoices, {
as: 'invoices_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.invoice_line_items, {
as: 'invoice_line_items_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.payments, {
as: 'payments_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.vendors, {
as: 'vendors_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.vendor_bills, {
as: 'vendor_bills_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.vendor_bill_line_items, {
as: 'vendor_bill_line_items_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.vendor_payments, {
as: 'vendor_payments_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.freelancers, {
as: 'freelancers_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.freelancer_assignments, {
as: 'freelancer_assignments_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.freelancer_payments, {
as: 'freelancer_payments_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.tenants.hasMany(db.time_entries, {
as: 'time_entries_tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
//end loop
db.tenants.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.tenants.hasMany(db.file, {
as: 'logo',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.tenants.getTableName(),
belongsToColumn: 'logo',
},
});
db.tenants.belongsTo(db.users, {
as: 'createdBy',
});
db.tenants.belongsTo(db.users, {
as: 'updatedBy',
});
};
return tenants;
};

View File

@ -0,0 +1,200 @@
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 time_entries = sequelize.define(
'time_entries',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
started_at: {
type: DataTypes.DATE,
},
ended_at: {
type: DataTypes.DATE,
},
duration_hours: {
type: DataTypes.DECIMAL,
},
billable: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
bill_rate: {
type: DataTypes.DECIMAL,
},
cost_rate: {
type: DataTypes.DECIMAL,
},
description: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"draft",
"approved",
"invoiced",
"rejected"
],
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
time_entries.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.time_entries.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.time_entries.belongsTo(db.projects, {
as: 'project',
foreignKey: {
name: 'projectId',
},
constraints: false,
});
db.time_entries.belongsTo(db.clients, {
as: 'client',
foreignKey: {
name: 'clientId',
},
constraints: false,
});
db.time_entries.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.time_entries.belongsTo(db.freelancer_assignments, {
as: 'freelancer_assignment',
foreignKey: {
name: 'freelancer_assignmentId',
},
constraints: false,
});
db.time_entries.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.time_entries.belongsTo(db.users, {
as: 'createdBy',
});
db.time_entries.belongsTo(db.users, {
as: 'updatedBy',
});
};
return time_entries;
};

View File

@ -0,0 +1,315 @@
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.projects, {
as: 'projects_owner',
foreignKey: {
name: 'ownerId',
},
constraints: false,
});
db.users.hasMany(db.estimates, {
as: 'estimates_issued_by',
foreignKey: {
name: 'issued_byId',
},
constraints: false,
});
db.users.hasMany(db.invoices, {
as: 'invoices_issued_by',
foreignKey: {
name: 'issued_byId',
},
constraints: false,
});
db.users.hasMany(db.payments, {
as: 'payments_recorded_by',
foreignKey: {
name: 'recorded_byId',
},
constraints: false,
});
db.users.hasMany(db.vendor_bills, {
as: 'vendor_bills_entered_by',
foreignKey: {
name: 'entered_byId',
},
constraints: false,
});
db.users.hasMany(db.vendor_payments, {
as: 'vendor_payments_recorded_by',
foreignKey: {
name: 'recorded_byId',
},
constraints: false,
});
db.users.hasMany(db.freelancer_payments, {
as: 'freelancer_payments_recorded_by',
foreignKey: {
name: 'recorded_byId',
},
constraints: false,
});
db.users.hasMany(db.time_entries, {
as: 'time_entries_user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
//end loop
db.users.belongsTo(db.roles, {
as: 'app_role',
foreignKey: {
name: 'app_roleId',
},
constraints: false,
});
db.users.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.users.hasMany(db.file, {
as: 'avatar',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.users.getTableName(),
belongsToColumn: 'avatar',
},
});
db.users.belongsTo(db.users, {
as: 'createdBy',
});
db.users.belongsTo(db.users, {
as: 'updatedBy',
});
};
users.beforeCreate((users, options) => {
users = trimStringFields(users);
if (users.provider !== providers.LOCAL && Object.values(providers).indexOf(users.provider) > -1) {
users.emailVerified = true;
if (!users.password) {
const password = crypto
.randomBytes(20)
.toString('hex');
const hashedPassword = bcrypt.hashSync(
password,
config.bcrypt.saltRounds,
);
users.password = hashedPassword
}
}
});
users.beforeUpdate((users, options) => {
users = trimStringFields(users);
});
return users;
};
function trimStringFields(users) {
users.email = users.email.trim();
users.firstName = users.firstName
? users.firstName.trim()
: null;
users.lastName = users.lastName
? users.lastName.trim()
: null;
return users;
}

View File

@ -0,0 +1,176 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const vendor_bill_line_items = sequelize.define(
'vendor_bill_line_items',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
description: {
type: DataTypes.TEXT,
},
quantity: {
type: DataTypes.DECIMAL,
},
unit_cost: {
type: DataTypes.DECIMAL,
},
unit_type: {
type: DataTypes.ENUM,
values: [
"each",
"hour",
"day",
"week",
"month"
],
},
tax_rate: {
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,
},
);
vendor_bill_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.vendor_bill_line_items.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.vendor_bill_line_items.belongsTo(db.vendor_bills, {
as: 'vendor_bill',
foreignKey: {
name: 'vendor_billId',
},
constraints: false,
});
db.vendor_bill_line_items.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.vendor_bill_line_items.belongsTo(db.users, {
as: 'createdBy',
});
db.vendor_bill_line_items.belongsTo(db.users, {
as: 'updatedBy',
});
};
return vendor_bill_line_items;
};

View File

@ -0,0 +1,242 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const vendor_bills = sequelize.define(
'vendor_bills',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
bill_number: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"draft",
"received",
"approved",
"partially_paid",
"paid",
"void"
],
},
bill_date: {
type: DataTypes.DATE,
},
due_date: {
type: DataTypes.DATE,
},
currency_code: {
type: DataTypes.TEXT,
},
subtotal_amount: {
type: DataTypes.DECIMAL,
},
tax_amount: {
type: DataTypes.DECIMAL,
},
total_amount: {
type: DataTypes.DECIMAL,
},
amount_paid: {
type: DataTypes.DECIMAL,
},
amount_due: {
type: DataTypes.DECIMAL,
},
memo: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
vendor_bills.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.vendor_bills.hasMany(db.vendor_bill_line_items, {
as: 'vendor_bill_line_items_vendor_bill',
foreignKey: {
name: 'vendor_billId',
},
constraints: false,
});
db.vendor_bills.hasMany(db.vendor_payments, {
as: 'vendor_payments_vendor_bill',
foreignKey: {
name: 'vendor_billId',
},
constraints: false,
});
//end loop
db.vendor_bills.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.vendor_bills.belongsTo(db.vendors, {
as: 'vendor',
foreignKey: {
name: 'vendorId',
},
constraints: false,
});
db.vendor_bills.belongsTo(db.projects, {
as: 'project',
foreignKey: {
name: 'projectId',
},
constraints: false,
});
db.vendor_bills.belongsTo(db.users, {
as: 'entered_by',
foreignKey: {
name: 'entered_byId',
},
constraints: false,
});
db.vendor_bills.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.vendor_bills.hasMany(db.file, {
as: 'attachments',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.vendor_bills.getTableName(),
belongsToColumn: 'attachments',
},
});
db.vendor_bills.belongsTo(db.users, {
as: 'createdBy',
});
db.vendor_bills.belongsTo(db.users, {
as: 'updatedBy',
});
};
return vendor_bills;
};

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 vendor_payments = sequelize.define(
'vendor_payments',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
amount: {
type: DataTypes.DECIMAL,
},
currency_code: {
type: DataTypes.TEXT,
},
paid_at: {
type: DataTypes.DATE,
},
method: {
type: DataTypes.ENUM,
values: [
"bank_transfer",
"card",
"cash",
"check",
"paypal",
"other"
],
},
status: {
type: DataTypes.ENUM,
values: [
"pending",
"succeeded",
"failed",
"voided"
],
},
reference: {
type: DataTypes.TEXT,
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
vendor_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.vendor_payments.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.vendor_payments.belongsTo(db.vendor_bills, {
as: 'vendor_bill',
foreignKey: {
name: 'vendor_billId',
},
constraints: false,
});
db.vendor_payments.belongsTo(db.vendors, {
as: 'vendor',
foreignKey: {
name: 'vendorId',
},
constraints: false,
});
db.vendor_payments.belongsTo(db.users, {
as: 'recorded_by',
foreignKey: {
name: 'recorded_byId',
},
constraints: false,
});
db.vendor_payments.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.vendor_payments.hasMany(db.file, {
as: 'receipt_files',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.vendor_payments.getTableName(),
belongsToColumn: 'receipt_files',
},
});
db.vendor_payments.belongsTo(db.users, {
as: 'createdBy',
});
db.vendor_payments.belongsTo(db.users, {
as: 'updatedBy',
});
};
return vendor_payments;
};

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 vendors = sequelize.define(
'vendors',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
contact_name: {
type: DataTypes.TEXT,
},
email: {
type: DataTypes.TEXT,
},
phone: {
type: DataTypes.TEXT,
},
website: {
type: DataTypes.TEXT,
},
address_line1: {
type: DataTypes.TEXT,
},
address_line2: {
type: DataTypes.TEXT,
},
city: {
type: DataTypes.TEXT,
},
region: {
type: DataTypes.TEXT,
},
postal_code: {
type: DataTypes.TEXT,
},
country: {
type: DataTypes.TEXT,
},
tax_number: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"active",
"inactive"
],
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
vendors.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.vendors.hasMany(db.vendor_bills, {
as: 'vendor_bills_vendor',
foreignKey: {
name: 'vendorId',
},
constraints: false,
});
db.vendors.hasMany(db.vendor_payments, {
as: 'vendor_payments_vendor',
foreignKey: {
name: 'vendorId',
},
constraints: false,
});
//end loop
db.vendors.belongsTo(db.tenants, {
as: 'tenant',
foreignKey: {
name: 'tenantId',
},
constraints: false,
});
db.vendors.belongsTo(db.organizations, {
as: 'organizations',
foreignKey: {
name: 'organizationsId',
},
constraints: false,
});
db.vendors.belongsTo(db.users, {
as: 'createdBy',
});
db.vendors.belongsTo(db.users, {
as: 'updatedBy',
});
};
return vendors;
};

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

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

@ -0,0 +1,213 @@
const express = require('express');
const cors = require('cors');
const app = express();
const passport = require('passport');
const path = require('path');
const fs = require('fs');
const bodyParser = require('body-parser');
const db = require('./db/models');
const config = require('./config');
const swaggerUI = require('swagger-ui-express');
const swaggerJsDoc = require('swagger-jsdoc');
const authRoutes = require('./routes/auth');
const fileRoutes = require('./routes/file');
const searchRoutes = require('./routes/search');
const sqlRoutes = require('./routes/sql');
const pexelsRoutes = require('./routes/pexels');
const organizationForAuthRoutes = require('./routes/organizationLogin');
const openaiRoutes = require('./routes/openai');
const usersRoutes = require('./routes/users');
const rolesRoutes = require('./routes/roles');
const permissionsRoutes = require('./routes/permissions');
const organizationsRoutes = require('./routes/organizations');
const tenantsRoutes = require('./routes/tenants');
const clientsRoutes = require('./routes/clients');
const projectsRoutes = require('./routes/projects');
const estimatesRoutes = require('./routes/estimates');
const estimate_line_itemsRoutes = require('./routes/estimate_line_items');
const invoicesRoutes = require('./routes/invoices');
const invoice_line_itemsRoutes = require('./routes/invoice_line_items');
const paymentsRoutes = require('./routes/payments');
const vendorsRoutes = require('./routes/vendors');
const vendor_billsRoutes = require('./routes/vendor_bills');
const vendor_bill_line_itemsRoutes = require('./routes/vendor_bill_line_items');
const vendor_paymentsRoutes = require('./routes/vendor_payments');
const freelancersRoutes = require('./routes/freelancers');
const freelancer_assignmentsRoutes = require('./routes/freelancer_assignments');
const freelancer_paymentsRoutes = require('./routes/freelancer_payments');
const time_entriesRoutes = require('./routes/time_entries');
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: "Multi-tenant Billing Ops SaaS",
description: "Multi-tenant Billing Ops 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/tenants', passport.authenticate('jwt', {session: false}), tenantsRoutes);
app.use('/api/clients', passport.authenticate('jwt', {session: false}), clientsRoutes);
app.use('/api/projects', passport.authenticate('jwt', {session: false}), projectsRoutes);
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/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/vendors', passport.authenticate('jwt', {session: false}), vendorsRoutes);
app.use('/api/vendor_bills', passport.authenticate('jwt', {session: false}), vendor_billsRoutes);
app.use('/api/vendor_bill_line_items', passport.authenticate('jwt', {session: false}), vendor_bill_line_itemsRoutes);
app.use('/api/vendor_payments', passport.authenticate('jwt', {session: false}), vendor_paymentsRoutes);
app.use('/api/freelancers', passport.authenticate('jwt', {session: false}), freelancersRoutes);
app.use('/api/freelancer_assignments', passport.authenticate('jwt', {session: false}), freelancer_assignmentsRoutes);
app.use('/api/freelancer_payments', passport.authenticate('jwt', {session: false}), freelancer_paymentsRoutes);
app.use('/api/time_entries', passport.authenticate('jwt', {session: false}), time_entriesRoutes);
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,496 @@
const express = require('express');
const ClientsService = require('../services/clients');
const ClientsDBApi = require('../db/api/clients');
const wrapAsync = require('../helpers').wrapAsync;
const config = require('../config');
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('clients'));
/**
* @swagger
* components:
* schemas:
* Clients:
* type: object
* properties:
* name:
* type: string
* default: name
* primary_contact_name:
* type: string
* default: primary_contact_name
* primary_email:
* type: string
* default: primary_email
* primary_phone:
* type: string
* default: primary_phone
* website:
* type: string
* default: website
* billing_address_line1:
* type: string
* default: billing_address_line1
* billing_address_line2:
* type: string
* default: billing_address_line2
* billing_city:
* type: string
* default: billing_city
* billing_region:
* type: string
* default: billing_region
* billing_postal_code:
* type: string
* default: billing_postal_code
* billing_country:
* type: string
* default: billing_country
* shipping_address_line1:
* type: string
* default: shipping_address_line1
* shipping_address_line2:
* type: string
* default: shipping_address_line2
* shipping_city:
* type: string
* default: shipping_city
* shipping_region:
* type: string
* default: shipping_region
* shipping_postal_code:
* type: string
* default: shipping_postal_code
* shipping_country:
* type: string
* default: shipping_country
* tax_number:
* type: string
* default: tax_number
* notes:
* type: string
* default: notes
*
*
*/
/**
* @swagger
* tags:
* name: Clients
* description: The Clients managing API
*/
/**
* @swagger
* /api/clients:
* post:
* security:
* - bearerAuth: []
* tags: [Clients]
* summary: Add new item
* description: Add new item
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Clients"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Clients"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*/
router.post('/', wrapAsync(async (req, res) => {
const referer = req.headers.referer || `${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await ClientsService.create(req.body.data, req.currentUser, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/budgets/bulk-import:
* post:
* security:
* - bearerAuth: []
* tags: [Clients]
* summary: Bulk import items
* description: Bulk import items
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* data:
* description: Data of the updated items
* type: array
* items:
* $ref: "#/components/schemas/Clients"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Clients"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 405:
* description: Invalid input data
* 500:
* description: Some server error
*
*/
router.post('/bulk-import', wrapAsync(async (req, res) => {
const referer = req.headers.referer || `${req.protocol}://${req.hostname}${req.originalUrl}`;
const link = new URL(referer);
await ClientsService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/clients/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Clients]
* summary: Update the data of the selected item
* description: Update the data of the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to update
* required: true
* schema:
* type: string
* requestBody:
* description: Set new item data
* required: true
* content:
* application/json:
* schema:
* properties:
* id:
* description: ID of the updated item
* type: string
* data:
* description: Data of the updated item
* type: object
* $ref: "#/components/schemas/Clients"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Clients"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.put('/:id', wrapAsync(async (req, res) => {
await ClientsService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/clients/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Clients]
* summary: Delete the selected item
* description: Delete the selected item
* parameters:
* - in: path
* name: id
* description: Item ID to delete
* required: true
* schema:
* type: string
* responses:
* 200:
* description: The item was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Clients"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.delete('/:id', wrapAsync(async (req, res) => {
await ClientsService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/clients/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Clients]
* summary: Delete the selected item list
* description: Delete the selected item list
* requestBody:
* required: true
* content:
* application/json:
* schema:
* properties:
* ids:
* description: IDs of the updated items
* type: array
* responses:
* 200:
* description: The items was successfully deleted
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Clients"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await ClientsService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/clients:
* get:
* security:
* - bearerAuth: []
* tags: [Clients]
* summary: Get all clients
* description: Get all clients
* responses:
* 200:
* description: Clients list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Clients"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/', wrapAsync(async (req, res) => {
const filetype = req.query.filetype
const globalAccess = req.currentUser.app_role.globalAccess;
const currentUser = req.currentUser;
const payload = await ClientsDBApi.findAll(
req.query, globalAccess, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','name','primary_contact_name','primary_email','primary_phone','website','billing_address_line1','billing_address_line2','billing_city','billing_region','billing_postal_code','billing_country','shipping_address_line1','shipping_address_line2','shipping_city','shipping_region','shipping_postal_code','shipping_country','tax_number','notes',
];
const opts = { fields };
try {
const csv = parse(payload.rows, opts);
res.status(200).attachment(csv);
res.send(csv)
} catch (err) {
console.error(err);
}
} else {
res.status(200).send(payload);
}
}));
/**
* @swagger
* /api/clients/count:
* get:
* security:
* - bearerAuth: []
* tags: [Clients]
* summary: Count all clients
* description: Count all clients
* responses:
* 200:
* description: Clients count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Clients"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/count', wrapAsync(async (req, res) => {
const globalAccess = req.currentUser.app_role.globalAccess;
const currentUser = req.currentUser;
const payload = await ClientsDBApi.findAll(
req.query,
globalAccess,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/clients/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Clients]
* summary: Find all clients that match search criteria
* description: Find all clients that match search criteria
* responses:
* 200:
* description: Clients list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Clients"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const globalAccess = req.currentUser.app_role.globalAccess;
const organizationId = req.currentUser.organization?.id
const payload = await ClientsDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
globalAccess, organizationId,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/clients/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Clients]
* summary: Get selected item
* description: Get selected item
* parameters:
* - in: path
* name: id
* description: ID of item to get
* required: true
* schema:
* type: string
* responses:
* 200:
* description: Selected item successfully received
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Clients"
* 400:
* description: Invalid ID supplied
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Item not found
* 500:
* description: Some server error
*/
router.get('/:id', wrapAsync(async (req, res) => {
const payload = await ClientsDBApi.findBy(
{ id: req.params.id },
);
res.status(200).send(payload);
}));
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

View File

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,104 @@
const express = require('express');
const router = express.Router();
const { pexelsKey, pexelsQuery } = require('../config');
const fetch = require('node-fetch');
const KEY = pexelsKey;
router.get('/image', async (req, res) => {
const headers = {
Authorization: `${KEY}`,
};
const query = pexelsQuery || 'nature';
const orientation = 'portrait';
const perPage = 1;
const url = `https://api.pexels.com/v1/search?query=${query}&orientation=${orientation}&per_page=${perPage}&page=1`;
try {
const response = await fetch(url, { headers });
const data = await response.json();
res.status(200).json(data.photos[0]);
} catch (error) {
res.status(200).json({ error: 'Failed to fetch image' });
}
});
router.get('/video', async (req, res) => {
const headers = {
Authorization: `${KEY}`,
};
const query = pexelsQuery || 'nature';
const orientation = 'portrait';
const perPage = 1;
const url = `https://api.pexels.com/videos/search?query=${query}&orientation=${orientation}&per_page=${perPage}&page=1`;
try {
const response = await fetch(url, { headers });
const data = await response.json();
res.status(200).json(data.videos[0]);
} catch (error) {
res.status(200).json({ error: 'Failed to fetch video' });
}
});
router.get('/multiple-images', async (req, res) => {
const headers = {
Authorization: `${KEY}`,
};
const queries = req.query.queries
? req.query.queries.split(',')
: ['home', 'apple', 'pizza', 'mountains', 'cat'];
const orientation = 'square';
const perPage = 1;
const fallbackImage = {
src: 'https://images.pexels.com/photos/8199252/pexels-photo-8199252.jpeg',
photographer: 'Yan Krukau',
photographer_url: 'https://www.pexels.com/@yankrukov',
};
const fetchFallbackImage = async () => {
try {
const response = await fetch('https://picsum.photos/600');
return {
src: response.url,
photographer: 'Random Picsum',
photographer_url: 'https://picsum.photos/',
};
} catch (error) {
return fallbackImage;
}
};
const fetchImage = async (query) => {
const url = `https://api.pexels.com/v1/search?query=${query}&orientation=${orientation}&per_page=${perPage}&page=1`;
const response = await fetch(url, { headers });
const data = await response.json();
return data.photos[0] || null;
};
const imagePromises = queries.map((query) => fetchImage(query));
const imagesResults = await Promise.allSettled(imagePromises);
const formattedImages = await Promise.all(imagesResults.map(async (result) => {
if (result.status === 'fulfilled' && result.value) {
const image = result.value;
return {
src: image.src?.original || fallbackImage.src,
photographer: image.photographer || fallbackImage.photographer,
photographer_url: image.photographer_url || fallbackImage.photographer_url,
};
} else {
const fallback = await fetchFallbackImage();
return {
src: fallback.src || '',
photographer: fallback.photographer || 'Unknown',
photographer_url: fallback.photographer_url || '',
};
}
}));
res.json(formattedImages);
});
module.exports = router;

View File

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

438
backend/src/routes/roles.js Normal file
View File

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

View File

@ -0,0 +1,56 @@
const express = require('express');
const SearchService = require('../services/search');
const config = require('../config');
const router = express.Router();
const { checkCrudPermissions } = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('search'));
/**
* @swagger
* path:
* /api/search:
* post:
* summary: Search
* description: Search results across multiple tables
* requestBody:
* content:
* application/json:
* schema:
* type: object
* properties:
* searchQuery:
* type: string
* required:
* - searchQuery
* responses:
* 200:
* description: Successful request
* 400:
* description: Invalid request
* 500:
* description: Internal server error
*/
router.post('/', async (req, res) => {
const { searchQuery , organizationId} = req.body;
const globalAccess = req.currentUser.app_role.globalAccess;
if (!searchQuery) {
return res.status(400).json({ error: 'Please enter a search query' });
}
try {
const foundMatches = await SearchService.search(searchQuery, req.currentUser , organizationId, globalAccess,);
res.json(foundMatches);
} catch (error) {
console.error('Internal Server Error', error);
res.status(500).json({ error: 'Internal Server Error' });
}
});
module.exports = router;

61
backend/src/routes/sql.js Normal file
View File

@ -0,0 +1,61 @@
const express = require('express');
const db = require('../db/models');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
/**
* @swagger
* /api/sql:
* post:
* security:
* - bearerAuth: []
* summary: Execute a SELECT-only SQL query
* description: Executes a read-only SQL query and returns rows.
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* sql:
* type: string
* required:
* - sql
* responses:
* 200:
* description: Query result
* 400:
* description: Invalid SQL
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 500:
* description: Internal server error
*/
router.post(
'/',
wrapAsync(async (req, res) => {
const { sql } = req.body;
if (typeof sql !== 'string' || !sql.trim()) {
return res.status(400).json({ error: 'SQL is required' });
}
const normalized = sql.trim().replace(/;+\s*$/, '');
if (!/^select\b/i.test(normalized)) {
return res.status(400).json({ error: 'Only SELECT statements are allowed' });
}
if (normalized.includes(';')) {
return res.status(400).json({ error: 'Only a single SELECT statement is allowed' });
}
const rows = await db.sequelize.query(normalized, {
type: db.Sequelize.QueryTypes.SELECT,
});
return res.status(200).json({ rows });
}),
);
module.exports = router;

View File

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

View File

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

451
backend/src/routes/users.js Normal file
View File

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

View File

@ -0,0 +1,459 @@
const express = require('express');
const Vendor_bill_line_itemsService = require('../services/vendor_bill_line_items');
const Vendor_bill_line_itemsDBApi = require('../db/api/vendor_bill_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('vendor_bill_line_items'));
/**
* @swagger
* components:
* schemas:
* Vendor_bill_line_items:
* type: object
* properties:
* name:
* type: string
* default: name
* description:
* type: string
* default: description
* sort_order:
* type: integer
* format: int64
* quantity:
* type: integer
* format: int64
* unit_cost:
* type: integer
* format: int64
* tax_rate:
* type: integer
* format: int64
* line_total:
* type: integer
* format: int64
*
*/
/**
* @swagger
* tags:
* name: Vendor_bill_line_items
* description: The Vendor_bill_line_items managing API
*/
/**
* @swagger
* /api/vendor_bill_line_items:
* post:
* security:
* - bearerAuth: []
* tags: [Vendor_bill_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/Vendor_bill_line_items"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Vendor_bill_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 Vendor_bill_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: [Vendor_bill_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/Vendor_bill_line_items"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Vendor_bill_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 Vendor_bill_line_itemsService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/vendor_bill_line_items/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Vendor_bill_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/Vendor_bill_line_items"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Vendor_bill_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 Vendor_bill_line_itemsService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/vendor_bill_line_items/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Vendor_bill_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/Vendor_bill_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 Vendor_bill_line_itemsService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/vendor_bill_line_items/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Vendor_bill_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/Vendor_bill_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 Vendor_bill_line_itemsService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/vendor_bill_line_items:
* get:
* security:
* - bearerAuth: []
* tags: [Vendor_bill_line_items]
* summary: Get all vendor_bill_line_items
* description: Get all vendor_bill_line_items
* responses:
* 200:
* description: Vendor_bill_line_items list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Vendor_bill_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 Vendor_bill_line_itemsDBApi.findAll(
req.query, globalAccess, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','name','description',
'sort_order',
'quantity','unit_cost','tax_rate','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/vendor_bill_line_items/count:
* get:
* security:
* - bearerAuth: []
* tags: [Vendor_bill_line_items]
* summary: Count all vendor_bill_line_items
* description: Count all vendor_bill_line_items
* responses:
* 200:
* description: Vendor_bill_line_items count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Vendor_bill_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 Vendor_bill_line_itemsDBApi.findAll(
req.query,
globalAccess,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/vendor_bill_line_items/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Vendor_bill_line_items]
* summary: Find all vendor_bill_line_items that match search criteria
* description: Find all vendor_bill_line_items that match search criteria
* responses:
* 200:
* description: Vendor_bill_line_items list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Vendor_bill_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 Vendor_bill_line_itemsDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
globalAccess, organizationId,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/vendor_bill_line_items/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Vendor_bill_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/Vendor_bill_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 Vendor_bill_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,462 @@
const express = require('express');
const Vendor_billsService = require('../services/vendor_bills');
const Vendor_billsDBApi = require('../db/api/vendor_bills');
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('vendor_bills'));
/**
* @swagger
* components:
* schemas:
* Vendor_bills:
* type: object
* properties:
* bill_number:
* type: string
* default: bill_number
* currency_code:
* type: string
* default: currency_code
* memo:
* type: string
* default: memo
* subtotal_amount:
* type: integer
* format: int64
* tax_amount:
* type: integer
* format: int64
* total_amount:
* type: integer
* format: int64
* amount_paid:
* type: integer
* format: int64
* amount_due:
* type: integer
* format: int64
*
*/
/**
* @swagger
* tags:
* name: Vendor_bills
* description: The Vendor_bills managing API
*/
/**
* @swagger
* /api/vendor_bills:
* post:
* security:
* - bearerAuth: []
* tags: [Vendor_bills]
* 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/Vendor_bills"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Vendor_bills"
* 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 Vendor_billsService.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: [Vendor_bills]
* 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/Vendor_bills"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Vendor_bills"
* 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 Vendor_billsService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/vendor_bills/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Vendor_bills]
* 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/Vendor_bills"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Vendor_bills"
* 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 Vendor_billsService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/vendor_bills/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Vendor_bills]
* 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/Vendor_bills"
* 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 Vendor_billsService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/vendor_bills/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Vendor_bills]
* 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/Vendor_bills"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await Vendor_billsService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/vendor_bills:
* get:
* security:
* - bearerAuth: []
* tags: [Vendor_bills]
* summary: Get all vendor_bills
* description: Get all vendor_bills
* responses:
* 200:
* description: Vendor_bills list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Vendor_bills"
* 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 Vendor_billsDBApi.findAll(
req.query, globalAccess, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','bill_number','currency_code','memo',
'subtotal_amount','tax_amount','total_amount','amount_paid','amount_due',
'bill_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/vendor_bills/count:
* get:
* security:
* - bearerAuth: []
* tags: [Vendor_bills]
* summary: Count all vendor_bills
* description: Count all vendor_bills
* responses:
* 200:
* description: Vendor_bills count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Vendor_bills"
* 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 Vendor_billsDBApi.findAll(
req.query,
globalAccess,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/vendor_bills/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Vendor_bills]
* summary: Find all vendor_bills that match search criteria
* description: Find all vendor_bills that match search criteria
* responses:
* 200:
* description: Vendor_bills list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Vendor_bills"
* 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 Vendor_billsDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
globalAccess, organizationId,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/vendor_bills/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Vendor_bills]
* 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/Vendor_bills"
* 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 Vendor_billsDBApi.findBy(
{ id: req.params.id },
);
res.status(200).send(payload);
}));
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

View File

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