Initial version

This commit is contained in:
Flatlogic Bot 2025-07-24 15:29:27 +00:00
commit 3ab917cfd5
673 changed files with 117936 additions and 0 deletions

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>CuriousDemo</h2>
<p>AppWizzy: A schema-building tool for users.</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>

17
Dockerfile Normal file
View File

@ -0,0 +1,17 @@
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/

200
README.md Normal file
View File

@ -0,0 +1,200 @@
# CuriousDemo
## 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`

26
app-shell/.eslintrc.cjs Normal file
View File

@ -0,0 +1,26 @@
const globals = require('globals');
module.exports = [
{
files: ['**/*.js', '**/*.ts', '**/*.tsx'],
languageOptions: {
ecmaVersion: 2021,
sourceType: 'module',
globals: {
...globals.browser,
...globals.node,
},
parser: '@typescript-eslint/parser',
},
plugins: ['@typescript-eslint'],
rules: {
'no-unused-vars': 'warn',
'no-console': 'off',
'indent': ['error', 2],
'quotes': ['error', 'single'],
'semi': ['error', 'always'],
'@typescript-eslint/no-unused-vars': 'warn',
},
},
];

11
app-shell/.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
app-shell/.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
app-shell/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 4000
CMD [ "yarn", "start" ]

13
app-shell/README.md Normal file
View File

@ -0,0 +1,13 @@
#test - template backend,
#### Run App on local machine:
##### Install local dependencies:
- `yarn install`
---
##### Start build:
- `yarn start`

43
app-shell/package.json Normal file
View File

@ -0,0 +1,43 @@
{
"name": "app-shell",
"description": "app-shell",
"scripts": {
"start": "node ./src/index.js"
},
"dependencies": {
"@babel/parser": "^7.26.7",
"adm-zip": "^0.5.16",
"axios": "^1.6.7",
"bcrypt": "5.1.1",
"cors": "2.8.5",
"eslint": "^9.13.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",
"passport": "^0.7.0",
"passport-google-oauth2": "^0.2.0",
"passport-jwt": "^4.0.1",
"passport-microsoft": "^0.1.0",
"postcss": "^8.5.1",
"puppeteer": "^24.10.0",
"sequelize-json-schema": "^2.1.1",
"pg": "^8.13.3"
},
"engines": {
"node": ">=18"
},
"private": true,
"devDependencies": {
"@typescript-eslint/eslint-plugin": "^8.12.2",
"@typescript-eslint/parser": "^8.12.2",
"cross-env": "7.0.3",
"mocha": "8.1.3",
"nodemon": "^3.1.7",
"sequelize-cli": "6.6.2"
}
}

File diff suppressed because one or more lines are too long

18
app-shell/src/config.js Normal file
View File

@ -0,0 +1,18 @@
const config = {
admin_pass: "989d1a94",
admin_email: "admin@flatlogic.com",
schema_encryption_key: process.env.SCHEMA_ENCRYPTION_KEY || '',
project_uuid: '989d1a94-13ba-4c95-a65f-778d4a5e11b2',
flHost: process.env.NODE_ENV === 'production' ? 'https://flatlogic.com/projects' : 'http://localhost:3000/projects',
gitea_domain: process.env.GITEA_DOMAIN || 'gitea.flatlogic.app',
gitea_username: process.env.GITEA_USERNAME || 'admin',
gitea_api_token: process.env.GITEA_API_TOKEN || null,
github_repo_url: process.env.GITHUB_REPO_URL || null,
github_token: process.env.GITHUB_TOKEN || null,
};
module.exports = config;

23
app-shell/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' });
}
};

54
app-shell/src/index.js Normal file
View File

@ -0,0 +1,54 @@
const express = require('express');
const cors = require('cors');
const app = express();
const bodyParser = require('body-parser');
const checkPermissions = require('./middlewares/check-permissions');
const modifyPath = require('./middlewares/modify-path');
const VCS = require('./services/vcs');
const executorRoutes = require('./routes/executor');
const vcsRoutes = require('./routes/vcs');
// Function to initialize the Git repository
function initRepo() {
const projectId = '32858';
return VCS.initRepo(projectId);
}
// Start the Express app on APP_SHELL_PORT (4000)
function startServer() {
const PORT = 4000;
app.listen(PORT, () => {
console.log(`Listening on port ${PORT}`);
});
}
// Run Git check after the server is up
function runGitCheck() {
initRepo()
.then(result => {
console.log(result?.message ? result.message : result);
// Here you can add additional logic if needed
})
.catch(err => {
console.error('Error during repo initialization:', err);
// Optionally exit the process if Git check is critical:
// process.exit(1);
});
}
app.use(cors({ origin: true }));
app.use(bodyParser.json());
app.use(checkPermissions);
app.use(modifyPath);
app.use('/executor', executorRoutes);
app.use('/vcs', vcsRoutes);
// Start the app_shell server
startServer();
// Now perform Git check
runGitCheck();
module.exports = app;

View File

@ -0,0 +1,17 @@
const config = require('../config');
function checkPermissions(req, res, next) {
const project_uuid = config.project_uuid;
const requiredHeader = 'X-Project-UUID';
const headerValue = req.headers[requiredHeader.toLowerCase()];
// Logging whatever request we're getting
console.log('Request:', req.url, req.method, req.body, req.headers);
if (headerValue && headerValue === project_uuid) {
next();
} else {
res.status(403).send({ error: 'Stop right there, criminal scum! Your project UUID is invalid or missing.' });
}
}
module.exports = checkPermissions;

View File

@ -0,0 +1,8 @@
function modifyPath(req, res, next) {
if (req.body && req.body.path) {
req.body.path = '../../../' + req.body.path;
}
next();
}
module.exports = modifyPath;

View File

@ -0,0 +1,346 @@
const express = require('express');
const multer = require('multer');
const upload = multer({ dest: 'uploads/' });
const fs = require('fs');
const ExecutorService = require('../services/executor');
const { takeScreenshot } = require("../services/screenshot_service");
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
router.post(
'/read_project_tree',
wrapAsync(async (req, res) => {
const { path } = req.body;
const tree = await ExecutorService.readProjectTree(path);
res.status(200).send(tree);
}),
);
router.post(
'/read_file',
wrapAsync(async (req, res) => {
const { path, showLines } = req.body;
const content = await ExecutorService.readFileContents(path, showLines);
res.status(200).send(content);
}),
);
router.post(
'/count_file_lines',
wrapAsync(async (req, res) => {
const { path } = req.body;
const content = await ExecutorService.countFileLines(path);
res.status(200).send(content);
}),
);
// router.post(
// '/read_file_header',
// wrapAsync(async (req, res) => {
// const { path, N } = req.body;
// try {
// const header = await ExecutorService.readFileHeader(path, N);
// res.status(200).send(header);
// } catch (error) {
// res.status(500).send({
// error: true,
// message: error.message,
// details: error.details || error.stack,
// validation: error.validation
// });
// }
// }),
// );
router.post(
'/read_file_line_context',
wrapAsync(async (req, res) => {
const { path, lineNumber, windowSize, showLines } = req.body;
try {
const context = await ExecutorService.readFileLineContext(path, lineNumber, windowSize, showLines);
res.status(200).send(context);
} catch (error) {
res.status(500).send({
error: true,
message: error.message,
details: error.details || error.stack,
validation: error.validation
});
}
}),
);
router.post(
'/write_file',
wrapAsync(async (req, res) => {
const { path, fileContents, comment } = req.body;
try {
await ExecutorService.writeFile(path, fileContents, comment);
res.status(200).send({ message: 'File written successfully' });
} catch (error) {
res.status(500).send({
error: true,
message: error.message,
details: error.details || error.stack,
validation: error.validation
});
}
}),
);
router.post(
'/insert_file_content',
wrapAsync(async (req, res) => {
const { path, lineNumber, newContent, message } = req.body;
try {
await ExecutorService.insertFileContent(path, lineNumber, newContent, message);
res.status(200).send({ message: 'File written successfully' });
} catch (error) {
res.status(500).send({
error: true,
message: error.message,
details: error.details || error.stack,
validation: error.validation
});
}
}),
);
router.post(
'/replace_file_line',
wrapAsync(async (req, res) => {
const { path, lineNumber, newText } = req.body;
try {
const result = await ExecutorService.replaceFileLine(path, lineNumber, newText);
res.status(200).send(result);
} catch (error) {
res.status(500).send({
error: true,
message: error.message,
details: error.details || error.stack,
validation: error.validation
});
}
}),
);
router.post(
'/replace_file_chunk',
wrapAsync(async (req, res) => {
const { path, startLine, endLine, newCode } = req.body;
try {
const result = await ExecutorService.replaceFileChunk(path, startLine, endLine, newCode);
res.status(200).send(result);
} catch (error) {
res.status(500).send({
error: true,
message: error.message,
details: error.details || error.stack,
validation: error.validation
});
}
}),
);
router.post(
'/delete_file_lines',
wrapAsync(async (req, res) => {
const { path, startLine, endLine, message } = req.body;
try {
const result = await ExecutorService.deleteFileLines(path, startLine, endLine, message);
res.status(200).send(result);
} catch (error) {
res.status(500).send({
error: true,
message: error.message,
details: error.details || error.stack,
validation: error.validation
});
}
}),
);
router.post(
'/validate_file',
wrapAsync(async (req, res) => {
const { path } = req.body;
try {
const validationResult = await ExecutorService.validateFile(path);
res.status(200).send({ validationResult });
} catch (error) {
res.status(500).send({
error: true,
message: error.message,
details: error.details || error.stack,
validation: error.validation
});
}
}),
);
router.post(
'/check_frontend_runtime_error',
wrapAsync(async (req, res) => {
try {
const result = await ExecutorService.checkFrontendRuntimeLogs();
res.status(200).send(result);
} catch (error) {
res.status(500).send({ error: error });
}
}),
);
router.post(
'/replace_code_block',
wrapAsync(async (req, res) => {
const {path, oldCode, newCode, message} = req.body;
try {
const response = await ExecutorService.replaceCodeBlock(path, oldCode, newCode, message);
res.status(200).send(response);
} catch (error) {
res.status(500).send({
error: true,
message: error.message,
details: error.details || error.stack,
validation: error.validation
})
}
})
)
router.post('/update_project_files_from_scheme',
upload.single('file'), // 'file' - name of the field in the form
async (req, res) => {
console.log('Request received');
console.log('Headers:', req.headers);
if (!req.file) {
return res.status(400).json({ error: 'No file uploaded' });
}
console.log('File info:', {
originalname: req.file.originalname,
path: req.file.path,
size: req.file.size,
mimetype: req.file.mimetype
});
try {
console.log('Starting update process...');
const result = await ExecutorService.updateProjectFilesFromScheme(req.file.path);
console.log('Update completed, result:', result);
console.log('Removing temp file...');
fs.unlinkSync(req.file.path);
console.log('Temp file removed');
console.log('Sending response...');
return res.json(result);
} catch (error) {
console.error('Error in route handler:', error);
if (req.file) {
try {
fs.unlinkSync(req.file.path);
console.log('Temp file removed after error');
} catch (unlinkError) {
console.error('Error removing temp file:', unlinkError);
}
}
console.error('Update project files error:', error);
return res.status(500).json({
error: error.message,
stack: process.env.NODE_ENV === 'development' ? error.stack : undefined
});
}
}
);
router.post(
'/get_db_schema',
wrapAsync(async (req, res) => {
try {
const jsonSchema = await ExecutorService.getDBSchema();
res.status(200).send({ jsonSchema });
} catch (error) {
res.status(500).send({ error: error });
}
}),
);
router.post(
'/execute_sql',
wrapAsync(async (req, res) => {
try {
const { query } = req.body;
const result = await ExecutorService.executeSQL(query);
res.status(200).send(result);
} catch (error) {
res.status(500).send({ error: error });
}
}),
);
router.post(
'/search_files',
wrapAsync(async (req, res) => {
try {
const { searchStrings } = req.body;
if (
typeof searchStrings !== 'string' &&
!(
Array.isArray(searchStrings) &&
searchStrings.every(item => typeof item === 'string')
)
) {
return res.status(400).send({ error: 'searchStrings must be a string or an array of strings' });
}
const result = await ExecutorService.searchFiles(searchStrings);
res.status(200).send(result);
} catch (error) {
res.status(500).send({ error: error.message });
}
}),
);
router.post(
'/screenshot',
wrapAsync(async (req, res) => {
const FRONT_PORT = process.env.FRONT_PORT || 3001;
const targetUrl = `http://localhost:${FRONT_PORT}${req.body.url || '/'}`;
const filename = req.query.filename || `screenshot-${Date.now()}.png`;
const fullPage = req.query.fullPage !== 'false';
try {
console.log(`[App-Shell/Screenshot Route]: request to take screenshot of ${targetUrl} with filename ${filename} and fullPage=${fullPage}`);
const outputPath = await takeScreenshot(targetUrl, filename, fullPage);
res.sendFile(outputPath, async (err) => {
if (err) {
console.error(`[App-Shell/Screenshot Route]: error sending screenshot ${outputPath}:`, err);
if (err.code === 'ENOENT') {
res.status(404).send('Screenshot not found.');
} else {
res.status(500).send('Error sending screenshot: ' + err.message);
}
} else {
console.log(`[App-Shell/Screenshot Route]: Screenshot sent successfully: ${outputPath}`);
}
});
} catch (error) {
console.error(`[App-Shell/Screenshot Route]: Could not take screenshot of ${targetUrl}:`, error);
res.status(500).send(`Error taking screenshot: ${error.message}`);
}
})
)
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

View File

@ -0,0 +1,40 @@
const express = require('express');
const wrapAsync = require('../helpers').wrapAsync; // Ваша обёртка для обработки асинхронных маршрутов
const VSC = require('../services/vcs');
const router = express.Router();
router.post('/init', wrapAsync(async (req, res) => {
const result = await VSC.initRepo();
res.status(200).send(result);
}));
router.post('/commit', wrapAsync(async (req, res) => {
const { message, files, dev_schema } = req.body;
const result = await VSC.commitChanges(message, files, dev_schema);
res.status(200).send(result);
}));
router.post('/log', wrapAsync(async (req, res) => {
const result = await VSC.getLog();
res.status(200).send(result);
}));
router.post('/rollback', wrapAsync(async (req, res) => {
const { ref } = req.body;
// const result = await VSC.checkout(ref);
const result = await VSC.revert(ref);
res.status(200).send(result);
}));
router.post('/sync-to-stable', wrapAsync(async (req, res) => {
const result = await VSC.mergeDevIntoMaster();
res.status(200).send(result);
}));
router.post('/reset-dev', wrapAsync(async (req, res) => {
const result = await VSC.resetDevBranch();
res.status(200).send(result);
}));
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

View File

@ -0,0 +1,88 @@
// Database.js
const { Client } = require('pg');
const config = require('../../../backend/src/db/db.config');
const env = process.env.NODE_ENV || 'development';
const dbConfig = config[env];
class Database {
constructor() {
this.client = new Client({
user: dbConfig.username,
password: dbConfig.password,
database: dbConfig.database,
host: dbConfig.host,
port: dbConfig.port
});
// Connect once, reuse the client
this.client.connect().catch(err => {
console.error('Error connecting to the database:', err);
throw err;
});
}
async executeSQL(query) {
try {
const result = await this.client.query(query);
return {
success: true,
rows: result.rows
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
// Method to fetch simple table/column info from 'information_schema'
// (You can expand this to handle constraints, indexes, etc.)
async getDBSchema(schemaName = 'public') {
try {
const tableQuery = `
SELECT table_name
FROM information_schema.tables
WHERE table_schema = $1
AND table_type = 'BASE TABLE'
ORDER BY table_name
`;
const columnQuery = `
SELECT table_name, column_name, data_type, is_nullable
FROM information_schema.columns
WHERE table_schema = $1
ORDER BY table_name, ordinal_position
`;
const [tablesResult, columnsResult] = await Promise.all([
this.client.query(tableQuery, [schemaName]),
this.client.query(columnQuery, [schemaName]),
]);
// Build a simple schema object:
const tables = tablesResult.rows.map(row => row.table_name);
const columnsByTable = {};
columnsResult.rows.forEach(row => {
const { table_name, column_name, data_type, is_nullable } = row;
if (!columnsByTable[table_name]) columnsByTable[table_name] = [];
columnsByTable[table_name].push({ column_name, data_type, is_nullable });
});
// Combine tables with their columns
return tables.map(table => ({
table,
columns: columnsByTable[table] || [],
}));
} catch (error) {
console.error('Error fetching schema:', error);
throw error;
}
}
async close() {
await this.client.end();
}
}
module.exports = new Database();

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,16 @@
const { getNotification, isNotification } = require('../helpers');
module.exports = class ForbiddenError extends Error {
constructor(messageCode) {
let message;
if (messageCode && isNotification(messageCode)) {
message = getNotification(messageCode);
}
message = message || getNotification('errors.forbidden.message');
super(message);
this.code = 403;
}
};

View File

@ -0,0 +1,16 @@
const { getNotification, isNotification } = require('../helpers');
module.exports = class ValidationError extends Error {
constructor(messageCode) {
let message;
if (messageCode && isNotification(messageCode)) {
message = getNotification(messageCode);
}
message = message || getNotification('errors.validation.message');
super(message);
this.code = 400;
}
};

View File

@ -0,0 +1,30 @@
const _get = require('lodash/get');
const errors = require('./list');
function format(message, args) {
if (!message) {
return null;
}
return message.replace(/{(\d+)}/g, function (match, number) {
return typeof args[number] != 'undefined' ? args[number] : match;
});
}
const isNotification = (key) => {
const message = _get(errors, key);
return !!message;
};
const getNotification = (key, ...args) => {
const message = _get(errors, key);
if (!message) {
return key;
}
return format(message, args);
};
exports.getNotification = getNotification;
exports.isNotification = isNotification;

View File

@ -0,0 +1,100 @@
const errors = {
app: {
title: 'test',
},
auth: {
userDisabled: 'Your account is disabled',
forbidden: 'Forbidden',
unauthorized: 'Unauthorized',
userNotFound: `Sorry, we don't recognize your credentials`,
wrongPassword: `Sorry, we don't recognize your credentials`,
weakPassword: 'This password is too weak',
emailAlreadyInUse: 'Email is already in use',
invalidEmail: 'Please provide a valid email',
passwordReset: {
invalidToken: 'Password reset link is invalid or has expired',
error: `Email not recognized`,
},
passwordUpdate: {
samePassword: `You can't use the same password. Please create new password`,
},
userNotVerified: `Sorry, your email has not been verified yet`,
emailAddressVerificationEmail: {
invalidToken: 'Email verification link is invalid or has expired',
error: `Email not recognized`,
},
},
iam: {
errors: {
userAlreadyExists: 'User with this email already exists',
userNotFound: 'User not found',
disablingHimself: `You can't disable yourself`,
revokingOwnPermission: `You can't revoke your own owner permission`,
deletingHimself: `You can't delete yourself`,
emailRequired: 'Email is required',
},
},
importer: {
errors: {
invalidFileEmpty: 'The file is empty',
invalidFileExcel: 'Only excel (.xlsx) files are allowed',
invalidFileUpload:
'Invalid file. Make sure you are using the last version of the template.',
importHashRequired: 'Import hash is required',
importHashExistent: 'Data has already been imported',
userEmailMissing: 'Some items in the CSV do not have an email',
},
},
errors: {
forbidden: {
message: 'Forbidden',
},
validation: {
message: 'An error occurred',
},
searchQueryRequired: {
message: 'Search query is required',
},
},
emails: {
invitation: {
subject: `You've been invited to {0}`,
body: `
<p>Hello,</p>
<p>You've been invited to {0} set password for your {1} account.</p>
<p><a href='{2}'>{2}</a></p>
<p>Thanks,</p>
<p>Your {0} team</p>
`,
},
emailAddressVerification: {
subject: `Verify your email for {0}`,
body: `
<p>Hello,</p>
<p>Follow this link to verify your email address.</p>
<p><a href='{0}'>{0}</a></p>
<p>If you didn't ask to verify this address, you can ignore this email.</p>
<p>Thanks,</p>
<p>Your {1} team</p>
`,
},
passwordReset: {
subject: `Reset your password for {0}`,
body: `
<p>Hello,</p>
<p>Follow this link to reset your {0} password for your {1} account.</p>
<p><a href='{2}'>{2}</a></p>
<p>If you didn't ask to reset your password, you can ignore this email.</p>
<p>Thanks,</p>
<p>Your {0} team</p>
`,
},
},
};
module.exports = errors;

View File

@ -0,0 +1,67 @@
const axios = require('axios');
const config = require('../config.js');
class ProjectEventsService {
/**
* Sends a project event to the Rails backend
*
* @param {string} eventType - Type of the event
* @param {object} payload - Event payload data
* @param {object} options - Additional options
* @param {string} [options.conversationId] - Optional conversation ID
* @param {boolean} [options.isError=false] - Whether this is an error event
* @returns {Promise<object>} - Response from the webhook
*/
static async sendEvent(eventType, payload = {}, options = {}) {
try {
console.log(`[DEBUG] Sending project event: ${eventType}`);
const webhookUrl = `https://flatlogic.com/projects/events_webhook`;
// Prepare the event data
const eventData = {
project_uuid: config.project_uuid,
event_type: eventType,
payload: {
...payload,
message: `[APP] ${payload.message}`,
is_error: options.isError || false,
system_message: true,
is_command_info: true
}
};
// Add conversation ID if provided
if (options.conversationId) {
eventData.conversation_id = options.conversationId;
}
const headers = {
'Content-Type': 'application/json',
'x-project-uuid': config.project_uuid
};
console.log(`[DEBUG] Event data: ${JSON.stringify(eventData)}`);
const response = await axios.post(webhookUrl, eventData, { headers });
console.log(`[DEBUG] Event sent successfully, status: ${response.status}`);
return response.data;
} catch (error) {
console.error(`[ERROR] Failed to send project event: ${error.message}`);
if (error.response) {
console.error(`[ERROR] Response status: ${error.response.status}`);
console.error(`[ERROR] Response data: ${JSON.stringify(error.response.data)}`);
}
// Don't throw the error, just return a failed status
// This prevents errors in the event service from breaking app functionality
return {
success: false,
error: error.message
};
}
}
}
module.exports = ProjectEventsService;

View File

@ -0,0 +1,83 @@
const puppeteer = require('puppeteer');
const path = require('path');
const fs = require('fs/promises');
const config = require('../config');
const BACKEND_URL = process.env.BACKEND_URL || 'http://localhost:3000';
const SCREENSHOT_DIR = process.env.SCREENSHOT_DIR || '/tmp/screenshots';
fs.mkdir(SCREENSHOT_DIR, { recursive: true }).catch(console.error);
async function takeScreenshot(url, filename = `screenshot-${Date.now()}.png`, fullPage = true) {
let browser;
const response = await axios.post(
`${BACKEND_URL}/api/auth/signin/local`,
{ email: config.admin_email, password: config.admin_pass },
{
headers: {
'Content-Type': 'application/json',
},
}
);
const token = response.data;
const outputPath = path.join(SCREENSHOT_DIR, filename);
try {
browser = await puppeteer.launch({
headless: true,
args: [
'--no-sandbox',
'--disable-setuid-sandbox',
'--disable-dev-shm-usage',
'--disable-accelerated-2d-canvas',
'--disable-gpu',
'window-size=1920,1080'
]
});
const page = await browser.newPage();
await page.setViewport({ width: 1920, height: 1080 });
if (token) {
await page.setRequestInterception(true);
page.on('request', interceptedRequest => {
if (interceptedRequest.isInterceptResolutionHandled()) {
return;
}
const headers = interceptedRequest.headers();
if (!headers['authorization'] && !headers['Authorization']) {
headers['Authorization'] = `Bearer ${token}`;
}
interceptedRequest.continue({ headers });
});
page.on('requestfailed', request => {
console.error(`[ScreenshotService]: Request failed: ${request.url()} - ${request.failure().errorText}`);
});
}
await page.goto(url, { waitUntil: 'load', timeout: 60000 });
await page.screenshot({
path: outputPath,
fullPage: true,
});
console.log(`[ScreenshotService]: Screenshot saved to ${outputPath}`);
return outputPath;
} catch (error) {
console.error(`[ScreenshotService]: Error taking screenshot: ${error.message}`);
throw error;
} finally {
if (browser) {
await browser.close();
}
}
}
module.exports = { takeScreenshot };

File diff suppressed because it is too large Load Diff

3044
app-shell/yarn.lock Normal file

File diff suppressed because it is too large Load Diff

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" ]

67
backend/README.md Normal file
View File

@ -0,0 +1,67 @@
#CuriousDemo - 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_curiousdemo;`
- Then give that new user privileges to the new database then quit the `psql`.
- `postgres=> GRANT ALL PRIVILEGES ON DATABASE db_curiousdemo 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`

53
backend/package.json Normal file
View File

@ -0,0 +1,53 @@
{
"name": "curiousdemo",
"description": "CuriousDemo - template backend",
"scripts": {
"start": "npm run db:migrate && npm run db:seed && npm run watch",
"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",
"mocha": "8.1.3",
"node-mocks-http": "1.9.0",
"nodemon": "2.0.5",
"sequelize-cli": "6.6.2"
}
}

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

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

75
backend/src/config.js Normal file
View File

@ -0,0 +1,75 @@
const os = require('os');
const config = {
gcloud: {
bucket: 'fldemo-files',
hash: '00b1f7545cdbfd7a2a56c0ea093a0530',
},
bcrypt: {
saltRounds: 12,
},
admin_pass: '989d1a94',
user_pass: '778d4a5e11b2',
admin_email: 'admin@flatlogic.com',
providers: {
LOCAL: 'local',
GOOGLE: 'google',
MICROSOFT: 'microsoft',
},
secret_key: process.env.SECRET_KEY || '',
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: 'CuriousDemo <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: {
admin: 'Administrator',
user: 'Support Specialist',
},
project_uuid: '989d1a94-13ba-4c95-a65f-778d4a5e11b2',
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 = 'Abstract tech design';
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,247 @@
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 Adbuilder_assetsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const adbuilder_assets = await db.adbuilder_assets.create(
{
id: data.id || undefined,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return adbuilder_assets;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const adbuilder_assetsData = data.map((item, index) => ({
id: item.id || undefined,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const adbuilder_assets = await db.adbuilder_assets.bulkCreate(
adbuilder_assetsData,
{ transaction },
);
// For each item created, replace relation files
return adbuilder_assets;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const adbuilder_assets = await db.adbuilder_assets.findByPk(
id,
{},
{ transaction },
);
const updatePayload = {};
updatePayload.updatedById = currentUser.id;
await adbuilder_assets.update(updatePayload, { transaction });
return adbuilder_assets;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const adbuilder_assets = await db.adbuilder_assets.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of adbuilder_assets) {
await record.update({ deletedBy: currentUser.id }, { transaction });
}
for (const record of adbuilder_assets) {
await record.destroy({ transaction });
}
});
return adbuilder_assets;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const adbuilder_assets = await db.adbuilder_assets.findByPk(id, options);
await adbuilder_assets.update(
{
deletedBy: currentUser.id,
},
{
transaction,
},
);
await adbuilder_assets.destroy({
transaction,
});
return adbuilder_assets;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const adbuilder_assets = await db.adbuilder_assets.findOne(
{ where },
{ transaction },
);
if (!adbuilder_assets) {
return adbuilder_assets;
}
const output = adbuilder_assets.get({ plain: true });
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
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.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.adbuilder_assets.findAndCountAll(
queryOptions,
);
return {
rows: options?.countOnly ? [] : rows,
count: count,
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike('adbuilder_assets', 'id', query),
],
};
}
const records = await db.adbuilder_assets.findAll({
attributes: ['id', 'id'],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['id', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.id,
}));
}
};

View File

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

View File

@ -0,0 +1,718 @@
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 Brand_rate_cardsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const brand_rate_cards = await db.brand_rate_cards.create(
{
id: data.id || undefined,
name: data.name || null,
rate_card_type: data.rate_card_type || null,
status: data.status || null,
currency: data.currency || null,
push_new_values: data.push_new_values || false,
inherit_default_rate_card: data.inherit_default_rate_card || false,
service_count: data.service_count || null,
discipline: data.discipline || null,
output_channel: data.output_channel || null,
staff_skills: data.staff_skills || null,
rate_card_owner: data.rate_card_owner || null,
rate_card_id: data.rate_card_id || null,
markets: data.markets || null,
languages: data.languages || null,
valid_from: data.valid_from || null,
valid_to: data.valid_to || null,
version_number: data.version_number || null,
commercial_owner: data.commercial_owner || null,
review_date: data.review_date || null,
assumptions: data.assumptions || null,
no_fixed_text: data.no_fixed_text || null,
yes_fixed_text: data.yes_fixed_text || null,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await brand_rate_cards.setClient(data.client || null, {
transaction,
});
await brand_rate_cards.setBrand(data.brand || null, {
transaction,
});
return brand_rate_cards;
}
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 brand_rate_cardsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name || null,
rate_card_type: item.rate_card_type || null,
status: item.status || null,
currency: item.currency || null,
push_new_values: item.push_new_values || false,
inherit_default_rate_card: item.inherit_default_rate_card || false,
service_count: item.service_count || null,
discipline: item.discipline || null,
output_channel: item.output_channel || null,
staff_skills: item.staff_skills || null,
rate_card_owner: item.rate_card_owner || null,
rate_card_id: item.rate_card_id || null,
markets: item.markets || null,
languages: item.languages || null,
valid_from: item.valid_from || null,
valid_to: item.valid_to || null,
version_number: item.version_number || null,
commercial_owner: item.commercial_owner || null,
review_date: item.review_date || null,
assumptions: item.assumptions || null,
no_fixed_text: item.no_fixed_text || null,
yes_fixed_text: item.yes_fixed_text || null,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const brand_rate_cards = await db.brand_rate_cards.bulkCreate(
brand_rate_cardsData,
{ transaction },
);
// For each item created, replace relation files
return brand_rate_cards;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const brand_rate_cards = await db.brand_rate_cards.findByPk(
id,
{},
{ transaction },
);
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.rate_card_type !== undefined)
updatePayload.rate_card_type = data.rate_card_type;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.currency !== undefined) updatePayload.currency = data.currency;
if (data.push_new_values !== undefined)
updatePayload.push_new_values = data.push_new_values;
if (data.inherit_default_rate_card !== undefined)
updatePayload.inherit_default_rate_card = data.inherit_default_rate_card;
if (data.service_count !== undefined)
updatePayload.service_count = data.service_count;
if (data.discipline !== undefined)
updatePayload.discipline = data.discipline;
if (data.output_channel !== undefined)
updatePayload.output_channel = data.output_channel;
if (data.staff_skills !== undefined)
updatePayload.staff_skills = data.staff_skills;
if (data.rate_card_owner !== undefined)
updatePayload.rate_card_owner = data.rate_card_owner;
if (data.rate_card_id !== undefined)
updatePayload.rate_card_id = data.rate_card_id;
if (data.markets !== undefined) updatePayload.markets = data.markets;
if (data.languages !== undefined) updatePayload.languages = data.languages;
if (data.valid_from !== undefined)
updatePayload.valid_from = data.valid_from;
if (data.valid_to !== undefined) updatePayload.valid_to = data.valid_to;
if (data.version_number !== undefined)
updatePayload.version_number = data.version_number;
if (data.commercial_owner !== undefined)
updatePayload.commercial_owner = data.commercial_owner;
if (data.review_date !== undefined)
updatePayload.review_date = data.review_date;
if (data.assumptions !== undefined)
updatePayload.assumptions = data.assumptions;
if (data.no_fixed_text !== undefined)
updatePayload.no_fixed_text = data.no_fixed_text;
if (data.yes_fixed_text !== undefined)
updatePayload.yes_fixed_text = data.yes_fixed_text;
updatePayload.updatedById = currentUser.id;
await brand_rate_cards.update(updatePayload, { transaction });
if (data.client !== undefined) {
await brand_rate_cards.setClient(
data.client,
{ transaction },
);
}
if (data.brand !== undefined) {
await brand_rate_cards.setBrand(
data.brand,
{ transaction },
);
}
return brand_rate_cards;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const brand_rate_cards = await db.brand_rate_cards.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of brand_rate_cards) {
await record.update({ deletedBy: currentUser.id }, { transaction });
}
for (const record of brand_rate_cards) {
await record.destroy({ transaction });
}
});
return brand_rate_cards;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const brand_rate_cards = await db.brand_rate_cards.findByPk(id, options);
await brand_rate_cards.update(
{
deletedBy: currentUser.id,
},
{
transaction,
},
);
await brand_rate_cards.destroy({
transaction,
});
return brand_rate_cards;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const brand_rate_cards = await db.brand_rate_cards.findOne(
{ where },
{ transaction },
);
if (!brand_rate_cards) {
return brand_rate_cards;
}
const output = brand_rate_cards.get({ plain: true });
output.brands_link_rate_card =
await brand_rate_cards.getBrands_link_rate_card({
transaction,
});
output.client = await brand_rate_cards.getClient({
transaction,
});
output.brand = await brand_rate_cards.getBrand({
transaction,
});
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.clients,
as: 'client',
where: filter.client
? {
[Op.or]: [
{
id: {
[Op.in]: filter.client
.split('|')
.map((term) => Utils.uuid(term)),
},
},
{
id: {
[Op.or]: filter.client
.split('|')
.map((term) => ({ [Op.iLike]: `%${term}%` })),
},
},
],
}
: {},
},
{
model: db.brands,
as: 'brand',
where: filter.brand
? {
[Op.or]: [
{
id: {
[Op.in]: filter.brand
.split('|')
.map((term) => Utils.uuid(term)),
},
},
{
id: {
[Op.or]: filter.brand
.split('|')
.map((term) => ({ [Op.iLike]: `%${term}%` })),
},
},
],
}
: {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike('brand_rate_cards', 'name', filter.name),
};
}
if (filter.rate_card_type) {
where = {
...where,
[Op.and]: Utils.ilike(
'brand_rate_cards',
'rate_card_type',
filter.rate_card_type,
),
};
}
if (filter.status) {
where = {
...where,
[Op.and]: Utils.ilike('brand_rate_cards', 'status', filter.status),
};
}
if (filter.currency) {
where = {
...where,
[Op.and]: Utils.ilike(
'brand_rate_cards',
'currency',
filter.currency,
),
};
}
if (filter.discipline) {
where = {
...where,
[Op.and]: Utils.ilike(
'brand_rate_cards',
'discipline',
filter.discipline,
),
};
}
if (filter.output_channel) {
where = {
...where,
[Op.and]: Utils.ilike(
'brand_rate_cards',
'output_channel',
filter.output_channel,
),
};
}
if (filter.staff_skills) {
where = {
...where,
[Op.and]: Utils.ilike(
'brand_rate_cards',
'staff_skills',
filter.staff_skills,
),
};
}
if (filter.rate_card_owner) {
where = {
...where,
[Op.and]: Utils.ilike(
'brand_rate_cards',
'rate_card_owner',
filter.rate_card_owner,
),
};
}
if (filter.rate_card_id) {
where = {
...where,
[Op.and]: Utils.ilike(
'brand_rate_cards',
'rate_card_id',
filter.rate_card_id,
),
};
}
if (filter.markets) {
where = {
...where,
[Op.and]: Utils.ilike('brand_rate_cards', 'markets', filter.markets),
};
}
if (filter.languages) {
where = {
...where,
[Op.and]: Utils.ilike(
'brand_rate_cards',
'languages',
filter.languages,
),
};
}
if (filter.version_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'brand_rate_cards',
'version_number',
filter.version_number,
),
};
}
if (filter.commercial_owner) {
where = {
...where,
[Op.and]: Utils.ilike(
'brand_rate_cards',
'commercial_owner',
filter.commercial_owner,
),
};
}
if (filter.assumptions) {
where = {
...where,
[Op.and]: Utils.ilike(
'brand_rate_cards',
'assumptions',
filter.assumptions,
),
};
}
if (filter.no_fixed_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'brand_rate_cards',
'no_fixed_text',
filter.no_fixed_text,
),
};
}
if (filter.yes_fixed_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'brand_rate_cards',
'yes_fixed_text',
filter.yes_fixed_text,
),
};
}
if (filter.service_countRange) {
const [start, end] = filter.service_countRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
service_count: {
...where.service_count,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
service_count: {
...where.service_count,
[Op.lte]: end,
},
};
}
}
if (filter.valid_fromRange) {
const [start, end] = filter.valid_fromRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
valid_from: {
...where.valid_from,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
valid_from: {
...where.valid_from,
[Op.lte]: end,
},
};
}
}
if (filter.valid_toRange) {
const [start, end] = filter.valid_toRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
valid_to: {
...where.valid_to,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
valid_to: {
...where.valid_to,
[Op.lte]: end,
},
};
}
}
if (filter.review_dateRange) {
const [start, end] = filter.review_dateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
review_date: {
...where.review_date,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
review_date: {
...where.review_date,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true',
};
}
if (filter.push_new_values) {
where = {
...where,
push_new_values: filter.push_new_values,
};
}
if (filter.inherit_default_rate_card) {
where = {
...where,
inherit_default_rate_card: filter.inherit_default_rate_card,
};
}
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.brand_rate_cards.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('brand_rate_cards', 'id', query),
],
};
}
const records = await db.brand_rate_cards.findAll({
attributes: ['id', 'id'],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['id', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.id,
}));
}
};

View File

@ -0,0 +1,606 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class BrandsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const brands = await db.brands.create(
{
id: data.id || undefined,
name: data.name || null,
rate_card_import: data.rate_card_import || false,
client_fixed_text: data.client_fixed_text || null,
yes_fixed_text: data.yes_fixed_text || null,
default_client_contact: data.default_client_contact || null,
inherit_default_rate_card: data.inherit_default_rate_card || false,
default_costs: data.default_costs || null,
production_fee: data.production_fee || null,
insurance_fee: data.insurance_fee || null,
temp: data.temp || null,
xero_id: data.xero_id || null,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await brands.setClient(data.client || null, {
transaction,
});
await brands.setDefault_account_manager(
data.default_account_manager || null,
{
transaction,
},
);
await brands.setDefault_sales(data.default_sales || null, {
transaction,
});
await brands.setLink_rate_card(data.link_rate_card || null, {
transaction,
});
return brands;
}
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 brandsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name || null,
rate_card_import: item.rate_card_import || false,
client_fixed_text: item.client_fixed_text || null,
yes_fixed_text: item.yes_fixed_text || null,
default_client_contact: item.default_client_contact || null,
inherit_default_rate_card: item.inherit_default_rate_card || false,
default_costs: item.default_costs || null,
production_fee: item.production_fee || null,
insurance_fee: item.insurance_fee || null,
temp: item.temp || null,
xero_id: item.xero_id || null,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const brands = await db.brands.bulkCreate(brandsData, { transaction });
// For each item created, replace relation files
return brands;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const brands = await db.brands.findByPk(id, {}, { transaction });
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.rate_card_import !== undefined)
updatePayload.rate_card_import = data.rate_card_import;
if (data.client_fixed_text !== undefined)
updatePayload.client_fixed_text = data.client_fixed_text;
if (data.yes_fixed_text !== undefined)
updatePayload.yes_fixed_text = data.yes_fixed_text;
if (data.default_client_contact !== undefined)
updatePayload.default_client_contact = data.default_client_contact;
if (data.inherit_default_rate_card !== undefined)
updatePayload.inherit_default_rate_card = data.inherit_default_rate_card;
if (data.default_costs !== undefined)
updatePayload.default_costs = data.default_costs;
if (data.production_fee !== undefined)
updatePayload.production_fee = data.production_fee;
if (data.insurance_fee !== undefined)
updatePayload.insurance_fee = data.insurance_fee;
if (data.temp !== undefined) updatePayload.temp = data.temp;
if (data.xero_id !== undefined) updatePayload.xero_id = data.xero_id;
updatePayload.updatedById = currentUser.id;
await brands.update(updatePayload, { transaction });
if (data.client !== undefined) {
await brands.setClient(
data.client,
{ transaction },
);
}
if (data.default_account_manager !== undefined) {
await brands.setDefault_account_manager(
data.default_account_manager,
{ transaction },
);
}
if (data.default_sales !== undefined) {
await brands.setDefault_sales(
data.default_sales,
{ transaction },
);
}
if (data.link_rate_card !== undefined) {
await brands.setLink_rate_card(
data.link_rate_card,
{ transaction },
);
}
return brands;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const brands = await db.brands.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of brands) {
await record.update({ deletedBy: currentUser.id }, { transaction });
}
for (const record of brands) {
await record.destroy({ transaction });
}
});
return brands;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const brands = await db.brands.findByPk(id, options);
await brands.update(
{
deletedBy: currentUser.id,
},
{
transaction,
},
);
await brands.destroy({
transaction,
});
return brands;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const brands = await db.brands.findOne({ where }, { transaction });
if (!brands) {
return brands;
}
const output = brands.get({ plain: true });
output.brand_rate_cards_brand = await brands.getBrand_rate_cards_brand({
transaction,
});
output.client = await brands.getClient({
transaction,
});
output.default_account_manager = await brands.getDefault_account_manager({
transaction,
});
output.default_sales = await brands.getDefault_sales({
transaction,
});
output.link_rate_card = await brands.getLink_rate_card({
transaction,
});
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.clients,
as: 'client',
where: filter.client
? {
[Op.or]: [
{
id: {
[Op.in]: filter.client
.split('|')
.map((term) => Utils.uuid(term)),
},
},
{
id: {
[Op.or]: filter.client
.split('|')
.map((term) => ({ [Op.iLike]: `%${term}%` })),
},
},
],
}
: {},
},
{
model: db.users,
as: 'default_account_manager',
where: filter.default_account_manager
? {
[Op.or]: [
{
id: {
[Op.in]: filter.default_account_manager
.split('|')
.map((term) => Utils.uuid(term)),
},
},
{
firstName: {
[Op.or]: filter.default_account_manager
.split('|')
.map((term) => ({ [Op.iLike]: `%${term}%` })),
},
},
],
}
: {},
},
{
model: db.users,
as: 'default_sales',
where: filter.default_sales
? {
[Op.or]: [
{
id: {
[Op.in]: filter.default_sales
.split('|')
.map((term) => Utils.uuid(term)),
},
},
{
firstName: {
[Op.or]: filter.default_sales
.split('|')
.map((term) => ({ [Op.iLike]: `%${term}%` })),
},
},
],
}
: {},
},
{
model: db.brand_rate_cards,
as: 'link_rate_card',
where: filter.link_rate_card
? {
[Op.or]: [
{
id: {
[Op.in]: filter.link_rate_card
.split('|')
.map((term) => Utils.uuid(term)),
},
},
{
id: {
[Op.or]: filter.link_rate_card
.split('|')
.map((term) => ({ [Op.iLike]: `%${term}%` })),
},
},
],
}
: {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike('brands', 'name', filter.name),
};
}
if (filter.client_fixed_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'brands',
'client_fixed_text',
filter.client_fixed_text,
),
};
}
if (filter.yes_fixed_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'brands',
'yes_fixed_text',
filter.yes_fixed_text,
),
};
}
if (filter.default_client_contact) {
where = {
...where,
[Op.and]: Utils.ilike(
'brands',
'default_client_contact',
filter.default_client_contact,
),
};
}
if (filter.temp) {
where = {
...where,
[Op.and]: Utils.ilike('brands', 'temp', filter.temp),
};
}
if (filter.xero_id) {
where = {
...where,
[Op.and]: Utils.ilike('brands', 'xero_id', filter.xero_id),
};
}
if (filter.default_costsRange) {
const [start, end] = filter.default_costsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
default_costs: {
...where.default_costs,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
default_costs: {
...where.default_costs,
[Op.lte]: end,
},
};
}
}
if (filter.production_feeRange) {
const [start, end] = filter.production_feeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
production_fee: {
...where.production_fee,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
production_fee: {
...where.production_fee,
[Op.lte]: end,
},
};
}
}
if (filter.insurance_feeRange) {
const [start, end] = filter.insurance_feeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
insurance_fee: {
...where.insurance_fee,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
insurance_fee: {
...where.insurance_fee,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true',
};
}
if (filter.rate_card_import) {
where = {
...where,
rate_card_import: filter.rate_card_import,
};
}
if (filter.inherit_default_rate_card) {
where = {
...where,
inherit_default_rate_card: filter.inherit_default_rate_card,
};
}
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.brands.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('brands', 'id', query),
],
};
}
const records = await db.brands.findAll({
attributes: ['id', 'id'],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['id', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.id,
}));
}
};

View File

@ -0,0 +1,237 @@
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 CampaignsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const campaigns = await db.campaigns.create(
{
id: data.id || undefined,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return campaigns;
}
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 campaignsData = data.map((item, index) => ({
id: item.id || undefined,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const campaigns = await db.campaigns.bulkCreate(campaignsData, {
transaction,
});
// For each item created, replace relation files
return campaigns;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const campaigns = await db.campaigns.findByPk(id, {}, { transaction });
const updatePayload = {};
updatePayload.updatedById = currentUser.id;
await campaigns.update(updatePayload, { transaction });
return campaigns;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const campaigns = await db.campaigns.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of campaigns) {
await record.update({ deletedBy: currentUser.id }, { transaction });
}
for (const record of campaigns) {
await record.destroy({ transaction });
}
});
return campaigns;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const campaigns = await db.campaigns.findByPk(id, options);
await campaigns.update(
{
deletedBy: currentUser.id,
},
{
transaction,
},
);
await campaigns.destroy({
transaction,
});
return campaigns;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const campaigns = await db.campaigns.findOne({ where }, { transaction });
if (!campaigns) {
return campaigns;
}
const output = campaigns.get({ plain: true });
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
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.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.campaigns.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('campaigns', 'id', query),
],
};
}
const records = await db.campaigns.findAll({
attributes: ['id', 'id'],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['id', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.id,
}));
}
};

View File

@ -0,0 +1,237 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Client_damDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const client_dam = await db.client_dam.create(
{
id: data.id || undefined,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return client_dam;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const client_damData = data.map((item, index) => ({
id: item.id || undefined,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const client_dam = await db.client_dam.bulkCreate(client_damData, {
transaction,
});
// For each item created, replace relation files
return client_dam;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const client_dam = await db.client_dam.findByPk(id, {}, { transaction });
const updatePayload = {};
updatePayload.updatedById = currentUser.id;
await client_dam.update(updatePayload, { transaction });
return client_dam;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const client_dam = await db.client_dam.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of client_dam) {
await record.update({ deletedBy: currentUser.id }, { transaction });
}
for (const record of client_dam) {
await record.destroy({ transaction });
}
});
return client_dam;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const client_dam = await db.client_dam.findByPk(id, options);
await client_dam.update(
{
deletedBy: currentUser.id,
},
{
transaction,
},
);
await client_dam.destroy({
transaction,
});
return client_dam;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const client_dam = await db.client_dam.findOne({ where }, { transaction });
if (!client_dam) {
return client_dam;
}
const output = client_dam.get({ plain: true });
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
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.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.client_dam.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('client_dam', 'id', query),
],
};
}
const records = await db.client_dam.findAll({
attributes: ['id', 'id'],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['id', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.id,
}));
}
};

View File

@ -0,0 +1,339 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Client_ordersDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const client_orders = await db.client_orders.create(
{
id: data.id || undefined,
status: data.status || null,
order_name: data.order_name || null,
order_number: data.order_number || null,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await client_orders.setAssets(data.assets || [], {
transaction,
});
return client_orders;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const client_ordersData = data.map((item, index) => ({
id: item.id || undefined,
status: item.status || null,
order_name: item.order_name || null,
order_number: item.order_number || null,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const client_orders = await db.client_orders.bulkCreate(client_ordersData, {
transaction,
});
// For each item created, replace relation files
return client_orders;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const client_orders = await db.client_orders.findByPk(
id,
{},
{ transaction },
);
const updatePayload = {};
if (data.status !== undefined) updatePayload.status = data.status;
if (data.order_name !== undefined)
updatePayload.order_name = data.order_name;
if (data.order_number !== undefined)
updatePayload.order_number = data.order_number;
updatePayload.updatedById = currentUser.id;
await client_orders.update(updatePayload, { transaction });
if (data.assets !== undefined) {
await client_orders.setAssets(data.assets, { transaction });
}
return client_orders;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const client_orders = await db.client_orders.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of client_orders) {
await record.update({ deletedBy: currentUser.id }, { transaction });
}
for (const record of client_orders) {
await record.destroy({ transaction });
}
});
return client_orders;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const client_orders = await db.client_orders.findByPk(id, options);
await client_orders.update(
{
deletedBy: currentUser.id,
},
{
transaction,
},
);
await client_orders.destroy({
transaction,
});
return client_orders;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const client_orders = await db.client_orders.findOne(
{ where },
{ transaction },
);
if (!client_orders) {
return client_orders;
}
const output = client_orders.get({ plain: true });
output.assets = await client_orders.getAssets({
transaction,
});
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.client_dam,
as: 'assets',
required: false,
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.status) {
where = {
...where,
[Op.and]: Utils.ilike('client_orders', 'status', filter.status),
};
}
if (filter.order_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'client_orders',
'order_name',
filter.order_name,
),
};
}
if (filter.order_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'client_orders',
'order_number',
filter.order_number,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true',
};
}
if (filter.assets) {
const searchTerms = filter.assets.split('|');
include = [
{
model: db.client_dam,
as: 'assets_filter',
required: searchTerms.length > 0,
where:
searchTerms.length > 0
? {
[Op.or]: [
{
id: {
[Op.in]: searchTerms.map((term) => Utils.uuid(term)),
},
},
{
id: {
[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,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order:
filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log,
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.client_orders.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('client_orders', 'id', query),
],
};
}
const records = await db.client_orders.findAll({
attributes: ['id', 'id'],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['id', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.id,
}));
}
};

View File

@ -0,0 +1,656 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class 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,
thyme_id: data.thyme_id || null,
name: data.name || null,
office: data.office || null,
address: data.address || null,
city: data.city || null,
post_code: data.post_code || null,
country_txt: data.country_txt || null,
phone_number: data.phone_number || null,
website: data.website || null,
currency: data.currency || null,
curious_customer_id: data.curious_customer_id || null,
agency: data.agency || null,
inclusive_amends: data.inclusive_amends || false,
early_payment_discount: data.early_payment_discount || null,
client_id_link: data.client_id_link || null,
public_url: data.public_url || null,
production_fee: data.production_fee || null,
insurance_fee: data.insurance_fee || null,
xero_id: data.xero_id || null,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await clients.setCountry(data.country || null, {
transaction,
});
await clients.setAccount_manager(data.account_manager || null, {
transaction,
});
await clients.setAll_brands(data.all_brands || [], {
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,
thyme_id: item.thyme_id || null,
name: item.name || null,
office: item.office || null,
address: item.address || null,
city: item.city || null,
post_code: item.post_code || null,
country_txt: item.country_txt || null,
phone_number: item.phone_number || null,
website: item.website || null,
currency: item.currency || null,
curious_customer_id: item.curious_customer_id || null,
agency: item.agency || null,
inclusive_amends: item.inclusive_amends || false,
early_payment_discount: item.early_payment_discount || null,
client_id_link: item.client_id_link || null,
public_url: item.public_url || null,
production_fee: item.production_fee || null,
insurance_fee: item.insurance_fee || null,
xero_id: item.xero_id || 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 clients = await db.clients.findByPk(id, {}, { transaction });
const updatePayload = {};
if (data.thyme_id !== undefined) updatePayload.thyme_id = data.thyme_id;
if (data.name !== undefined) updatePayload.name = data.name;
if (data.office !== undefined) updatePayload.office = data.office;
if (data.address !== undefined) updatePayload.address = data.address;
if (data.city !== undefined) updatePayload.city = data.city;
if (data.post_code !== undefined) updatePayload.post_code = data.post_code;
if (data.country_txt !== undefined)
updatePayload.country_txt = data.country_txt;
if (data.phone_number !== undefined)
updatePayload.phone_number = data.phone_number;
if (data.website !== undefined) updatePayload.website = data.website;
if (data.currency !== undefined) updatePayload.currency = data.currency;
if (data.curious_customer_id !== undefined)
updatePayload.curious_customer_id = data.curious_customer_id;
if (data.agency !== undefined) updatePayload.agency = data.agency;
if (data.inclusive_amends !== undefined)
updatePayload.inclusive_amends = data.inclusive_amends;
if (data.early_payment_discount !== undefined)
updatePayload.early_payment_discount = data.early_payment_discount;
if (data.client_id_link !== undefined)
updatePayload.client_id_link = data.client_id_link;
if (data.public_url !== undefined)
updatePayload.public_url = data.public_url;
if (data.production_fee !== undefined)
updatePayload.production_fee = data.production_fee;
if (data.insurance_fee !== undefined)
updatePayload.insurance_fee = data.insurance_fee;
if (data.xero_id !== undefined) updatePayload.xero_id = data.xero_id;
updatePayload.updatedById = currentUser.id;
await clients.update(updatePayload, { transaction });
if (data.country !== undefined) {
await clients.setCountry(
data.country,
{ transaction },
);
}
if (data.account_manager !== undefined) {
await clients.setAccount_manager(
data.account_manager,
{ transaction },
);
}
if (data.all_brands !== undefined) {
await clients.setAll_brands(data.all_brands, { 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.brands_client = await clients.getBrands_client({
transaction,
});
output.brand_rate_cards_client = await clients.getBrand_rate_cards_client({
transaction,
});
output.country = await clients.getCountry({
transaction,
});
output.account_manager = await clients.getAccount_manager({
transaction,
});
output.all_brands = await clients.getAll_brands({
transaction,
});
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.countries,
as: 'country',
where: filter.country
? {
[Op.or]: [
{
id: {
[Op.in]: filter.country
.split('|')
.map((term) => Utils.uuid(term)),
},
},
{
id: {
[Op.or]: filter.country
.split('|')
.map((term) => ({ [Op.iLike]: `%${term}%` })),
},
},
],
}
: {},
},
{
model: db.users,
as: 'account_manager',
where: filter.account_manager
? {
[Op.or]: [
{
id: {
[Op.in]: filter.account_manager
.split('|')
.map((term) => Utils.uuid(term)),
},
},
{
firstName: {
[Op.or]: filter.account_manager
.split('|')
.map((term) => ({ [Op.iLike]: `%${term}%` })),
},
},
],
}
: {},
},
{
model: db.brands,
as: 'all_brands',
required: false,
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.thyme_id) {
where = {
...where,
[Op.and]: Utils.ilike('clients', 'thyme_id', filter.thyme_id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike('clients', 'name', filter.name),
};
}
if (filter.office) {
where = {
...where,
[Op.and]: Utils.ilike('clients', 'office', filter.office),
};
}
if (filter.address) {
where = {
...where,
[Op.and]: Utils.ilike('clients', 'address', filter.address),
};
}
if (filter.city) {
where = {
...where,
[Op.and]: Utils.ilike('clients', 'city', filter.city),
};
}
if (filter.post_code) {
where = {
...where,
[Op.and]: Utils.ilike('clients', 'post_code', filter.post_code),
};
}
if (filter.country_txt) {
where = {
...where,
[Op.and]: Utils.ilike('clients', 'country_txt', filter.country_txt),
};
}
if (filter.phone_number) {
where = {
...where,
[Op.and]: Utils.ilike('clients', 'phone_number', filter.phone_number),
};
}
if (filter.website) {
where = {
...where,
[Op.and]: Utils.ilike('clients', 'website', filter.website),
};
}
if (filter.currency) {
where = {
...where,
[Op.and]: Utils.ilike('clients', 'currency', filter.currency),
};
}
if (filter.curious_customer_id) {
where = {
...where,
[Op.and]: Utils.ilike(
'clients',
'curious_customer_id',
filter.curious_customer_id,
),
};
}
if (filter.agency) {
where = {
...where,
[Op.and]: Utils.ilike('clients', 'agency', filter.agency),
};
}
if (filter.client_id_link) {
where = {
...where,
[Op.and]: Utils.ilike(
'clients',
'client_id_link',
filter.client_id_link,
),
};
}
if (filter.public_url) {
where = {
...where,
[Op.and]: Utils.ilike('clients', 'public_url', filter.public_url),
};
}
if (filter.xero_id) {
where = {
...where,
[Op.and]: Utils.ilike('clients', 'xero_id', filter.xero_id),
};
}
if (filter.early_payment_discountRange) {
const [start, end] = filter.early_payment_discountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
early_payment_discount: {
...where.early_payment_discount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
early_payment_discount: {
...where.early_payment_discount,
[Op.lte]: end,
},
};
}
}
if (filter.production_feeRange) {
const [start, end] = filter.production_feeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
production_fee: {
...where.production_fee,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
production_fee: {
...where.production_fee,
[Op.lte]: end,
},
};
}
}
if (filter.insurance_feeRange) {
const [start, end] = filter.insurance_feeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
insurance_fee: {
...where.insurance_fee,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
insurance_fee: {
...where.insurance_fee,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true',
};
}
if (filter.inclusive_amends) {
where = {
...where,
inclusive_amends: filter.inclusive_amends,
};
}
if (filter.all_brands) {
const searchTerms = filter.all_brands.split('|');
include = [
{
model: db.brands,
as: 'all_brands_filter',
required: searchTerms.length > 0,
where:
searchTerms.length > 0
? {
[Op.or]: [
{
id: {
[Op.in]: searchTerms.map((term) => Utils.uuid(term)),
},
},
{
id: {
[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,
},
};
}
}
}
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) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike('clients', 'id', query),
],
};
}
const records = await db.clients.findAll({
attributes: ['id', 'id'],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['id', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.id,
}));
}
};

View File

@ -0,0 +1,283 @@
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 CountriesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const countries = await db.countries.create(
{
id: data.id || undefined,
name: data.name || null,
currency: data.currency || null,
default_prefill: data.default_prefill || null,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return countries;
}
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 countriesData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name || null,
currency: item.currency || null,
default_prefill: item.default_prefill || null,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const countries = await db.countries.bulkCreate(countriesData, {
transaction,
});
// For each item created, replace relation files
return countries;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const countries = await db.countries.findByPk(id, {}, { transaction });
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.currency !== undefined) updatePayload.currency = data.currency;
if (data.default_prefill !== undefined)
updatePayload.default_prefill = data.default_prefill;
updatePayload.updatedById = currentUser.id;
await countries.update(updatePayload, { transaction });
return countries;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const countries = await db.countries.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of countries) {
await record.update({ deletedBy: currentUser.id }, { transaction });
}
for (const record of countries) {
await record.destroy({ transaction });
}
});
return countries;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const countries = await db.countries.findByPk(id, options);
await countries.update(
{
deletedBy: currentUser.id,
},
{
transaction,
},
);
await countries.destroy({
transaction,
});
return countries;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const countries = await db.countries.findOne({ where }, { transaction });
if (!countries) {
return countries;
}
const output = countries.get({ plain: true });
output.clients_country = await countries.getClients_country({
transaction,
});
output.markets_country = await countries.getMarkets_country({
transaction,
});
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
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('countries', 'name', filter.name),
};
}
if (filter.currency) {
where = {
...where,
[Op.and]: Utils.ilike('countries', 'currency', filter.currency),
};
}
if (filter.default_prefill) {
where = {
...where,
[Op.and]: Utils.ilike(
'countries',
'default_prefill',
filter.default_prefill,
),
};
}
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.countries.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('countries', 'id', query),
],
};
}
const records = await db.countries.findAll({
attributes: ['id', 'id'],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['id', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.id,
}));
}
};

View File

@ -0,0 +1,607 @@
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 Default_activities_productsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const default_activities_products =
await db.default_activities_products.create(
{
id: data.id || undefined,
name: data.name || null,
rate_type: data.rate_type || null,
standard_service: data.standard_service || null,
service_text: data.service_text || null,
rate: data.rate || null,
service_id: data.service_id || null,
service_code: data.service_code || null,
unit_type: data.unit_type || null,
cost: data.cost || null,
qty: data.qty || null,
currency: data.currency || null,
rate_gbp: data.rate_gbp || null,
rate_eur: data.rate_eur || null,
rate_usd: data.rate_usd || null,
yes_fixed_text: data.yes_fixed_text || false,
no_fixed_text: data.no_fixed_text || false,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await default_activities_products.setDepartment(data.department || null, {
transaction,
});
return default_activities_products;
}
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 default_activities_productsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name || null,
rate_type: item.rate_type || null,
standard_service: item.standard_service || null,
service_text: item.service_text || null,
rate: item.rate || null,
service_id: item.service_id || null,
service_code: item.service_code || null,
unit_type: item.unit_type || null,
cost: item.cost || null,
qty: item.qty || null,
currency: item.currency || null,
rate_gbp: item.rate_gbp || null,
rate_eur: item.rate_eur || null,
rate_usd: item.rate_usd || null,
yes_fixed_text: item.yes_fixed_text || false,
no_fixed_text: item.no_fixed_text || false,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const default_activities_products =
await db.default_activities_products.bulkCreate(
default_activities_productsData,
{ transaction },
);
// For each item created, replace relation files
return default_activities_products;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const default_activities_products =
await db.default_activities_products.findByPk(id, {}, { transaction });
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.rate_type !== undefined) updatePayload.rate_type = data.rate_type;
if (data.standard_service !== undefined)
updatePayload.standard_service = data.standard_service;
if (data.service_text !== undefined)
updatePayload.service_text = data.service_text;
if (data.rate !== undefined) updatePayload.rate = data.rate;
if (data.service_id !== undefined)
updatePayload.service_id = data.service_id;
if (data.service_code !== undefined)
updatePayload.service_code = data.service_code;
if (data.unit_type !== undefined) updatePayload.unit_type = data.unit_type;
if (data.cost !== undefined) updatePayload.cost = data.cost;
if (data.qty !== undefined) updatePayload.qty = data.qty;
if (data.currency !== undefined) updatePayload.currency = data.currency;
if (data.rate_gbp !== undefined) updatePayload.rate_gbp = data.rate_gbp;
if (data.rate_eur !== undefined) updatePayload.rate_eur = data.rate_eur;
if (data.rate_usd !== undefined) updatePayload.rate_usd = data.rate_usd;
if (data.yes_fixed_text !== undefined)
updatePayload.yes_fixed_text = data.yes_fixed_text;
if (data.no_fixed_text !== undefined)
updatePayload.no_fixed_text = data.no_fixed_text;
updatePayload.updatedById = currentUser.id;
await default_activities_products.update(updatePayload, { transaction });
if (data.department !== undefined) {
await default_activities_products.setDepartment(
data.department,
{ transaction },
);
}
return default_activities_products;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const default_activities_products =
await db.default_activities_products.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of default_activities_products) {
await record.update({ deletedBy: currentUser.id }, { transaction });
}
for (const record of default_activities_products) {
await record.destroy({ transaction });
}
});
return default_activities_products;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const default_activities_products =
await db.default_activities_products.findByPk(id, options);
await default_activities_products.update(
{
deletedBy: currentUser.id,
},
{
transaction,
},
);
await default_activities_products.destroy({
transaction,
});
return default_activities_products;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const default_activities_products =
await db.default_activities_products.findOne({ where }, { transaction });
if (!default_activities_products) {
return default_activities_products;
}
const output = default_activities_products.get({ plain: true });
output.department = await default_activities_products.getDepartment({
transaction,
});
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.departments,
as: 'department',
where: filter.department
? {
[Op.or]: [
{
id: {
[Op.in]: filter.department
.split('|')
.map((term) => Utils.uuid(term)),
},
},
{
id: {
[Op.or]: filter.department
.split('|')
.map((term) => ({ [Op.iLike]: `%${term}%` })),
},
},
],
}
: {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'default_activities_products',
'name',
filter.name,
),
};
}
if (filter.rate_type) {
where = {
...where,
[Op.and]: Utils.ilike(
'default_activities_products',
'rate_type',
filter.rate_type,
),
};
}
if (filter.standard_service) {
where = {
...where,
[Op.and]: Utils.ilike(
'default_activities_products',
'standard_service',
filter.standard_service,
),
};
}
if (filter.service_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'default_activities_products',
'service_text',
filter.service_text,
),
};
}
if (filter.service_id) {
where = {
...where,
[Op.and]: Utils.ilike(
'default_activities_products',
'service_id',
filter.service_id,
),
};
}
if (filter.service_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'default_activities_products',
'service_code',
filter.service_code,
),
};
}
if (filter.unit_type) {
where = {
...where,
[Op.and]: Utils.ilike(
'default_activities_products',
'unit_type',
filter.unit_type,
),
};
}
if (filter.currency) {
where = {
...where,
[Op.and]: Utils.ilike(
'default_activities_products',
'currency',
filter.currency,
),
};
}
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.costRange) {
const [start, end] = filter.costRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
cost: {
...where.cost,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
cost: {
...where.cost,
[Op.lte]: end,
},
};
}
}
if (filter.qtyRange) {
const [start, end] = filter.qtyRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
qty: {
...where.qty,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
qty: {
...where.qty,
[Op.lte]: end,
},
};
}
}
if (filter.rate_gbpRange) {
const [start, end] = filter.rate_gbpRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
rate_gbp: {
...where.rate_gbp,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
rate_gbp: {
...where.rate_gbp,
[Op.lte]: end,
},
};
}
}
if (filter.rate_eurRange) {
const [start, end] = filter.rate_eurRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
rate_eur: {
...where.rate_eur,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
rate_eur: {
...where.rate_eur,
[Op.lte]: end,
},
};
}
}
if (filter.rate_usdRange) {
const [start, end] = filter.rate_usdRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
rate_usd: {
...where.rate_usd,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
rate_usd: {
...where.rate_usd,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true',
};
}
if (filter.yes_fixed_text) {
where = {
...where,
yes_fixed_text: filter.yes_fixed_text,
};
}
if (filter.no_fixed_text) {
where = {
...where,
no_fixed_text: filter.no_fixed_text,
};
}
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.default_activities_products.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('default_activities_products', 'id', query),
],
};
}
const records = await db.default_activities_products.findAll({
attributes: ['id', 'id'],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['id', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.id,
}));
}
};

View File

@ -0,0 +1,269 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class DepartmentsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const departments = await db.departments.create(
{
id: data.id || undefined,
name: data.name || null,
timing_id: data.timing_id || null,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return departments;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const departmentsData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name || null,
timing_id: item.timing_id || null,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const departments = await db.departments.bulkCreate(departmentsData, {
transaction,
});
// For each item created, replace relation files
return departments;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const departments = await db.departments.findByPk(id, {}, { transaction });
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.timing_id !== undefined) updatePayload.timing_id = data.timing_id;
updatePayload.updatedById = currentUser.id;
await departments.update(updatePayload, { transaction });
return departments;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const departments = await db.departments.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of departments) {
await record.update({ deletedBy: currentUser.id }, { transaction });
}
for (const record of departments) {
await record.destroy({ transaction });
}
});
return departments;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const departments = await db.departments.findByPk(id, options);
await departments.update(
{
deletedBy: currentUser.id,
},
{
transaction,
},
);
await departments.destroy({
transaction,
});
return departments;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const departments = await db.departments.findOne(
{ where },
{ transaction },
);
if (!departments) {
return departments;
}
const output = departments.get({ plain: true });
output.default_activities_products_department =
await departments.getDefault_activities_products_department({
transaction,
});
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
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('departments', 'name', filter.name),
};
}
if (filter.timing_id) {
where = {
...where,
[Op.and]: Utils.ilike('departments', 'timing_id', filter.timing_id),
};
}
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.departments.findAndCountAll(
queryOptions,
);
return {
rows: options?.countOnly ? [] : rows,
count: count,
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike('departments', 'id', query),
],
};
}
const records = await db.departments.findAll({
attributes: ['id', 'id'],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['id', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.id,
}));
}
};

View File

@ -0,0 +1,73 @@
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,288 @@
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 MarketsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const markets = await db.markets.create(
{
id: data.id || undefined,
market: data.market || null,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await markets.setCountry(data.country || null, {
transaction,
});
return markets;
}
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 marketsData = data.map((item, index) => ({
id: item.id || undefined,
market: item.market || null,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const markets = await db.markets.bulkCreate(marketsData, { transaction });
// For each item created, replace relation files
return markets;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const markets = await db.markets.findByPk(id, {}, { transaction });
const updatePayload = {};
if (data.market !== undefined) updatePayload.market = data.market;
updatePayload.updatedById = currentUser.id;
await markets.update(updatePayload, { transaction });
if (data.country !== undefined) {
await markets.setCountry(
data.country,
{ transaction },
);
}
return markets;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const markets = await db.markets.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of markets) {
await record.update({ deletedBy: currentUser.id }, { transaction });
}
for (const record of markets) {
await record.destroy({ transaction });
}
});
return markets;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const markets = await db.markets.findByPk(id, options);
await markets.update(
{
deletedBy: currentUser.id,
},
{
transaction,
},
);
await markets.destroy({
transaction,
});
return markets;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const markets = await db.markets.findOne({ where }, { transaction });
if (!markets) {
return markets;
}
const output = markets.get({ plain: true });
output.country = await markets.getCountry({
transaction,
});
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.countries,
as: 'country',
where: filter.country
? {
[Op.or]: [
{
id: {
[Op.in]: filter.country
.split('|')
.map((term) => Utils.uuid(term)),
},
},
{
id: {
[Op.or]: filter.country
.split('|')
.map((term) => ({ [Op.iLike]: `%${term}%` })),
},
},
],
}
: {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.market) {
where = {
...where,
[Op.and]: Utils.ilike('markets', 'market', filter.market),
};
}
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.markets.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('markets', 'id', query),
],
};
}
const records = await db.markets.findAll({
attributes: ['id', 'id'],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['id', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.id,
}));
}
};

View File

@ -0,0 +1,257 @@
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 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 });
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
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,
},
};
}
}
}
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) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike('organizations', 'id', query),
],
};
}
const records = await db.organizations.findAll({
attributes: ['id', 'id'],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['id', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.id,
}));
}
};

View File

@ -0,0 +1,235 @@
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 OutworkDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const outwork = await db.outwork.create(
{
id: data.id || undefined,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return outwork;
}
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 outworkData = data.map((item, index) => ({
id: item.id || undefined,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const outwork = await db.outwork.bulkCreate(outworkData, { transaction });
// For each item created, replace relation files
return outwork;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const outwork = await db.outwork.findByPk(id, {}, { transaction });
const updatePayload = {};
updatePayload.updatedById = currentUser.id;
await outwork.update(updatePayload, { transaction });
return outwork;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const outwork = await db.outwork.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of outwork) {
await record.update({ deletedBy: currentUser.id }, { transaction });
}
for (const record of outwork) {
await record.destroy({ transaction });
}
});
return outwork;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const outwork = await db.outwork.findByPk(id, options);
await outwork.update(
{
deletedBy: currentUser.id,
},
{
transaction,
},
);
await outwork.destroy({
transaction,
});
return outwork;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const outwork = await db.outwork.findOne({ where }, { transaction });
if (!outwork) {
return outwork;
}
const output = outwork.get({ plain: true });
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
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.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.outwork.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('outwork', 'id', query),
],
};
}
const records = await db.outwork.findAll({
attributes: ['id', 'id'],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['id', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.id,
}));
}
};

View File

@ -0,0 +1,250 @@
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 Outwork_line_itemsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const outwork_line_items = await db.outwork_line_items.create(
{
id: data.id || undefined,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return outwork_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 outwork_line_itemsData = data.map((item, index) => ({
id: item.id || undefined,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const outwork_line_items = await db.outwork_line_items.bulkCreate(
outwork_line_itemsData,
{ transaction },
);
// For each item created, replace relation files
return outwork_line_items;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const outwork_line_items = await db.outwork_line_items.findByPk(
id,
{},
{ transaction },
);
const updatePayload = {};
updatePayload.updatedById = currentUser.id;
await outwork_line_items.update(updatePayload, { transaction });
return outwork_line_items;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const outwork_line_items = await db.outwork_line_items.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of outwork_line_items) {
await record.update({ deletedBy: currentUser.id }, { transaction });
}
for (const record of outwork_line_items) {
await record.destroy({ transaction });
}
});
return outwork_line_items;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const outwork_line_items = await db.outwork_line_items.findByPk(
id,
options,
);
await outwork_line_items.update(
{
deletedBy: currentUser.id,
},
{
transaction,
},
);
await outwork_line_items.destroy({
transaction,
});
return outwork_line_items;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const outwork_line_items = await db.outwork_line_items.findOne(
{ where },
{ transaction },
);
if (!outwork_line_items) {
return outwork_line_items;
}
const output = outwork_line_items.get({ plain: true });
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
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.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.outwork_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) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike('outwork_line_items', 'id', query),
],
};
}
const records = await db.outwork_line_items.findAll({
attributes: ['id', 'id'],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['id', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.id,
}));
}
};

View File

@ -0,0 +1,253 @@
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 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;
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,235 @@
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 QuotesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const quotes = await db.quotes.create(
{
id: data.id || undefined,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return quotes;
}
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 quotesData = data.map((item, index) => ({
id: item.id || undefined,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const quotes = await db.quotes.bulkCreate(quotesData, { transaction });
// For each item created, replace relation files
return quotes;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const quotes = await db.quotes.findByPk(id, {}, { transaction });
const updatePayload = {};
updatePayload.updatedById = currentUser.id;
await quotes.update(updatePayload, { transaction });
return quotes;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const quotes = await db.quotes.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of quotes) {
await record.update({ deletedBy: currentUser.id }, { transaction });
}
for (const record of quotes) {
await record.destroy({ transaction });
}
});
return quotes;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const quotes = await db.quotes.findByPk(id, options);
await quotes.update(
{
deletedBy: currentUser.id,
},
{
transaction,
},
);
await quotes.destroy({
transaction,
});
return quotes;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const quotes = await db.quotes.findOne({ where }, { transaction });
if (!quotes) {
return quotes;
}
const output = quotes.get({ plain: true });
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
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.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.quotes.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('quotes', 'id', query),
],
};
}
const records = await db.quotes.findAll({
attributes: ['id', 'id'],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['id', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.id,
}));
}
};

View File

@ -0,0 +1,235 @@
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 ReportsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const reports = await db.reports.create(
{
id: data.id || undefined,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return reports;
}
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 reportsData = data.map((item, index) => ({
id: item.id || undefined,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const reports = await db.reports.bulkCreate(reportsData, { transaction });
// For each item created, replace relation files
return reports;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const reports = await db.reports.findByPk(id, {}, { transaction });
const updatePayload = {};
updatePayload.updatedById = currentUser.id;
await reports.update(updatePayload, { transaction });
return reports;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const reports = await db.reports.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of reports) {
await record.update({ deletedBy: currentUser.id }, { transaction });
}
for (const record of reports) {
await record.destroy({ transaction });
}
});
return reports;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const reports = await db.reports.findByPk(id, options);
await reports.update(
{
deletedBy: currentUser.id,
},
{
transaction,
},
);
await reports.destroy({
transaction,
});
return reports;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const reports = await db.reports.findOne({ where }, { transaction });
if (!reports) {
return reports;
}
const output = reports.get({ plain: true });
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
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.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.reports.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('reports', 'id', query),
],
};
}
const records = await db.reports.findAll({
attributes: ['id', 'id'],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['id', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.id,
}));
}
};

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

@ -0,0 +1,316 @@
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 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,
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,
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 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;
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, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
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.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,
},
};
}
}
}
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) {
let where = {};
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,247 @@
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 Saved_adaptationsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const saved_adaptations = await db.saved_adaptations.create(
{
id: data.id || undefined,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return saved_adaptations;
}
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 saved_adaptationsData = data.map((item, index) => ({
id: item.id || undefined,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const saved_adaptations = await db.saved_adaptations.bulkCreate(
saved_adaptationsData,
{ transaction },
);
// For each item created, replace relation files
return saved_adaptations;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const saved_adaptations = await db.saved_adaptations.findByPk(
id,
{},
{ transaction },
);
const updatePayload = {};
updatePayload.updatedById = currentUser.id;
await saved_adaptations.update(updatePayload, { transaction });
return saved_adaptations;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const saved_adaptations = await db.saved_adaptations.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of saved_adaptations) {
await record.update({ deletedBy: currentUser.id }, { transaction });
}
for (const record of saved_adaptations) {
await record.destroy({ transaction });
}
});
return saved_adaptations;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const saved_adaptations = await db.saved_adaptations.findByPk(id, options);
await saved_adaptations.update(
{
deletedBy: currentUser.id,
},
{
transaction,
},
);
await saved_adaptations.destroy({
transaction,
});
return saved_adaptations;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const saved_adaptations = await db.saved_adaptations.findOne(
{ where },
{ transaction },
);
if (!saved_adaptations) {
return saved_adaptations;
}
const output = saved_adaptations.get({ plain: true });
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
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.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.saved_adaptations.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('saved_adaptations', 'id', query),
],
};
}
const records = await db.saved_adaptations.findAll({
attributes: ['id', 'id'],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['id', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.id,
}));
}
};

View File

@ -0,0 +1,247 @@
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 Specs_databaseDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const specs_database = await db.specs_database.create(
{
id: data.id || undefined,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return specs_database;
}
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 specs_databaseData = data.map((item, index) => ({
id: item.id || undefined,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const specs_database = await db.specs_database.bulkCreate(
specs_databaseData,
{ transaction },
);
// For each item created, replace relation files
return specs_database;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const specs_database = await db.specs_database.findByPk(
id,
{},
{ transaction },
);
const updatePayload = {};
updatePayload.updatedById = currentUser.id;
await specs_database.update(updatePayload, { transaction });
return specs_database;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const specs_database = await db.specs_database.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of specs_database) {
await record.update({ deletedBy: currentUser.id }, { transaction });
}
for (const record of specs_database) {
await record.destroy({ transaction });
}
});
return specs_database;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const specs_database = await db.specs_database.findByPk(id, options);
await specs_database.update(
{
deletedBy: currentUser.id,
},
{
transaction,
},
);
await specs_database.destroy({
transaction,
});
return specs_database;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const specs_database = await db.specs_database.findOne(
{ where },
{ transaction },
);
if (!specs_database) {
return specs_database;
}
const output = specs_database.get({ plain: true });
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
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.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.specs_database.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('specs_database', 'id', query),
],
};
}
const records = await db.specs_database.findAll({
attributes: ['id', 'id'],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['id', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.id,
}));
}
};

View File

@ -0,0 +1,237 @@
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 SuppliersDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const suppliers = await db.suppliers.create(
{
id: data.id || undefined,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return suppliers;
}
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 suppliersData = data.map((item, index) => ({
id: item.id || undefined,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const suppliers = await db.suppliers.bulkCreate(suppliersData, {
transaction,
});
// For each item created, replace relation files
return suppliers;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const suppliers = await db.suppliers.findByPk(id, {}, { transaction });
const updatePayload = {};
updatePayload.updatedById = currentUser.id;
await suppliers.update(updatePayload, { transaction });
return suppliers;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const suppliers = await db.suppliers.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of suppliers) {
await record.update({ deletedBy: currentUser.id }, { transaction });
}
for (const record of suppliers) {
await record.destroy({ transaction });
}
});
return suppliers;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const suppliers = await db.suppliers.findByPk(id, options);
await suppliers.update(
{
deletedBy: currentUser.id,
},
{
transaction,
},
);
await suppliers.destroy({
transaction,
});
return suppliers;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const suppliers = await db.suppliers.findOne({ where }, { transaction });
if (!suppliers) {
return suppliers;
}
const output = suppliers.get({ plain: true });
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
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.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.suppliers.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('suppliers', 'id', query),
],
};
}
const records = await db.suppliers.findAll({
attributes: ['id', 'id'],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['id', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.id,
}));
}
};

View File

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

View File

@ -0,0 +1,250 @@
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 Tracking_categoriesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const tracking_categories = await db.tracking_categories.create(
{
id: data.id || undefined,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return tracking_categories;
}
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 tracking_categoriesData = data.map((item, index) => ({
id: item.id || undefined,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const tracking_categories = await db.tracking_categories.bulkCreate(
tracking_categoriesData,
{ transaction },
);
// For each item created, replace relation files
return tracking_categories;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const tracking_categories = await db.tracking_categories.findByPk(
id,
{},
{ transaction },
);
const updatePayload = {};
updatePayload.updatedById = currentUser.id;
await tracking_categories.update(updatePayload, { transaction });
return tracking_categories;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const tracking_categories = await db.tracking_categories.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of tracking_categories) {
await record.update({ deletedBy: currentUser.id }, { transaction });
}
for (const record of tracking_categories) {
await record.destroy({ transaction });
}
});
return tracking_categories;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const tracking_categories = await db.tracking_categories.findByPk(
id,
options,
);
await tracking_categories.update(
{
deletedBy: currentUser.id,
},
{
transaction,
},
);
await tracking_categories.destroy({
transaction,
});
return tracking_categories;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const tracking_categories = await db.tracking_categories.findOne(
{ where },
{ transaction },
);
if (!tracking_categories) {
return tracking_categories;
}
const output = tracking_categories.get({ plain: true });
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
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.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.tracking_categories.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('tracking_categories', 'id', query),
],
};
}
const records = await db.tracking_categories.findAll({
attributes: ['id', 'id'],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['id', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.id,
}));
}
};

767
backend/src/db/api/users.js Normal file
View File

@ -0,0 +1,767 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const bcrypt = require('bcrypt');
const config = require('../../config');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class UsersDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const users = await db.users.create(
{
id: data.data.id || undefined,
firstName: data.data.firstName || null,
lastName: data.data.lastName || null,
phoneNumber: data.data.phoneNumber || null,
email: data.data.email || null,
disabled: data.data.disabled || false,
password: data.data.password || null,
emailVerified: data.data.emailVerified || true,
emailVerificationToken: data.data.emailVerificationToken || null,
emailVerificationTokenExpiresAt:
data.data.emailVerificationTokenExpiresAt || null,
passwordResetToken: data.data.passwordResetToken || null,
passwordResetTokenExpiresAt:
data.data.passwordResetTokenExpiresAt || null,
provider: data.data.provider || null,
clientId: data.data.clientId || null,
importHash: data.data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
if (!data.data.app_role) {
const role = await db.roles.findOne({
where: { name: 'User' },
});
if (role) {
await users.setApp_role(role, {
transaction,
});
}
} else {
await users.setApp_role(data.data.app_role || null, {
transaction,
});
}
await users.setCustom_permissions(data.data.custom_permissions || [], {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.users.getTableName(),
belongsToColumn: 'avatar',
belongsToId: users.id,
},
data.data.avatar,
options,
);
return users;
}
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 usersData = data.map((item, index) => ({
id: item.id || undefined,
firstName: item.firstName || null,
lastName: item.lastName || null,
phoneNumber: item.phoneNumber || null,
email: item.email || null,
disabled: item.disabled || false,
password: item.password || null,
emailVerified: item.emailVerified || false,
emailVerificationToken: item.emailVerificationToken || null,
emailVerificationTokenExpiresAt:
item.emailVerificationTokenExpiresAt || null,
passwordResetToken: item.passwordResetToken || null,
passwordResetTokenExpiresAt: item.passwordResetTokenExpiresAt || null,
provider: item.provider || null,
clientId: item.clientId || null,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const users = await db.users.bulkCreate(usersData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < users.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.users.getTableName(),
belongsToColumn: 'avatar',
belongsToId: users[i].id,
},
data[i].avatar,
options,
);
}
return users;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const users = await db.users.findByPk(id, {}, { transaction });
if (!data?.app_role) {
data.app_role = users?.app_role?.id;
}
if (!data?.custom_permissions) {
data.custom_permissions = users?.custom_permissions?.map(
(item) => item.id,
);
}
if (data.password) {
data.password = bcrypt.hashSync(data.password, config.bcrypt.saltRounds);
} else {
data.password = users.password;
}
const updatePayload = {};
if (data.firstName !== undefined) updatePayload.firstName = data.firstName;
if (data.lastName !== undefined) updatePayload.lastName = data.lastName;
if (data.phoneNumber !== undefined)
updatePayload.phoneNumber = data.phoneNumber;
if (data.email !== undefined) updatePayload.email = data.email;
if (data.disabled !== undefined) updatePayload.disabled = data.disabled;
if (data.password !== undefined) updatePayload.password = data.password;
if (data.emailVerified !== undefined)
updatePayload.emailVerified = data.emailVerified;
else updatePayload.emailVerified = true;
if (data.emailVerificationToken !== undefined)
updatePayload.emailVerificationToken = data.emailVerificationToken;
if (data.emailVerificationTokenExpiresAt !== undefined)
updatePayload.emailVerificationTokenExpiresAt =
data.emailVerificationTokenExpiresAt;
if (data.passwordResetToken !== undefined)
updatePayload.passwordResetToken = data.passwordResetToken;
if (data.passwordResetTokenExpiresAt !== undefined)
updatePayload.passwordResetTokenExpiresAt =
data.passwordResetTokenExpiresAt;
if (data.provider !== undefined) updatePayload.provider = data.provider;
if (data.clientId !== undefined) updatePayload.clientId = data.clientId;
updatePayload.updatedById = currentUser.id;
await users.update(updatePayload, { transaction });
if (data.app_role !== undefined) {
await users.setApp_role(
data.app_role,
{ transaction },
);
}
if (data.custom_permissions !== undefined) {
await users.setCustom_permissions(data.custom_permissions, {
transaction,
});
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.users.getTableName(),
belongsToColumn: 'avatar',
belongsToId: users.id,
},
data.avatar,
options,
);
return users;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const users = await db.users.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of users) {
await record.update({ deletedBy: currentUser.id }, { transaction });
}
for (const record of users) {
await record.destroy({ transaction });
}
});
return users;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const users = await db.users.findByPk(id, options);
await users.update(
{
deletedBy: currentUser.id,
},
{
transaction,
},
);
await users.destroy({
transaction,
});
return users;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const users = await db.users.findOne({ where }, { transaction });
if (!users) {
return users;
}
const output = users.get({ plain: true });
output.brands_default_account_manager =
await users.getBrands_default_account_manager({
transaction,
});
output.brands_default_sales = await users.getBrands_default_sales({
transaction,
});
output.clients_account_manager = await users.getClients_account_manager({
transaction,
});
output.avatar = await users.getAvatar({
transaction,
});
output.app_role = await users.getApp_role({
transaction,
});
if (output.app_role) {
output.app_role_permissions = await output.app_role.getPermissions({
transaction,
});
}
output.custom_permissions = await users.getCustom_permissions({
transaction,
});
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.roles,
as: 'app_role',
where: filter.app_role
? {
[Op.or]: [
{
id: {
[Op.in]: filter.app_role
.split('|')
.map((term) => Utils.uuid(term)),
},
},
{
name: {
[Op.or]: filter.app_role
.split('|')
.map((term) => ({ [Op.iLike]: `%${term}%` })),
},
},
],
}
: {},
},
{
model: db.permissions,
as: 'custom_permissions',
required: false,
},
{
model: db.file,
as: 'avatar',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.firstName) {
where = {
...where,
[Op.and]: Utils.ilike('users', 'firstName', filter.firstName),
};
}
if (filter.lastName) {
where = {
...where,
[Op.and]: Utils.ilike('users', 'lastName', filter.lastName),
};
}
if (filter.phoneNumber) {
where = {
...where,
[Op.and]: Utils.ilike('users', 'phoneNumber', filter.phoneNumber),
};
}
if (filter.email) {
where = {
...where,
[Op.and]: Utils.ilike('users', 'email', filter.email),
};
}
if (filter.password) {
where = {
...where,
[Op.and]: Utils.ilike('users', 'password', filter.password),
};
}
if (filter.emailVerificationToken) {
where = {
...where,
[Op.and]: Utils.ilike(
'users',
'emailVerificationToken',
filter.emailVerificationToken,
),
};
}
if (filter.passwordResetToken) {
where = {
...where,
[Op.and]: Utils.ilike(
'users',
'passwordResetToken',
filter.passwordResetToken,
),
};
}
if (filter.provider) {
where = {
...where,
[Op.and]: Utils.ilike('users', 'provider', filter.provider),
};
}
if (filter.clientId) {
where = {
...where,
[Op.and]: Utils.ilike('users', 'clientId', filter.clientId),
};
}
if (filter.emailVerificationTokenExpiresAtRange) {
const [start, end] = filter.emailVerificationTokenExpiresAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
emailVerificationTokenExpiresAt: {
...where.emailVerificationTokenExpiresAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
emailVerificationTokenExpiresAt: {
...where.emailVerificationTokenExpiresAt,
[Op.lte]: end,
},
};
}
}
if (filter.passwordResetTokenExpiresAtRange) {
const [start, end] = filter.passwordResetTokenExpiresAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
passwordResetTokenExpiresAt: {
...where.passwordResetTokenExpiresAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
passwordResetTokenExpiresAt: {
...where.passwordResetTokenExpiresAt,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true',
};
}
if (filter.disabled) {
where = {
...where,
disabled: filter.disabled,
};
}
if (filter.emailVerified) {
where = {
...where,
emailVerified: filter.emailVerified,
};
}
if (filter.custom_permissions) {
const searchTerms = filter.custom_permissions.split('|');
include = [
{
model: db.permissions,
as: 'custom_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,
},
};
}
}
}
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.users.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('users', 'firstName', query),
],
};
}
const records = await db.users.findAll({
attributes: ['id', 'firstName'],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['firstName', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.firstName,
}));
}
static async createFromAuth(data, options) {
const transaction = (options && options.transaction) || undefined;
const users = await db.users.create(
{
email: data.email,
firstName: data.firstName,
authenticationUid: data.authenticationUid,
password: data.password,
},
{ transaction },
);
const app_role = await db.roles.findOne({
where: { name: config.roles?.user || 'User' },
});
if (app_role?.id) {
await users.setApp_role(app_role?.id || null, {
transaction,
});
}
await users.update(
{
authenticationUid: users.id,
},
{ transaction },
);
delete users.password;
return users;
}
static async updatePassword(id, password, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const users = await db.users.findByPk(id, {
transaction,
});
await users.update(
{
password,
authenticationUid: id,
updatedById: currentUser.id,
},
{ transaction },
);
return users;
}
static async generateEmailVerificationToken(email, options) {
return this._generateToken(
['emailVerificationToken', 'emailVerificationTokenExpiresAt'],
email,
options,
);
}
static async generatePasswordResetToken(email, options) {
return this._generateToken(
['passwordResetToken', 'passwordResetTokenExpiresAt'],
email,
options,
);
}
static async findByPasswordResetToken(token, options) {
const transaction = (options && options.transaction) || undefined;
return db.users.findOne(
{
where: {
passwordResetToken: token,
passwordResetTokenExpiresAt: {
[db.Sequelize.Op.gt]: Date.now(),
},
},
},
{ transaction },
);
}
static async findByEmailVerificationToken(token, options) {
const transaction = (options && options.transaction) || undefined;
return db.users.findOne(
{
where: {
emailVerificationToken: token,
emailVerificationTokenExpiresAt: {
[db.Sequelize.Op.gt]: Date.now(),
},
},
},
{ transaction },
);
}
static async markEmailVerified(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const users = await db.users.findByPk(id, {
transaction,
});
await users.update(
{
emailVerified: true,
updatedById: currentUser.id,
},
{ transaction },
);
return true;
}
static async _generateToken(keyNames, email, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const users = await db.users.findOne(
{
where: { email: email.toLowerCase() },
},
{
transaction,
},
);
const token = crypto.randomBytes(20).toString('hex');
const tokenExpiresAt = Date.now() + 360000;
if (users) {
await users.update(
{
[keyNames[0]]: token,
[keyNames[1]]: tokenExpiresAt,
updatedById: currentUser.id,
},
{ transaction },
);
}
return token;
}
};

View File

@ -0,0 +1,247 @@
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 Zipflow_workflowsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const zipflow_workflows = await db.zipflow_workflows.create(
{
id: data.id || undefined,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return zipflow_workflows;
}
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 zipflow_workflowsData = data.map((item, index) => ({
id: item.id || undefined,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const zipflow_workflows = await db.zipflow_workflows.bulkCreate(
zipflow_workflowsData,
{ transaction },
);
// For each item created, replace relation files
return zipflow_workflows;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const zipflow_workflows = await db.zipflow_workflows.findByPk(
id,
{},
{ transaction },
);
const updatePayload = {};
updatePayload.updatedById = currentUser.id;
await zipflow_workflows.update(updatePayload, { transaction });
return zipflow_workflows;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const zipflow_workflows = await db.zipflow_workflows.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of zipflow_workflows) {
await record.update({ deletedBy: currentUser.id }, { transaction });
}
for (const record of zipflow_workflows) {
await record.destroy({ transaction });
}
});
return zipflow_workflows;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const zipflow_workflows = await db.zipflow_workflows.findByPk(id, options);
await zipflow_workflows.update(
{
deletedBy: currentUser.id,
},
{
transaction,
},
);
await zipflow_workflows.destroy({
transaction,
});
return zipflow_workflows;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const zipflow_workflows = await db.zipflow_workflows.findOne(
{ where },
{ transaction },
);
if (!zipflow_workflows) {
return zipflow_workflows;
}
const output = zipflow_workflows.get({ plain: true });
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
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.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.zipflow_workflows.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('zipflow_workflows', 'id', query),
],
};
}
const records = await db.zipflow_workflows.findAll({
attributes: ['id', 'id'],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['id', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.id,
}));
}
};

View File

@ -0,0 +1,31 @@
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_curiousdemo',
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,594 @@
module.exports = {
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async up(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.addColumn(
'organizations',
'name',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await queryInterface.addColumn(
'brands',
'clientId',
{
type: Sequelize.DataTypes.UUID,
references: {
model: 'clients',
key: 'id',
},
},
{ transaction },
);
await queryInterface.addColumn(
'brands',
'name',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await queryInterface.addColumn(
'brands',
'rate_card_import',
{
type: Sequelize.DataTypes.BOOLEAN,
defaultValue: false,
allowNull: false,
},
{ transaction },
);
await queryInterface.addColumn(
'brands',
'client_fixed_text',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await queryInterface.addColumn(
'brands',
'yes_fixed_text',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await queryInterface.addColumn(
'brands',
'default_client_contact',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await queryInterface.addColumn(
'brands',
'default_account_managerId',
{
type: Sequelize.DataTypes.UUID,
references: {
model: 'users',
key: 'id',
},
},
{ transaction },
);
await queryInterface.addColumn(
'brands',
'default_salesId',
{
type: Sequelize.DataTypes.UUID,
references: {
model: 'users',
key: 'id',
},
},
{ transaction },
);
await queryInterface.addColumn(
'brands',
'inherit_default_rate_card',
{
type: Sequelize.DataTypes.BOOLEAN,
defaultValue: false,
allowNull: false,
},
{ transaction },
);
await queryInterface.addColumn(
'brands',
'link_rate_cardId',
{
type: Sequelize.DataTypes.UUID,
references: {
model: 'brand_rate_cards',
key: 'id',
},
},
{ transaction },
);
await queryInterface.addColumn(
'brands',
'default_costs',
{
type: Sequelize.DataTypes.DECIMAL,
},
{ transaction },
);
await queryInterface.addColumn(
'brands',
'production_fee',
{
type: Sequelize.DataTypes.DECIMAL,
},
{ transaction },
);
await queryInterface.addColumn(
'brands',
'insurance_fee',
{
type: Sequelize.DataTypes.DECIMAL,
},
{ transaction },
);
await queryInterface.addColumn(
'brands',
'temp',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await queryInterface.addColumn(
'brands',
'xero_id',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await queryInterface.addColumn(
'brand_rate_cards',
'name',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await queryInterface.addColumn(
'brand_rate_cards',
'rate_card_type',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await queryInterface.addColumn(
'brand_rate_cards',
'clientId',
{
type: Sequelize.DataTypes.UUID,
references: {
model: 'clients',
key: 'id',
},
},
{ transaction },
);
await queryInterface.addColumn(
'brand_rate_cards',
'brandId',
{
type: Sequelize.DataTypes.UUID,
references: {
model: 'brands',
key: 'id',
},
},
{ transaction },
);
await queryInterface.addColumn(
'brand_rate_cards',
'status',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await queryInterface.addColumn(
'brand_rate_cards',
'currency',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await queryInterface.addColumn(
'brand_rate_cards',
'push_new_values',
{
type: Sequelize.DataTypes.BOOLEAN,
defaultValue: false,
allowNull: false,
},
{ transaction },
);
await queryInterface.addColumn(
'brand_rate_cards',
'inherit_default_rate_card',
{
type: Sequelize.DataTypes.BOOLEAN,
defaultValue: false,
allowNull: false,
},
{ transaction },
);
await queryInterface.addColumn(
'brand_rate_cards',
'service_count',
{
type: Sequelize.DataTypes.INTEGER,
},
{ transaction },
);
await queryInterface.addColumn(
'brand_rate_cards',
'discipline',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await queryInterface.addColumn(
'brand_rate_cards',
'output_channel',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await queryInterface.addColumn(
'brand_rate_cards',
'staff_skills',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await queryInterface.addColumn(
'brand_rate_cards',
'rate_card_owner',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await queryInterface.addColumn(
'brand_rate_cards',
'rate_card_id',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await queryInterface.addColumn(
'brand_rate_cards',
'markets',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await queryInterface.addColumn(
'brand_rate_cards',
'languages',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await queryInterface.addColumn(
'brand_rate_cards',
'valid_from',
{
type: Sequelize.DataTypes.DATEONLY,
},
{ transaction },
);
await queryInterface.addColumn(
'brand_rate_cards',
'valid_to',
{
type: Sequelize.DataTypes.DATEONLY,
},
{ transaction },
);
await queryInterface.addColumn(
'brand_rate_cards',
'version_number',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await queryInterface.addColumn(
'brand_rate_cards',
'commercial_owner',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await queryInterface.addColumn(
'brand_rate_cards',
'review_date',
{
type: Sequelize.DataTypes.DATEONLY,
},
{ transaction },
);
await queryInterface.addColumn(
'brand_rate_cards',
'assumptions',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await queryInterface.addColumn(
'brand_rate_cards',
'no_fixed_text',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await queryInterface.addColumn(
'brand_rate_cards',
'yes_fixed_text',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async down(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.removeColumn('brand_rate_cards', 'yes_fixed_text', {
transaction,
});
await queryInterface.removeColumn('brand_rate_cards', 'no_fixed_text', {
transaction,
});
await queryInterface.removeColumn('brand_rate_cards', 'assumptions', {
transaction,
});
await queryInterface.removeColumn('brand_rate_cards', 'review_date', {
transaction,
});
await queryInterface.removeColumn(
'brand_rate_cards',
'commercial_owner',
{ transaction },
);
await queryInterface.removeColumn('brand_rate_cards', 'version_number', {
transaction,
});
await queryInterface.removeColumn('brand_rate_cards', 'valid_to', {
transaction,
});
await queryInterface.removeColumn('brand_rate_cards', 'valid_from', {
transaction,
});
await queryInterface.removeColumn('brand_rate_cards', 'languages', {
transaction,
});
await queryInterface.removeColumn('brand_rate_cards', 'markets', {
transaction,
});
await queryInterface.removeColumn('brand_rate_cards', 'rate_card_id', {
transaction,
});
await queryInterface.removeColumn('brand_rate_cards', 'rate_card_owner', {
transaction,
});
await queryInterface.removeColumn('brand_rate_cards', 'staff_skills', {
transaction,
});
await queryInterface.removeColumn('brand_rate_cards', 'output_channel', {
transaction,
});
await queryInterface.removeColumn('brand_rate_cards', 'discipline', {
transaction,
});
await queryInterface.removeColumn('brand_rate_cards', 'service_count', {
transaction,
});
await queryInterface.removeColumn(
'brand_rate_cards',
'inherit_default_rate_card',
{ transaction },
);
await queryInterface.removeColumn('brand_rate_cards', 'push_new_values', {
transaction,
});
await queryInterface.removeColumn('brand_rate_cards', 'currency', {
transaction,
});
await queryInterface.removeColumn('brand_rate_cards', 'status', {
transaction,
});
await queryInterface.removeColumn('brand_rate_cards', 'brandId', {
transaction,
});
await queryInterface.removeColumn('brand_rate_cards', 'clientId', {
transaction,
});
await queryInterface.removeColumn('brand_rate_cards', 'rate_card_type', {
transaction,
});
await queryInterface.removeColumn('brand_rate_cards', 'name', {
transaction,
});
await queryInterface.removeColumn('brands', 'xero_id', { transaction });
await queryInterface.removeColumn('brands', 'temp', { transaction });
await queryInterface.removeColumn('brands', 'insurance_fee', {
transaction,
});
await queryInterface.removeColumn('brands', 'production_fee', {
transaction,
});
await queryInterface.removeColumn('brands', 'default_costs', {
transaction,
});
await queryInterface.removeColumn('brands', 'link_rate_cardId', {
transaction,
});
await queryInterface.removeColumn('brands', 'inherit_default_rate_card', {
transaction,
});
await queryInterface.removeColumn('brands', 'default_salesId', {
transaction,
});
await queryInterface.removeColumn('brands', 'default_account_managerId', {
transaction,
});
await queryInterface.removeColumn('brands', 'default_client_contact', {
transaction,
});
await queryInterface.removeColumn('brands', 'yes_fixed_text', {
transaction,
});
await queryInterface.removeColumn('brands', 'client_fixed_text', {
transaction,
});
await queryInterface.removeColumn('brands', 'rate_card_import', {
transaction,
});
await queryInterface.removeColumn('brands', 'name', { transaction });
await queryInterface.removeColumn('brands', 'clientId', { transaction });
await queryInterface.removeColumn('organizations', 'name', {
transaction,
});
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
};

View File

@ -0,0 +1,380 @@
module.exports = {
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async up(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.addColumn(
'countries',
'name',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await queryInterface.addColumn(
'countries',
'currency',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await queryInterface.addColumn(
'countries',
'default_prefill',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await queryInterface.addColumn(
'client_orders',
'status',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await queryInterface.addColumn(
'client_orders',
'order_name',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await queryInterface.addColumn(
'client_orders',
'order_number',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await queryInterface.addColumn(
'clients',
'thyme_id',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await queryInterface.addColumn(
'clients',
'name',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await queryInterface.addColumn(
'clients',
'office',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await queryInterface.addColumn(
'clients',
'address',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await queryInterface.addColumn(
'clients',
'city',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await queryInterface.addColumn(
'clients',
'post_code',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await queryInterface.addColumn(
'clients',
'countryId',
{
type: Sequelize.DataTypes.UUID,
references: {
model: 'countries',
key: 'id',
},
},
{ transaction },
);
await queryInterface.addColumn(
'clients',
'country_txt',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await queryInterface.addColumn(
'clients',
'phone_number',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await queryInterface.addColumn(
'clients',
'website',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await queryInterface.addColumn(
'clients',
'currency',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await queryInterface.addColumn(
'clients',
'curious_customer_id',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await queryInterface.addColumn(
'clients',
'account_managerId',
{
type: Sequelize.DataTypes.UUID,
references: {
model: 'users',
key: 'id',
},
},
{ transaction },
);
await queryInterface.addColumn(
'clients',
'agency',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await queryInterface.addColumn(
'clients',
'inclusive_amends',
{
type: Sequelize.DataTypes.BOOLEAN,
defaultValue: false,
allowNull: false,
},
{ transaction },
);
await queryInterface.addColumn(
'clients',
'early_payment_discount',
{
type: Sequelize.DataTypes.DECIMAL,
},
{ transaction },
);
await queryInterface.addColumn(
'clients',
'client_id_link',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await queryInterface.addColumn(
'clients',
'public_url',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await queryInterface.addColumn(
'clients',
'production_fee',
{
type: Sequelize.DataTypes.DECIMAL,
},
{ transaction },
);
await queryInterface.addColumn(
'clients',
'insurance_fee',
{
type: Sequelize.DataTypes.DECIMAL,
},
{ transaction },
);
await queryInterface.addColumn(
'clients',
'xero_id',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async down(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.removeColumn('clients', 'xero_id', { transaction });
await queryInterface.removeColumn('clients', 'insurance_fee', {
transaction,
});
await queryInterface.removeColumn('clients', 'production_fee', {
transaction,
});
await queryInterface.removeColumn('clients', 'public_url', {
transaction,
});
await queryInterface.removeColumn('clients', 'client_id_link', {
transaction,
});
await queryInterface.removeColumn('clients', 'early_payment_discount', {
transaction,
});
await queryInterface.removeColumn('clients', 'inclusive_amends', {
transaction,
});
await queryInterface.removeColumn('clients', 'agency', { transaction });
await queryInterface.removeColumn('clients', 'account_managerId', {
transaction,
});
await queryInterface.removeColumn('clients', 'curious_customer_id', {
transaction,
});
await queryInterface.removeColumn('clients', 'currency', { transaction });
await queryInterface.removeColumn('clients', 'website', { transaction });
await queryInterface.removeColumn('clients', 'phone_number', {
transaction,
});
await queryInterface.removeColumn('clients', 'country_txt', {
transaction,
});
await queryInterface.removeColumn('clients', 'countryId', {
transaction,
});
await queryInterface.removeColumn('clients', 'post_code', {
transaction,
});
await queryInterface.removeColumn('clients', 'city', { transaction });
await queryInterface.removeColumn('clients', 'address', { transaction });
await queryInterface.removeColumn('clients', 'office', { transaction });
await queryInterface.removeColumn('clients', 'name', { transaction });
await queryInterface.removeColumn('clients', 'thyme_id', { transaction });
await queryInterface.removeColumn('client_orders', 'order_number', {
transaction,
});
await queryInterface.removeColumn('client_orders', 'order_name', {
transaction,
});
await queryInterface.removeColumn('client_orders', 'status', {
transaction,
});
await queryInterface.removeColumn('countries', 'default_prefill', {
transaction,
});
await queryInterface.removeColumn('countries', 'currency', {
transaction,
});
await queryInterface.removeColumn('countries', 'name', { transaction });
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
};

View File

@ -0,0 +1,294 @@
module.exports = {
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async up(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.addColumn(
'default_activities_products',
'name',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await queryInterface.addColumn(
'default_activities_products',
'rate_type',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await queryInterface.addColumn(
'default_activities_products',
'standard_service',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await queryInterface.addColumn(
'default_activities_products',
'departmentId',
{
type: Sequelize.DataTypes.UUID,
references: {
model: 'departments',
key: 'id',
},
},
{ transaction },
);
await queryInterface.addColumn(
'default_activities_products',
'service_text',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await queryInterface.addColumn(
'default_activities_products',
'rate',
{
type: Sequelize.DataTypes.DECIMAL,
},
{ transaction },
);
await queryInterface.addColumn(
'default_activities_products',
'service_id',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await queryInterface.addColumn(
'default_activities_products',
'service_code',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await queryInterface.addColumn(
'default_activities_products',
'unit_type',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await queryInterface.addColumn(
'default_activities_products',
'cost',
{
type: Sequelize.DataTypes.DECIMAL,
},
{ transaction },
);
await queryInterface.addColumn(
'default_activities_products',
'qty',
{
type: Sequelize.DataTypes.DECIMAL,
},
{ transaction },
);
await queryInterface.addColumn(
'default_activities_products',
'currency',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await queryInterface.addColumn(
'default_activities_products',
'rate_gbp',
{
type: Sequelize.DataTypes.DECIMAL,
},
{ transaction },
);
await queryInterface.addColumn(
'default_activities_products',
'rate_eur',
{
type: Sequelize.DataTypes.DECIMAL,
},
{ transaction },
);
await queryInterface.addColumn(
'default_activities_products',
'rate_usd',
{
type: Sequelize.DataTypes.DECIMAL,
},
{ transaction },
);
await queryInterface.addColumn(
'default_activities_products',
'yes_fixed_text',
{
type: Sequelize.DataTypes.BOOLEAN,
defaultValue: false,
allowNull: false,
},
{ transaction },
);
await queryInterface.addColumn(
'default_activities_products',
'no_fixed_text',
{
type: Sequelize.DataTypes.BOOLEAN,
defaultValue: false,
allowNull: false,
},
{ transaction },
);
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async down(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.removeColumn(
'default_activities_products',
'no_fixed_text',
{ transaction },
);
await queryInterface.removeColumn(
'default_activities_products',
'yes_fixed_text',
{ transaction },
);
await queryInterface.removeColumn(
'default_activities_products',
'rate_usd',
{ transaction },
);
await queryInterface.removeColumn(
'default_activities_products',
'rate_eur',
{ transaction },
);
await queryInterface.removeColumn(
'default_activities_products',
'rate_gbp',
{ transaction },
);
await queryInterface.removeColumn(
'default_activities_products',
'currency',
{ transaction },
);
await queryInterface.removeColumn('default_activities_products', 'qty', {
transaction,
});
await queryInterface.removeColumn('default_activities_products', 'cost', {
transaction,
});
await queryInterface.removeColumn(
'default_activities_products',
'unit_type',
{ transaction },
);
await queryInterface.removeColumn(
'default_activities_products',
'service_code',
{ transaction },
);
await queryInterface.removeColumn(
'default_activities_products',
'service_id',
{ transaction },
);
await queryInterface.removeColumn('default_activities_products', 'rate', {
transaction,
});
await queryInterface.removeColumn(
'default_activities_products',
'service_text',
{ transaction },
);
await queryInterface.removeColumn(
'default_activities_products',
'departmentId',
{ transaction },
);
await queryInterface.removeColumn(
'default_activities_products',
'standard_service',
{ transaction },
);
await queryInterface.removeColumn(
'default_activities_products',
'rate_type',
{ transaction },
);
await queryInterface.removeColumn('default_activities_products', 'name', {
transaction,
});
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
};

View File

@ -0,0 +1,60 @@
module.exports = {
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async up(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.addColumn(
'departments',
'name',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await queryInterface.addColumn(
'departments',
'timing_id',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async down(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.removeColumn('departments', 'timing_id', {
transaction,
});
await queryInterface.removeColumn('departments', 'name', { transaction });
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
};

View File

@ -0,0 +1,65 @@
module.exports = {
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async up(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.addColumn(
'markets',
'countryId',
{
type: Sequelize.DataTypes.UUID,
references: {
model: 'countries',
key: 'id',
},
},
{ transaction },
);
await queryInterface.addColumn(
'markets',
'market',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async down(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.removeColumn('markets', 'market', { transaction });
await queryInterface.removeColumn('markets', 'countryId', {
transaction,
});
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
};

View File

@ -0,0 +1,47 @@
module.exports = {
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async up(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.addColumn(
'users',
'clientId',
{
type: Sequelize.DataTypes.TEXT,
},
{ transaction },
);
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
/**
* @param {QueryInterface} queryInterface
* @param {Sequelize} Sequelize
* @returns {Promise<void>}
*/
async down(queryInterface, Sequelize) {
/**
* @type {Transaction}
*/
const transaction = await queryInterface.sequelize.transaction();
try {
await queryInterface.removeColumn('users', 'clientId', { transaction });
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
};

View File

@ -0,0 +1,45 @@
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 adbuilder_assets = sequelize.define(
'adbuilder_assets',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
adbuilder_assets.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.adbuilder_assets.belongsTo(db.users, {
as: 'createdBy',
});
db.adbuilder_assets.belongsTo(db.users, {
as: 'updatedBy',
});
};
return adbuilder_assets;
};

View File

@ -0,0 +1,45 @@
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 adbuilder_templates = sequelize.define(
'adbuilder_templates',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
adbuilder_templates.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.adbuilder_templates.belongsTo(db.users, {
as: 'createdBy',
});
db.adbuilder_templates.belongsTo(db.users, {
as: 'updatedBy',
});
};
return adbuilder_templates;
};

View File

@ -0,0 +1,181 @@
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 brand_rate_cards = sequelize.define(
'brand_rate_cards',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
rate_card_type: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.TEXT,
},
currency: {
type: DataTypes.TEXT,
},
push_new_values: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
inherit_default_rate_card: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
service_count: {
type: DataTypes.INTEGER,
},
discipline: {
type: DataTypes.TEXT,
},
output_channel: {
type: DataTypes.TEXT,
},
staff_skills: {
type: DataTypes.TEXT,
},
rate_card_owner: {
type: DataTypes.TEXT,
},
rate_card_id: {
type: DataTypes.TEXT,
},
markets: {
type: DataTypes.TEXT,
},
languages: {
type: DataTypes.TEXT,
},
valid_from: {
type: DataTypes.DATEONLY,
get: function () {
return this.getDataValue('valid_from')
? moment.utc(this.getDataValue('valid_from')).format('YYYY-MM-DD')
: null;
},
},
valid_to: {
type: DataTypes.DATEONLY,
get: function () {
return this.getDataValue('valid_to')
? moment.utc(this.getDataValue('valid_to')).format('YYYY-MM-DD')
: null;
},
},
version_number: {
type: DataTypes.TEXT,
},
commercial_owner: {
type: DataTypes.TEXT,
},
review_date: {
type: DataTypes.DATEONLY,
get: function () {
return this.getDataValue('review_date')
? moment.utc(this.getDataValue('review_date')).format('YYYY-MM-DD')
: null;
},
},
assumptions: {
type: DataTypes.TEXT,
},
no_fixed_text: {
type: DataTypes.TEXT,
},
yes_fixed_text: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
brand_rate_cards.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.brand_rate_cards.hasMany(db.brands, {
as: 'brands_link_rate_card',
foreignKey: {
name: 'link_rate_cardId',
},
constraints: false,
});
//end loop
db.brand_rate_cards.belongsTo(db.clients, {
as: 'client',
foreignKey: {
name: 'clientId',
},
constraints: false,
});
db.brand_rate_cards.belongsTo(db.brands, {
as: 'brand',
foreignKey: {
name: 'brandId',
},
constraints: false,
});
db.brand_rate_cards.belongsTo(db.users, {
as: 'createdBy',
});
db.brand_rate_cards.belongsTo(db.users, {
as: 'updatedBy',
});
};
return brand_rate_cards;
};

View File

@ -0,0 +1,135 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function (sequelize, DataTypes) {
const brands = sequelize.define(
'brands',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
rate_card_import: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
client_fixed_text: {
type: DataTypes.TEXT,
},
yes_fixed_text: {
type: DataTypes.TEXT,
},
default_client_contact: {
type: DataTypes.TEXT,
},
inherit_default_rate_card: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
default_costs: {
type: DataTypes.DECIMAL,
},
production_fee: {
type: DataTypes.DECIMAL,
},
insurance_fee: {
type: DataTypes.DECIMAL,
},
temp: {
type: DataTypes.TEXT,
},
xero_id: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
brands.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.brands.hasMany(db.brand_rate_cards, {
as: 'brand_rate_cards_brand',
foreignKey: {
name: 'brandId',
},
constraints: false,
});
//end loop
db.brands.belongsTo(db.clients, {
as: 'client',
foreignKey: {
name: 'clientId',
},
constraints: false,
});
db.brands.belongsTo(db.users, {
as: 'default_account_manager',
foreignKey: {
name: 'default_account_managerId',
},
constraints: false,
});
db.brands.belongsTo(db.users, {
as: 'default_sales',
foreignKey: {
name: 'default_salesId',
},
constraints: false,
});
db.brands.belongsTo(db.brand_rate_cards, {
as: 'link_rate_card',
foreignKey: {
name: 'link_rate_cardId',
},
constraints: false,
});
db.brands.belongsTo(db.users, {
as: 'createdBy',
});
db.brands.belongsTo(db.users, {
as: 'updatedBy',
});
};
return brands;
};

View File

@ -0,0 +1,45 @@
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 campaigns = sequelize.define(
'campaigns',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
campaigns.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.campaigns.belongsTo(db.users, {
as: 'createdBy',
});
db.campaigns.belongsTo(db.users, {
as: 'updatedBy',
});
};
return campaigns;
};

View File

@ -0,0 +1,45 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function (sequelize, DataTypes) {
const client_dam = sequelize.define(
'client_dam',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
client_dam.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.client_dam.belongsTo(db.users, {
as: 'createdBy',
});
db.client_dam.belongsTo(db.users, {
as: 'updatedBy',
});
};
return client_dam;
};

View File

@ -0,0 +1,75 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function (sequelize, DataTypes) {
const client_orders = sequelize.define(
'client_orders',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
status: {
type: DataTypes.TEXT,
},
order_name: {
type: DataTypes.TEXT,
},
order_number: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
client_orders.associate = (db) => {
db.client_orders.belongsToMany(db.client_dam, {
as: 'assets',
foreignKey: {
name: 'client_orders_assetsId',
},
constraints: false,
through: 'client_ordersAssetsClient_dam',
});
db.client_orders.belongsToMany(db.client_dam, {
as: 'assets_filter',
foreignKey: {
name: 'client_orders_assetsId',
},
constraints: false,
through: 'client_ordersAssetsClient_dam',
});
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.client_orders.belongsTo(db.users, {
as: 'createdBy',
});
db.client_orders.belongsTo(db.users, {
as: 'updatedBy',
});
};
return client_orders;
};

View File

@ -0,0 +1,174 @@
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,
},
thyme_id: {
type: DataTypes.TEXT,
},
name: {
type: DataTypes.TEXT,
},
office: {
type: DataTypes.TEXT,
},
address: {
type: DataTypes.TEXT,
},
city: {
type: DataTypes.TEXT,
},
post_code: {
type: DataTypes.TEXT,
},
country_txt: {
type: DataTypes.TEXT,
},
phone_number: {
type: DataTypes.TEXT,
},
website: {
type: DataTypes.TEXT,
},
currency: {
type: DataTypes.TEXT,
},
curious_customer_id: {
type: DataTypes.TEXT,
},
agency: {
type: DataTypes.TEXT,
},
inclusive_amends: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
early_payment_discount: {
type: DataTypes.DECIMAL,
},
client_id_link: {
type: DataTypes.TEXT,
},
public_url: {
type: DataTypes.TEXT,
},
production_fee: {
type: DataTypes.DECIMAL,
},
insurance_fee: {
type: DataTypes.DECIMAL,
},
xero_id: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
clients.associate = (db) => {
db.clients.belongsToMany(db.brands, {
as: 'all_brands',
foreignKey: {
name: 'clients_all_brandsId',
},
constraints: false,
through: 'clientsAll_brandsBrands',
});
db.clients.belongsToMany(db.brands, {
as: 'all_brands_filter',
foreignKey: {
name: 'clients_all_brandsId',
},
constraints: false,
through: 'clientsAll_brandsBrands',
});
/// 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.brands, {
as: 'brands_client',
foreignKey: {
name: 'clientId',
},
constraints: false,
});
db.clients.hasMany(db.brand_rate_cards, {
as: 'brand_rate_cards_client',
foreignKey: {
name: 'clientId',
},
constraints: false,
});
//end loop
db.clients.belongsTo(db.countries, {
as: 'country',
foreignKey: {
name: 'countryId',
},
constraints: false,
});
db.clients.belongsTo(db.users, {
as: 'account_manager',
foreignKey: {
name: 'account_managerId',
},
constraints: false,
});
db.clients.belongsTo(db.users, {
as: 'createdBy',
});
db.clients.belongsTo(db.users, {
as: 'updatedBy',
});
};
return clients;
};

View File

@ -0,0 +1,73 @@
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 countries = sequelize.define(
'countries',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
currency: {
type: DataTypes.TEXT,
},
default_prefill: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
countries.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.countries.hasMany(db.clients, {
as: 'clients_country',
foreignKey: {
name: 'countryId',
},
constraints: false,
});
db.countries.hasMany(db.markets, {
as: 'markets_country',
foreignKey: {
name: 'countryId',
},
constraints: false,
});
//end loop
db.countries.belongsTo(db.users, {
as: 'createdBy',
});
db.countries.belongsTo(db.users, {
as: 'updatedBy',
});
};
return countries;
};

View File

@ -0,0 +1,123 @@
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 default_activities_products = sequelize.define(
'default_activities_products',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
rate_type: {
type: DataTypes.TEXT,
},
standard_service: {
type: DataTypes.TEXT,
},
service_text: {
type: DataTypes.TEXT,
},
rate: {
type: DataTypes.DECIMAL,
},
service_id: {
type: DataTypes.TEXT,
},
service_code: {
type: DataTypes.TEXT,
},
unit_type: {
type: DataTypes.TEXT,
},
cost: {
type: DataTypes.DECIMAL,
},
qty: {
type: DataTypes.DECIMAL,
},
currency: {
type: DataTypes.TEXT,
},
rate_gbp: {
type: DataTypes.DECIMAL,
},
rate_eur: {
type: DataTypes.DECIMAL,
},
rate_usd: {
type: DataTypes.DECIMAL,
},
yes_fixed_text: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
no_fixed_text: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
default_activities_products.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.default_activities_products.belongsTo(db.departments, {
as: 'department',
foreignKey: {
name: 'departmentId',
},
constraints: false,
});
db.default_activities_products.belongsTo(db.users, {
as: 'createdBy',
});
db.default_activities_products.belongsTo(db.users, {
as: 'updatedBy',
});
};
return default_activities_products;
};

View File

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

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,47 @@
'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,57 @@
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 markets = sequelize.define(
'markets',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
market: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
markets.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.markets.belongsTo(db.countries, {
as: 'country',
foreignKey: {
name: 'countryId',
},
constraints: false,
});
db.markets.belongsTo(db.users, {
as: 'createdBy',
});
db.markets.belongsTo(db.users, {
as: 'updatedBy',
});
};
return markets;
};

View File

@ -0,0 +1,49 @@
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
//end loop
db.organizations.belongsTo(db.users, {
as: 'createdBy',
});
db.organizations.belongsTo(db.users, {
as: 'updatedBy',
});
};
return organizations;
};

View File

@ -0,0 +1,45 @@
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 outwork = sequelize.define(
'outwork',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
outwork.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.outwork.belongsTo(db.users, {
as: 'createdBy',
});
db.outwork.belongsTo(db.users, {
as: 'updatedBy',
});
};
return outwork;
};

View File

@ -0,0 +1,45 @@
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 outwork_line_items = sequelize.define(
'outwork_line_items',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
outwork_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.outwork_line_items.belongsTo(db.users, {
as: 'createdBy',
});
db.outwork_line_items.belongsTo(db.users, {
as: 'updatedBy',
});
};
return outwork_line_items;
};

View File

@ -0,0 +1,49 @@
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,45 @@
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 quotes = sequelize.define(
'quotes',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
quotes.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.quotes.belongsTo(db.users, {
as: 'createdBy',
});
db.quotes.belongsTo(db.users, {
as: 'updatedBy',
});
};
return quotes;
};

View File

@ -0,0 +1,45 @@
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 reports = sequelize.define(
'reports',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
reports.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.reports.belongsTo(db.users, {
as: 'createdBy',
});
db.reports.belongsTo(db.users, {
as: 'updatedBy',
});
};
return reports;
};

View File

@ -0,0 +1,79 @@
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,
},
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,45 @@
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 saved_adaptations = sequelize.define(
'saved_adaptations',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
saved_adaptations.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.saved_adaptations.belongsTo(db.users, {
as: 'createdBy',
});
db.saved_adaptations.belongsTo(db.users, {
as: 'updatedBy',
});
};
return saved_adaptations;
};

View File

@ -0,0 +1,45 @@
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 specs_database = sequelize.define(
'specs_database',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
specs_database.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.specs_database.belongsTo(db.users, {
as: 'createdBy',
});
db.specs_database.belongsTo(db.users, {
as: 'updatedBy',
});
};
return specs_database;
};

View File

@ -0,0 +1,45 @@
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 suppliers = sequelize.define(
'suppliers',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
suppliers.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.suppliers.belongsTo(db.users, {
as: 'createdBy',
});
db.suppliers.belongsTo(db.users, {
as: 'updatedBy',
});
};
return suppliers;
};

View File

@ -0,0 +1,45 @@
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 supporting_documents = sequelize.define(
'supporting_documents',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
supporting_documents.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.supporting_documents.belongsTo(db.users, {
as: 'createdBy',
});
db.supporting_documents.belongsTo(db.users, {
as: 'updatedBy',
});
};
return supporting_documents;
};

View File

@ -0,0 +1,45 @@
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 tracking_categories = sequelize.define(
'tracking_categories',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
tracking_categories.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.tracking_categories.belongsTo(db.users, {
as: 'createdBy',
});
db.tracking_categories.belongsTo(db.users, {
as: 'updatedBy',
});
};
return tracking_categories;
};

View File

@ -0,0 +1,199 @@
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,
},
clientId: {
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.brands, {
as: 'brands_default_account_manager',
foreignKey: {
name: 'default_account_managerId',
},
constraints: false,
});
db.users.hasMany(db.brands, {
as: 'brands_default_sales',
foreignKey: {
name: 'default_salesId',
},
constraints: false,
});
db.users.hasMany(db.clients, {
as: 'clients_account_manager',
foreignKey: {
name: 'account_managerId',
},
constraints: false,
});
//end loop
db.users.belongsTo(db.roles, {
as: 'app_role',
foreignKey: {
name: 'app_roleId',
},
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,45 @@
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 zipflow_workflows = sequelize.define(
'zipflow_workflows',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
zipflow_workflows.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.zipflow_workflows.belongsTo(db.users, {
as: 'createdBy',
});
db.zipflow_workflows.belongsTo(db.users, {
as: 'updatedBy',
});
};
return zipflow_workflows;
};

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