Initial version

This commit is contained in:
Flatlogic Bot 2026-02-19 23:45:10 +00:00
commit 726602aebe
629 changed files with 187990 additions and 0 deletions

305
.cursorrules Normal file
View File

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

3
.dockerignore Normal file
View File

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

3
.gitignore vendored Normal file
View File

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

187
502.html Normal file
View File

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

21
Dockerfile Normal file
View File

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

85
Dockerfile.dev Normal file
View File

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

1
LICENSE Normal file
View File

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

244
README.md Normal file
View File

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

14
backend/.env Normal file
View File

@ -0,0 +1,14 @@
DB_NAME=app_38630
DB_USER=app_38630
DB_PASS=3e1d2c91-7e09-4ac7-820f-05d8ff7efb47
DB_HOST=127.0.0.1
DB_PORT=5432
PORT=3000
GOOGLE_CLIENT_ID=671001533244-kf1k1gmp6mnl0r030qmvdu6v36ghmim6.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET=Yo4qbKZniqvojzUQ60iKlxqR
MS_CLIENT_ID=4696f457-31af-40de-897c-e00d7d4cff73
MS_CLIENT_SECRET=m8jzZ.5UpHF3=-dXzyxiZ4e[F8OF54@p
EMAIL_USER=AKIAVEW7G4PQUBGM52OF
EMAIL_PASS=BLnD4hKGb6YkSz3gaQrf8fnyLi3C3/EdjOOsLEDTDPTz
SECRET_KEY=HUEyqESqgQ1yTwzVlO6wprC9Kf1J1xuA
PEXELS_KEY=Vc99rnmOhHhJAbgGQoKLZtsaIVfkeownoQNbTj78VemUjKh08ZYRbf18

4
backend/.eslintignore Normal file
View File

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

15
backend/.eslintrc.cjs Normal file
View File

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

11
backend/.prettierrc Normal file
View File

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

7
backend/.sequelizerc Normal file
View File

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

23
backend/Dockerfile Normal file
View File

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

56
backend/README.md Normal file
View File

@ -0,0 +1,56 @@
#Stone Factory Arabic Site - 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_stone_factory_arabic_site;`
- Then give that new user privileges to the new database then quit the `psql`.
- `postgres=> GRANT ALL PRIVILEGES ON DATABASE db_stone_factory_arabic_site TO admin;`
- `postgres=> \q`
------------
#### Api Documentation (Swagger)
http://localhost:8080/api-docs (local host)
http://host_name/api-docs
------------
##### Setup database tables or update after schema change
- `yarn db:migrate`
##### Seed the initial data (admin accounts, relevant for the first setup):
- `yarn db:seed`
##### Start build:
- `yarn start`

56
backend/package.json Normal file
View File

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

View File

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

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

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

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

@ -0,0 +1,79 @@
const os = require('os');
const config = {
gcloud: {
bucket: "fldemo-files",
hash: "afeefb9d49f5b7977577876b99532ac7"
},
bcrypt: {
saltRounds: 12
},
admin_pass: "3e1d2c91",
user_pass: "05d8ff7efb47",
admin_email: "admin@flatlogic.com",
providers: {
LOCAL: 'local',
GOOGLE: 'google',
MICROSOFT: 'microsoft'
},
secret_key: process.env.SECRET_KEY || '3e1d2c91-7e09-4ac7-820f-05d8ff7efb47',
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: 'Stone Factory Arabic Site <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: 'Viewer',
},
project_uuid: '3e1d2c91-7e09-4ac7-820f-05d8ff7efb47',
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 = 'Light through carved stone tunnel';
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,419 @@
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 ApplicationsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const applications = await db.applications.create(
{
id: data.id || undefined,
name_ar: data.name_ar
||
null
,
application_scope: data.application_scope
||
null
,
description_ar: data.description_ar
||
null
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return applications;
}
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 applicationsData = data.map((item, index) => ({
id: item.id || undefined,
name_ar: item.name_ar
||
null
,
application_scope: item.application_scope
||
null
,
description_ar: item.description_ar
||
null
,
is_active: item.is_active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const applications = await db.applications.bulkCreate(applicationsData, { transaction });
// For each item created, replace relation files
return applications;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const applications = await db.applications.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name_ar !== undefined) updatePayload.name_ar = data.name_ar;
if (data.application_scope !== undefined) updatePayload.application_scope = data.application_scope;
if (data.description_ar !== undefined) updatePayload.description_ar = data.description_ar;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await applications.update(updatePayload, {transaction});
return applications;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const applications = await db.applications.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of applications) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of applications) {
await record.destroy({transaction});
}
});
return applications;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const applications = await db.applications.findByPk(id, options);
await applications.update({
deletedBy: currentUser.id
}, {
transaction,
});
await applications.destroy({
transaction
});
return applications;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const applications = await db.applications.findOne(
{ where },
{ transaction },
);
if (!applications) {
return applications;
}
const output = applications.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_ar) {
where = {
...where,
[Op.and]: Utils.ilike(
'applications',
'name_ar',
filter.name_ar,
),
};
}
if (filter.description_ar) {
where = {
...where,
[Op.and]: Utils.ilike(
'applications',
'description_ar',
filter.description_ar,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.application_scope) {
where = {
...where,
application_scope: filter.application_scope,
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
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.applications.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(
'applications',
'name_ar',
query,
),
],
};
}
const records = await db.applications.findAll({
attributes: [ 'id', 'name_ar' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['name_ar', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.name_ar,
}));
}
};

View File

@ -0,0 +1,464 @@
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 Blog_categoriesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const blog_categories = await db.blog_categories.create(
{
id: data.id || undefined,
name_ar: data.name_ar
||
null
,
slug: data.slug
||
null
,
description_ar: data.description_ar
||
null
,
sort_order: data.sort_order
||
null
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return blog_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 blog_categoriesData = data.map((item, index) => ({
id: item.id || undefined,
name_ar: item.name_ar
||
null
,
slug: item.slug
||
null
,
description_ar: item.description_ar
||
null
,
sort_order: item.sort_order
||
null
,
is_active: item.is_active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const blog_categories = await db.blog_categories.bulkCreate(blog_categoriesData, { transaction });
// For each item created, replace relation files
return blog_categories;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const blog_categories = await db.blog_categories.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name_ar !== undefined) updatePayload.name_ar = data.name_ar;
if (data.slug !== undefined) updatePayload.slug = data.slug;
if (data.description_ar !== undefined) updatePayload.description_ar = data.description_ar;
if (data.sort_order !== undefined) updatePayload.sort_order = data.sort_order;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await blog_categories.update(updatePayload, {transaction});
return blog_categories;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const blog_categories = await db.blog_categories.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of blog_categories) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of blog_categories) {
await record.destroy({transaction});
}
});
return blog_categories;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const blog_categories = await db.blog_categories.findByPk(id, options);
await blog_categories.update({
deletedBy: currentUser.id
}, {
transaction,
});
await blog_categories.destroy({
transaction
});
return blog_categories;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const blog_categories = await db.blog_categories.findOne(
{ where },
{ transaction },
);
if (!blog_categories) {
return blog_categories;
}
const output = blog_categories.get({plain: true});
output.blog_posts_category = await blog_categories.getBlog_posts_category({
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_ar) {
where = {
...where,
[Op.and]: Utils.ilike(
'blog_categories',
'name_ar',
filter.name_ar,
),
};
}
if (filter.slug) {
where = {
...where,
[Op.and]: Utils.ilike(
'blog_categories',
'slug',
filter.slug,
),
};
}
if (filter.description_ar) {
where = {
...where,
[Op.and]: Utils.ilike(
'blog_categories',
'description_ar',
filter.description_ar,
),
};
}
if (filter.sort_orderRange) {
const [start, end] = filter.sort_orderRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sort_order: {
...where.sort_order,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sort_order: {
...where.sort_order,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
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.blog_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(
'blog_categories',
'name_ar',
query,
),
],
};
}
const records = await db.blog_categories.findAll({
attributes: [ 'id', 'name_ar' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['name_ar', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.name_ar,
}));
}
};

View File

@ -0,0 +1,746 @@
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 Blog_postsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const blog_posts = await db.blog_posts.create(
{
id: data.id || undefined,
title_ar: data.title_ar
||
null
,
slug: data.slug
||
null
,
excerpt_ar: data.excerpt_ar
||
null
,
content_ar: data.content_ar
||
null
,
publish_status: data.publish_status
||
null
,
published_at: data.published_at
||
null
,
is_featured: data.is_featured
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await blog_posts.setCategory( data.category || null, {
transaction,
});
await blog_posts.setAuthor( data.author || null, {
transaction,
});
await blog_posts.setRelated_stones(data.related_stones || [], {
transaction,
});
await blog_posts.setRelated_projects(data.related_projects || [], {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.blog_posts.getTableName(),
belongsToColumn: 'featured_image',
belongsToId: blog_posts.id,
},
data.featured_image,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.blog_posts.getTableName(),
belongsToColumn: 'attachments',
belongsToId: blog_posts.id,
},
data.attachments,
options,
);
return blog_posts;
}
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 blog_postsData = data.map((item, index) => ({
id: item.id || undefined,
title_ar: item.title_ar
||
null
,
slug: item.slug
||
null
,
excerpt_ar: item.excerpt_ar
||
null
,
content_ar: item.content_ar
||
null
,
publish_status: item.publish_status
||
null
,
published_at: item.published_at
||
null
,
is_featured: item.is_featured
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const blog_posts = await db.blog_posts.bulkCreate(blog_postsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < blog_posts.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.blog_posts.getTableName(),
belongsToColumn: 'featured_image',
belongsToId: blog_posts[i].id,
},
data[i].featured_image,
options,
);
}
for (let i = 0; i < blog_posts.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.blog_posts.getTableName(),
belongsToColumn: 'attachments',
belongsToId: blog_posts[i].id,
},
data[i].attachments,
options,
);
}
return blog_posts;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const blog_posts = await db.blog_posts.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.title_ar !== undefined) updatePayload.title_ar = data.title_ar;
if (data.slug !== undefined) updatePayload.slug = data.slug;
if (data.excerpt_ar !== undefined) updatePayload.excerpt_ar = data.excerpt_ar;
if (data.content_ar !== undefined) updatePayload.content_ar = data.content_ar;
if (data.publish_status !== undefined) updatePayload.publish_status = data.publish_status;
if (data.published_at !== undefined) updatePayload.published_at = data.published_at;
if (data.is_featured !== undefined) updatePayload.is_featured = data.is_featured;
updatePayload.updatedById = currentUser.id;
await blog_posts.update(updatePayload, {transaction});
if (data.category !== undefined) {
await blog_posts.setCategory(
data.category,
{ transaction }
);
}
if (data.author !== undefined) {
await blog_posts.setAuthor(
data.author,
{ transaction }
);
}
if (data.related_stones !== undefined) {
await blog_posts.setRelated_stones(data.related_stones, { transaction });
}
if (data.related_projects !== undefined) {
await blog_posts.setRelated_projects(data.related_projects, { transaction });
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.blog_posts.getTableName(),
belongsToColumn: 'featured_image',
belongsToId: blog_posts.id,
},
data.featured_image,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.blog_posts.getTableName(),
belongsToColumn: 'attachments',
belongsToId: blog_posts.id,
},
data.attachments,
options,
);
return blog_posts;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const blog_posts = await db.blog_posts.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of blog_posts) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of blog_posts) {
await record.destroy({transaction});
}
});
return blog_posts;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const blog_posts = await db.blog_posts.findByPk(id, options);
await blog_posts.update({
deletedBy: currentUser.id
}, {
transaction,
});
await blog_posts.destroy({
transaction
});
return blog_posts;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const blog_posts = await db.blog_posts.findOne(
{ where },
{ transaction },
);
if (!blog_posts) {
return blog_posts;
}
const output = blog_posts.get({plain: true});
output.category = await blog_posts.getCategory({
transaction
});
output.author = await blog_posts.getAuthor({
transaction
});
output.featured_image = await blog_posts.getFeatured_image({
transaction
});
output.attachments = await blog_posts.getAttachments({
transaction
});
output.related_stones = await blog_posts.getRelated_stones({
transaction
});
output.related_projects = await blog_posts.getRelated_projects({
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.blog_categories,
as: 'category',
where: filter.category ? {
[Op.or]: [
{ id: { [Op.in]: filter.category.split('|').map(term => Utils.uuid(term)) } },
{
name_ar: {
[Op.or]: filter.category.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'author',
where: filter.author ? {
[Op.or]: [
{ id: { [Op.in]: filter.author.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.author.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.stones,
as: 'related_stones',
required: false,
},
{
model: db.projects,
as: 'related_projects',
required: false,
},
{
model: db.file,
as: 'featured_image',
},
{
model: db.file,
as: 'attachments',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.title_ar) {
where = {
...where,
[Op.and]: Utils.ilike(
'blog_posts',
'title_ar',
filter.title_ar,
),
};
}
if (filter.slug) {
where = {
...where,
[Op.and]: Utils.ilike(
'blog_posts',
'slug',
filter.slug,
),
};
}
if (filter.excerpt_ar) {
where = {
...where,
[Op.and]: Utils.ilike(
'blog_posts',
'excerpt_ar',
filter.excerpt_ar,
),
};
}
if (filter.content_ar) {
where = {
...where,
[Op.and]: Utils.ilike(
'blog_posts',
'content_ar',
filter.content_ar,
),
};
}
if (filter.published_atRange) {
const [start, end] = filter.published_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
published_at: {
...where.published_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
published_at: {
...where.published_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.publish_status) {
where = {
...where,
publish_status: filter.publish_status,
};
}
if (filter.is_featured) {
where = {
...where,
is_featured: filter.is_featured,
};
}
if (filter.related_stones) {
const searchTerms = filter.related_stones.split('|');
include = [
{
model: db.stones,
as: 'related_stones_filter',
required: searchTerms.length > 0,
where: searchTerms.length > 0 ? {
[Op.or]: [
{ id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
{
name_ar: {
[Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
}
}
]
} : undefined
},
...include,
]
}
if (filter.related_projects) {
const searchTerms = filter.related_projects.split('|');
include = [
{
model: db.projects,
as: 'related_projects_filter',
required: searchTerms.length > 0,
where: searchTerms.length > 0 ? {
[Op.or]: [
{ id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
{
name_ar: {
[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.blog_posts.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(
'blog_posts',
'title_ar',
query,
),
],
};
}
const records = await db.blog_posts.findAll({
attributes: [ 'id', 'title_ar' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['title_ar', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.title_ar,
}));
}
};

View File

@ -0,0 +1,549 @@
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 Contact_locationsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const contact_locations = await db.contact_locations.create(
{
id: data.id || undefined,
name_ar: data.name_ar
||
null
,
address_ar: data.address_ar
||
null
,
phone: data.phone
||
null
,
email: data.email
||
null
,
google_maps_url: data.google_maps_url
||
null
,
latitude: data.latitude
||
null
,
longitude: data.longitude
||
null
,
is_primary: data.is_primary
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return contact_locations;
}
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 contact_locationsData = data.map((item, index) => ({
id: item.id || undefined,
name_ar: item.name_ar
||
null
,
address_ar: item.address_ar
||
null
,
phone: item.phone
||
null
,
email: item.email
||
null
,
google_maps_url: item.google_maps_url
||
null
,
latitude: item.latitude
||
null
,
longitude: item.longitude
||
null
,
is_primary: item.is_primary
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const contact_locations = await db.contact_locations.bulkCreate(contact_locationsData, { transaction });
// For each item created, replace relation files
return contact_locations;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const contact_locations = await db.contact_locations.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name_ar !== undefined) updatePayload.name_ar = data.name_ar;
if (data.address_ar !== undefined) updatePayload.address_ar = data.address_ar;
if (data.phone !== undefined) updatePayload.phone = data.phone;
if (data.email !== undefined) updatePayload.email = data.email;
if (data.google_maps_url !== undefined) updatePayload.google_maps_url = data.google_maps_url;
if (data.latitude !== undefined) updatePayload.latitude = data.latitude;
if (data.longitude !== undefined) updatePayload.longitude = data.longitude;
if (data.is_primary !== undefined) updatePayload.is_primary = data.is_primary;
updatePayload.updatedById = currentUser.id;
await contact_locations.update(updatePayload, {transaction});
return contact_locations;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const contact_locations = await db.contact_locations.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of contact_locations) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of contact_locations) {
await record.destroy({transaction});
}
});
return contact_locations;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const contact_locations = await db.contact_locations.findByPk(id, options);
await contact_locations.update({
deletedBy: currentUser.id
}, {
transaction,
});
await contact_locations.destroy({
transaction
});
return contact_locations;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const contact_locations = await db.contact_locations.findOne(
{ where },
{ transaction },
);
if (!contact_locations) {
return contact_locations;
}
const output = contact_locations.get({plain: true});
output.inquiries_location = await contact_locations.getInquiries_location({
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_ar) {
where = {
...where,
[Op.and]: Utils.ilike(
'contact_locations',
'name_ar',
filter.name_ar,
),
};
}
if (filter.address_ar) {
where = {
...where,
[Op.and]: Utils.ilike(
'contact_locations',
'address_ar',
filter.address_ar,
),
};
}
if (filter.phone) {
where = {
...where,
[Op.and]: Utils.ilike(
'contact_locations',
'phone',
filter.phone,
),
};
}
if (filter.email) {
where = {
...where,
[Op.and]: Utils.ilike(
'contact_locations',
'email',
filter.email,
),
};
}
if (filter.google_maps_url) {
where = {
...where,
[Op.and]: Utils.ilike(
'contact_locations',
'google_maps_url',
filter.google_maps_url,
),
};
}
if (filter.latitudeRange) {
const [start, end] = filter.latitudeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
latitude: {
...where.latitude,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
latitude: {
...where.latitude,
[Op.lte]: end,
},
};
}
}
if (filter.longitudeRange) {
const [start, end] = filter.longitudeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
longitude: {
...where.longitude,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
longitude: {
...where.longitude,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.is_primary) {
where = {
...where,
is_primary: filter.is_primary,
};
}
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.contact_locations.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(
'contact_locations',
'name_ar',
query,
),
],
};
}
const records = await db.contact_locations.findAll({
attributes: [ 'id', 'name_ar' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['name_ar', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.name_ar,
}));
}
};

View File

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

View File

@ -0,0 +1,441 @@
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 FinishesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const finishes = await db.finishes.create(
{
id: data.id || undefined,
name_ar: data.name_ar
||
null
,
description_ar: data.description_ar
||
null
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.finishes.getTableName(),
belongsToColumn: 'example_images',
belongsToId: finishes.id,
},
data.example_images,
options,
);
return finishes;
}
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 finishesData = data.map((item, index) => ({
id: item.id || undefined,
name_ar: item.name_ar
||
null
,
description_ar: item.description_ar
||
null
,
is_active: item.is_active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const finishes = await db.finishes.bulkCreate(finishesData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < finishes.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.finishes.getTableName(),
belongsToColumn: 'example_images',
belongsToId: finishes[i].id,
},
data[i].example_images,
options,
);
}
return finishes;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const finishes = await db.finishes.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name_ar !== undefined) updatePayload.name_ar = data.name_ar;
if (data.description_ar !== undefined) updatePayload.description_ar = data.description_ar;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await finishes.update(updatePayload, {transaction});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.finishes.getTableName(),
belongsToColumn: 'example_images',
belongsToId: finishes.id,
},
data.example_images,
options,
);
return finishes;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const finishes = await db.finishes.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of finishes) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of finishes) {
await record.destroy({transaction});
}
});
return finishes;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const finishes = await db.finishes.findByPk(id, options);
await finishes.update({
deletedBy: currentUser.id
}, {
transaction,
});
await finishes.destroy({
transaction
});
return finishes;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const finishes = await db.finishes.findOne(
{ where },
{ transaction },
);
if (!finishes) {
return finishes;
}
const output = finishes.get({plain: true});
output.example_images = await finishes.getExample_images({
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.file,
as: 'example_images',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name_ar) {
where = {
...where,
[Op.and]: Utils.ilike(
'finishes',
'name_ar',
filter.name_ar,
),
};
}
if (filter.description_ar) {
where = {
...where,
[Op.and]: Utils.ilike(
'finishes',
'description_ar',
filter.description_ar,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
if (filter.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.finishes.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(
'finishes',
'name_ar',
query,
),
],
};
}
const records = await db.finishes.findAll({
attributes: [ 'id', 'name_ar' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['name_ar', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.name_ar,
}));
}
};

View File

@ -0,0 +1,588 @@
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 Hero_slidesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const hero_slides = await db.hero_slides.create(
{
id: data.id || undefined,
headline_ar: data.headline_ar
||
null
,
subheadline_ar: data.subheadline_ar
||
null
,
cta_type: data.cta_type
||
null
,
cta_label_ar: data.cta_label_ar
||
null
,
cta_url: data.cta_url
||
null
,
sort_order: data.sort_order
||
null
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.hero_slides.getTableName(),
belongsToColumn: 'background_images',
belongsToId: hero_slides.id,
},
data.background_images,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.hero_slides.getTableName(),
belongsToColumn: 'background_videos',
belongsToId: hero_slides.id,
},
data.background_videos,
options,
);
return hero_slides;
}
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 hero_slidesData = data.map((item, index) => ({
id: item.id || undefined,
headline_ar: item.headline_ar
||
null
,
subheadline_ar: item.subheadline_ar
||
null
,
cta_type: item.cta_type
||
null
,
cta_label_ar: item.cta_label_ar
||
null
,
cta_url: item.cta_url
||
null
,
sort_order: item.sort_order
||
null
,
is_active: item.is_active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const hero_slides = await db.hero_slides.bulkCreate(hero_slidesData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < hero_slides.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.hero_slides.getTableName(),
belongsToColumn: 'background_images',
belongsToId: hero_slides[i].id,
},
data[i].background_images,
options,
);
}
for (let i = 0; i < hero_slides.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.hero_slides.getTableName(),
belongsToColumn: 'background_videos',
belongsToId: hero_slides[i].id,
},
data[i].background_videos,
options,
);
}
return hero_slides;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const hero_slides = await db.hero_slides.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.headline_ar !== undefined) updatePayload.headline_ar = data.headline_ar;
if (data.subheadline_ar !== undefined) updatePayload.subheadline_ar = data.subheadline_ar;
if (data.cta_type !== undefined) updatePayload.cta_type = data.cta_type;
if (data.cta_label_ar !== undefined) updatePayload.cta_label_ar = data.cta_label_ar;
if (data.cta_url !== undefined) updatePayload.cta_url = data.cta_url;
if (data.sort_order !== undefined) updatePayload.sort_order = data.sort_order;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await hero_slides.update(updatePayload, {transaction});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.hero_slides.getTableName(),
belongsToColumn: 'background_images',
belongsToId: hero_slides.id,
},
data.background_images,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.hero_slides.getTableName(),
belongsToColumn: 'background_videos',
belongsToId: hero_slides.id,
},
data.background_videos,
options,
);
return hero_slides;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const hero_slides = await db.hero_slides.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of hero_slides) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of hero_slides) {
await record.destroy({transaction});
}
});
return hero_slides;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const hero_slides = await db.hero_slides.findByPk(id, options);
await hero_slides.update({
deletedBy: currentUser.id
}, {
transaction,
});
await hero_slides.destroy({
transaction
});
return hero_slides;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const hero_slides = await db.hero_slides.findOne(
{ where },
{ transaction },
);
if (!hero_slides) {
return hero_slides;
}
const output = hero_slides.get({plain: true});
output.background_images = await hero_slides.getBackground_images({
transaction
});
output.background_videos = await hero_slides.getBackground_videos({
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.file,
as: 'background_images',
},
{
model: db.file,
as: 'background_videos',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.headline_ar) {
where = {
...where,
[Op.and]: Utils.ilike(
'hero_slides',
'headline_ar',
filter.headline_ar,
),
};
}
if (filter.subheadline_ar) {
where = {
...where,
[Op.and]: Utils.ilike(
'hero_slides',
'subheadline_ar',
filter.subheadline_ar,
),
};
}
if (filter.cta_label_ar) {
where = {
...where,
[Op.and]: Utils.ilike(
'hero_slides',
'cta_label_ar',
filter.cta_label_ar,
),
};
}
if (filter.cta_url) {
where = {
...where,
[Op.and]: Utils.ilike(
'hero_slides',
'cta_url',
filter.cta_url,
),
};
}
if (filter.sort_orderRange) {
const [start, end] = filter.sort_orderRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sort_order: {
...where.sort_order,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sort_order: {
...where.sort_order,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.cta_type) {
where = {
...where,
cta_type: filter.cta_type,
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
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.hero_slides.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(
'hero_slides',
'headline_ar',
query,
),
],
};
}
const records = await db.hero_slides.findAll({
attributes: [ 'id', 'headline_ar' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['headline_ar', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.headline_ar,
}));
}
};

View File

@ -0,0 +1,617 @@
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 InquiriesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const inquiries = await db.inquiries.create(
{
id: data.id || undefined,
full_name: data.full_name
||
null
,
email: data.email
||
null
,
phone: data.phone
||
null
,
subject_ar: data.subject_ar
||
null
,
message_ar: data.message_ar
||
null
,
status: data.status
||
null
,
received_at: data.received_at
||
null
,
replied_at: data.replied_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await inquiries.setLocation( data.location || null, {
transaction,
});
await inquiries.setAssigned_to( data.assigned_to || null, {
transaction,
});
return inquiries;
}
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 inquiriesData = data.map((item, index) => ({
id: item.id || undefined,
full_name: item.full_name
||
null
,
email: item.email
||
null
,
phone: item.phone
||
null
,
subject_ar: item.subject_ar
||
null
,
message_ar: item.message_ar
||
null
,
status: item.status
||
null
,
received_at: item.received_at
||
null
,
replied_at: item.replied_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const inquiries = await db.inquiries.bulkCreate(inquiriesData, { transaction });
// For each item created, replace relation files
return inquiries;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const inquiries = await db.inquiries.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.full_name !== undefined) updatePayload.full_name = data.full_name;
if (data.email !== undefined) updatePayload.email = data.email;
if (data.phone !== undefined) updatePayload.phone = data.phone;
if (data.subject_ar !== undefined) updatePayload.subject_ar = data.subject_ar;
if (data.message_ar !== undefined) updatePayload.message_ar = data.message_ar;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.received_at !== undefined) updatePayload.received_at = data.received_at;
if (data.replied_at !== undefined) updatePayload.replied_at = data.replied_at;
updatePayload.updatedById = currentUser.id;
await inquiries.update(updatePayload, {transaction});
if (data.location !== undefined) {
await inquiries.setLocation(
data.location,
{ transaction }
);
}
if (data.assigned_to !== undefined) {
await inquiries.setAssigned_to(
data.assigned_to,
{ transaction }
);
}
return inquiries;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const inquiries = await db.inquiries.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of inquiries) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of inquiries) {
await record.destroy({transaction});
}
});
return inquiries;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const inquiries = await db.inquiries.findByPk(id, options);
await inquiries.update({
deletedBy: currentUser.id
}, {
transaction,
});
await inquiries.destroy({
transaction
});
return inquiries;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const inquiries = await db.inquiries.findOne(
{ where },
{ transaction },
);
if (!inquiries) {
return inquiries;
}
const output = inquiries.get({plain: true});
output.location = await inquiries.getLocation({
transaction
});
output.assigned_to = await inquiries.getAssigned_to({
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.contact_locations,
as: 'location',
where: filter.location ? {
[Op.or]: [
{ id: { [Op.in]: filter.location.split('|').map(term => Utils.uuid(term)) } },
{
name_ar: {
[Op.or]: filter.location.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'assigned_to',
where: filter.assigned_to ? {
[Op.or]: [
{ id: { [Op.in]: filter.assigned_to.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.assigned_to.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.full_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'inquiries',
'full_name',
filter.full_name,
),
};
}
if (filter.email) {
where = {
...where,
[Op.and]: Utils.ilike(
'inquiries',
'email',
filter.email,
),
};
}
if (filter.phone) {
where = {
...where,
[Op.and]: Utils.ilike(
'inquiries',
'phone',
filter.phone,
),
};
}
if (filter.subject_ar) {
where = {
...where,
[Op.and]: Utils.ilike(
'inquiries',
'subject_ar',
filter.subject_ar,
),
};
}
if (filter.message_ar) {
where = {
...where,
[Op.and]: Utils.ilike(
'inquiries',
'message_ar',
filter.message_ar,
),
};
}
if (filter.received_atRange) {
const [start, end] = filter.received_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
received_at: {
...where.received_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
received_at: {
...where.received_at,
[Op.lte]: end,
},
};
}
}
if (filter.replied_atRange) {
const [start, end] = filter.replied_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
replied_at: {
...where.replied_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
replied_at: {
...where.replied_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.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.inquiries.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(
'inquiries',
'subject_ar',
query,
),
],
};
}
const records = await db.inquiries.findAll({
attributes: [ 'id', 'subject_ar' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['subject_ar', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.subject_ar,
}));
}
};

View File

@ -0,0 +1,801 @@
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 Lead_requestsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const lead_requests = await db.lead_requests.create(
{
id: data.id || undefined,
request_type: data.request_type
||
null
,
full_name: data.full_name
||
null
,
company_name: data.company_name
||
null
,
email: data.email
||
null
,
phone: data.phone
||
null
,
customer_type: data.customer_type
||
null
,
message_ar: data.message_ar
||
null
,
lead_status: data.lead_status
||
null
,
preferred_contact_time: data.preferred_contact_time
||
null
,
last_contacted_at: data.last_contacted_at
||
null
,
internal_notes: data.internal_notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await lead_requests.setInterested_stone( data.interested_stone || null, {
transaction,
});
await lead_requests.setInterested_service( data.interested_service || null, {
transaction,
});
await lead_requests.setRelated_project( data.related_project || null, {
transaction,
});
await lead_requests.setAssigned_to( data.assigned_to || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.lead_requests.getTableName(),
belongsToColumn: 'reference_files',
belongsToId: lead_requests.id,
},
data.reference_files,
options,
);
return lead_requests;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const lead_requestsData = data.map((item, index) => ({
id: item.id || undefined,
request_type: item.request_type
||
null
,
full_name: item.full_name
||
null
,
company_name: item.company_name
||
null
,
email: item.email
||
null
,
phone: item.phone
||
null
,
customer_type: item.customer_type
||
null
,
message_ar: item.message_ar
||
null
,
lead_status: item.lead_status
||
null
,
preferred_contact_time: item.preferred_contact_time
||
null
,
last_contacted_at: item.last_contacted_at
||
null
,
internal_notes: item.internal_notes
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const lead_requests = await db.lead_requests.bulkCreate(lead_requestsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < lead_requests.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.lead_requests.getTableName(),
belongsToColumn: 'reference_files',
belongsToId: lead_requests[i].id,
},
data[i].reference_files,
options,
);
}
return lead_requests;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const lead_requests = await db.lead_requests.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.request_type !== undefined) updatePayload.request_type = data.request_type;
if (data.full_name !== undefined) updatePayload.full_name = data.full_name;
if (data.company_name !== undefined) updatePayload.company_name = data.company_name;
if (data.email !== undefined) updatePayload.email = data.email;
if (data.phone !== undefined) updatePayload.phone = data.phone;
if (data.customer_type !== undefined) updatePayload.customer_type = data.customer_type;
if (data.message_ar !== undefined) updatePayload.message_ar = data.message_ar;
if (data.lead_status !== undefined) updatePayload.lead_status = data.lead_status;
if (data.preferred_contact_time !== undefined) updatePayload.preferred_contact_time = data.preferred_contact_time;
if (data.last_contacted_at !== undefined) updatePayload.last_contacted_at = data.last_contacted_at;
if (data.internal_notes !== undefined) updatePayload.internal_notes = data.internal_notes;
updatePayload.updatedById = currentUser.id;
await lead_requests.update(updatePayload, {transaction});
if (data.interested_stone !== undefined) {
await lead_requests.setInterested_stone(
data.interested_stone,
{ transaction }
);
}
if (data.interested_service !== undefined) {
await lead_requests.setInterested_service(
data.interested_service,
{ transaction }
);
}
if (data.related_project !== undefined) {
await lead_requests.setRelated_project(
data.related_project,
{ transaction }
);
}
if (data.assigned_to !== undefined) {
await lead_requests.setAssigned_to(
data.assigned_to,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.lead_requests.getTableName(),
belongsToColumn: 'reference_files',
belongsToId: lead_requests.id,
},
data.reference_files,
options,
);
return lead_requests;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const lead_requests = await db.lead_requests.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of lead_requests) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of lead_requests) {
await record.destroy({transaction});
}
});
return lead_requests;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const lead_requests = await db.lead_requests.findByPk(id, options);
await lead_requests.update({
deletedBy: currentUser.id
}, {
transaction,
});
await lead_requests.destroy({
transaction
});
return lead_requests;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const lead_requests = await db.lead_requests.findOne(
{ where },
{ transaction },
);
if (!lead_requests) {
return lead_requests;
}
const output = lead_requests.get({plain: true});
output.quote_items_lead_request = await lead_requests.getQuote_items_lead_request({
transaction
});
output.interested_stone = await lead_requests.getInterested_stone({
transaction
});
output.interested_service = await lead_requests.getInterested_service({
transaction
});
output.related_project = await lead_requests.getRelated_project({
transaction
});
output.reference_files = await lead_requests.getReference_files({
transaction
});
output.assigned_to = await lead_requests.getAssigned_to({
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.stones,
as: 'interested_stone',
where: filter.interested_stone ? {
[Op.or]: [
{ id: { [Op.in]: filter.interested_stone.split('|').map(term => Utils.uuid(term)) } },
{
name_ar: {
[Op.or]: filter.interested_stone.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.services,
as: 'interested_service',
where: filter.interested_service ? {
[Op.or]: [
{ id: { [Op.in]: filter.interested_service.split('|').map(term => Utils.uuid(term)) } },
{
name_ar: {
[Op.or]: filter.interested_service.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.projects,
as: 'related_project',
where: filter.related_project ? {
[Op.or]: [
{ id: { [Op.in]: filter.related_project.split('|').map(term => Utils.uuid(term)) } },
{
name_ar: {
[Op.or]: filter.related_project.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'assigned_to',
where: filter.assigned_to ? {
[Op.or]: [
{ id: { [Op.in]: filter.assigned_to.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.assigned_to.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.file,
as: 'reference_files',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.full_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'lead_requests',
'full_name',
filter.full_name,
),
};
}
if (filter.company_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'lead_requests',
'company_name',
filter.company_name,
),
};
}
if (filter.email) {
where = {
...where,
[Op.and]: Utils.ilike(
'lead_requests',
'email',
filter.email,
),
};
}
if (filter.phone) {
where = {
...where,
[Op.and]: Utils.ilike(
'lead_requests',
'phone',
filter.phone,
),
};
}
if (filter.message_ar) {
where = {
...where,
[Op.and]: Utils.ilike(
'lead_requests',
'message_ar',
filter.message_ar,
),
};
}
if (filter.internal_notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'lead_requests',
'internal_notes',
filter.internal_notes,
),
};
}
if (filter.preferred_contact_timeRange) {
const [start, end] = filter.preferred_contact_timeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
preferred_contact_time: {
...where.preferred_contact_time,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
preferred_contact_time: {
...where.preferred_contact_time,
[Op.lte]: end,
},
};
}
}
if (filter.last_contacted_atRange) {
const [start, end] = filter.last_contacted_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
last_contacted_at: {
...where.last_contacted_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
last_contacted_at: {
...where.last_contacted_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.request_type) {
where = {
...where,
request_type: filter.request_type,
};
}
if (filter.customer_type) {
where = {
...where,
customer_type: filter.customer_type,
};
}
if (filter.lead_status) {
where = {
...where,
lead_status: filter.lead_status,
};
}
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.lead_requests.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'lead_requests',
'full_name',
query,
),
],
};
}
const records = await db.lead_requests.findAll({
attributes: [ 'id', 'full_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['full_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.full_name,
}));
}
};

View File

@ -0,0 +1,527 @@
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 Media_libraryDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const media_library = await db.media_library.create(
{
id: data.id || undefined,
media_type: data.media_type
||
null
,
title_ar: data.title_ar
||
null
,
alt_text_ar: data.alt_text_ar
||
null
,
source_note_ar: data.source_note_ar
||
null
,
is_public: data.is_public
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.media_library.getTableName(),
belongsToColumn: 'images',
belongsToId: media_library.id,
},
data.images,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.media_library.getTableName(),
belongsToColumn: 'files',
belongsToId: media_library.id,
},
data.files,
options,
);
return media_library;
}
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 media_libraryData = data.map((item, index) => ({
id: item.id || undefined,
media_type: item.media_type
||
null
,
title_ar: item.title_ar
||
null
,
alt_text_ar: item.alt_text_ar
||
null
,
source_note_ar: item.source_note_ar
||
null
,
is_public: item.is_public
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const media_library = await db.media_library.bulkCreate(media_libraryData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < media_library.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.media_library.getTableName(),
belongsToColumn: 'images',
belongsToId: media_library[i].id,
},
data[i].images,
options,
);
}
for (let i = 0; i < media_library.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.media_library.getTableName(),
belongsToColumn: 'files',
belongsToId: media_library[i].id,
},
data[i].files,
options,
);
}
return media_library;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const media_library = await db.media_library.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.media_type !== undefined) updatePayload.media_type = data.media_type;
if (data.title_ar !== undefined) updatePayload.title_ar = data.title_ar;
if (data.alt_text_ar !== undefined) updatePayload.alt_text_ar = data.alt_text_ar;
if (data.source_note_ar !== undefined) updatePayload.source_note_ar = data.source_note_ar;
if (data.is_public !== undefined) updatePayload.is_public = data.is_public;
updatePayload.updatedById = currentUser.id;
await media_library.update(updatePayload, {transaction});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.media_library.getTableName(),
belongsToColumn: 'images',
belongsToId: media_library.id,
},
data.images,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.media_library.getTableName(),
belongsToColumn: 'files',
belongsToId: media_library.id,
},
data.files,
options,
);
return media_library;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const media_library = await db.media_library.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of media_library) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of media_library) {
await record.destroy({transaction});
}
});
return media_library;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const media_library = await db.media_library.findByPk(id, options);
await media_library.update({
deletedBy: currentUser.id
}, {
transaction,
});
await media_library.destroy({
transaction
});
return media_library;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const media_library = await db.media_library.findOne(
{ where },
{ transaction },
);
if (!media_library) {
return media_library;
}
const output = media_library.get({plain: true});
output.images = await media_library.getImages({
transaction
});
output.files = await media_library.getFiles({
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.file,
as: 'images',
},
{
model: db.file,
as: 'files',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.title_ar) {
where = {
...where,
[Op.and]: Utils.ilike(
'media_library',
'title_ar',
filter.title_ar,
),
};
}
if (filter.alt_text_ar) {
where = {
...where,
[Op.and]: Utils.ilike(
'media_library',
'alt_text_ar',
filter.alt_text_ar,
),
};
}
if (filter.source_note_ar) {
where = {
...where,
[Op.and]: Utils.ilike(
'media_library',
'source_note_ar',
filter.source_note_ar,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.media_type) {
where = {
...where,
media_type: filter.media_type,
};
}
if (filter.is_public) {
where = {
...where,
is_public: filter.is_public,
};
}
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.media_library.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(
'media_library',
'title_ar',
query,
),
],
};
}
const records = await db.media_library.findAll({
attributes: [ 'id', 'title_ar' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['title_ar', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.title_ar,
}));
}
};

View File

@ -0,0 +1,353 @@
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,573 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Project_mediaDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const project_media = await db.project_media.create(
{
id: data.id || undefined,
media_kind: data.media_kind
||
null
,
media_role: data.media_role
||
null
,
caption_ar: data.caption_ar
||
null
,
sort_order: data.sort_order
||
null
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await project_media.setProject( data.project || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.project_media.getTableName(),
belongsToColumn: 'images',
belongsToId: project_media.id,
},
data.images,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.project_media.getTableName(),
belongsToColumn: 'videos',
belongsToId: project_media.id,
},
data.videos,
options,
);
return project_media;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const project_mediaData = data.map((item, index) => ({
id: item.id || undefined,
media_kind: item.media_kind
||
null
,
media_role: item.media_role
||
null
,
caption_ar: item.caption_ar
||
null
,
sort_order: item.sort_order
||
null
,
is_active: item.is_active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const project_media = await db.project_media.bulkCreate(project_mediaData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < project_media.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.project_media.getTableName(),
belongsToColumn: 'images',
belongsToId: project_media[i].id,
},
data[i].images,
options,
);
}
for (let i = 0; i < project_media.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.project_media.getTableName(),
belongsToColumn: 'videos',
belongsToId: project_media[i].id,
},
data[i].videos,
options,
);
}
return project_media;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const project_media = await db.project_media.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.media_kind !== undefined) updatePayload.media_kind = data.media_kind;
if (data.media_role !== undefined) updatePayload.media_role = data.media_role;
if (data.caption_ar !== undefined) updatePayload.caption_ar = data.caption_ar;
if (data.sort_order !== undefined) updatePayload.sort_order = data.sort_order;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await project_media.update(updatePayload, {transaction});
if (data.project !== undefined) {
await project_media.setProject(
data.project,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.project_media.getTableName(),
belongsToColumn: 'images',
belongsToId: project_media.id,
},
data.images,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.project_media.getTableName(),
belongsToColumn: 'videos',
belongsToId: project_media.id,
},
data.videos,
options,
);
return project_media;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const project_media = await db.project_media.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of project_media) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of project_media) {
await record.destroy({transaction});
}
});
return project_media;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const project_media = await db.project_media.findByPk(id, options);
await project_media.update({
deletedBy: currentUser.id
}, {
transaction,
});
await project_media.destroy({
transaction
});
return project_media;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const project_media = await db.project_media.findOne(
{ where },
{ transaction },
);
if (!project_media) {
return project_media;
}
const output = project_media.get({plain: true});
output.project = await project_media.getProject({
transaction
});
output.images = await project_media.getImages({
transaction
});
output.videos = await project_media.getVideos({
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.projects,
as: 'project',
where: filter.project ? {
[Op.or]: [
{ id: { [Op.in]: filter.project.split('|').map(term => Utils.uuid(term)) } },
{
name_ar: {
[Op.or]: filter.project.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.file,
as: 'images',
},
{
model: db.file,
as: 'videos',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.caption_ar) {
where = {
...where,
[Op.and]: Utils.ilike(
'project_media',
'caption_ar',
filter.caption_ar,
),
};
}
if (filter.sort_orderRange) {
const [start, end] = filter.sort_orderRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sort_order: {
...where.sort_order,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sort_order: {
...where.sort_order,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.media_kind) {
where = {
...where,
media_kind: filter.media_kind,
};
}
if (filter.media_role) {
where = {
...where,
media_role: filter.media_role,
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
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.project_media.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'project_media',
'caption_ar',
query,
),
],
};
}
const records = await db.project_media.findAll({
attributes: [ 'id', 'caption_ar' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['caption_ar', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.caption_ar,
}));
}
};

View File

@ -0,0 +1,865 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class ProjectsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const projects = await db.projects.create(
{
id: data.id || undefined,
name_ar: data.name_ar
||
null
,
slug: data.slug
||
null
,
project_scope: data.project_scope
||
null
,
location_ar: data.location_ar
||
null
,
summary_ar: data.summary_ar
||
null
,
description_ar: data.description_ar
||
null
,
started_at: data.started_at
||
null
,
completed_at: data.completed_at
||
null
,
is_featured: data.is_featured
||
false
,
is_published: data.is_published
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await projects.setStones_used(data.stones_used || [], {
transaction,
});
await projects.setApplications(data.applications || [], {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.projects.getTableName(),
belongsToColumn: 'before_images',
belongsToId: projects.id,
},
data.before_images,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.projects.getTableName(),
belongsToColumn: 'after_images',
belongsToId: projects.id,
},
data.after_images,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.projects.getTableName(),
belongsToColumn: 'gallery_images',
belongsToId: projects.id,
},
data.gallery_images,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.projects.getTableName(),
belongsToColumn: 'attachments',
belongsToId: projects.id,
},
data.attachments,
options,
);
return projects;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const projectsData = data.map((item, index) => ({
id: item.id || undefined,
name_ar: item.name_ar
||
null
,
slug: item.slug
||
null
,
project_scope: item.project_scope
||
null
,
location_ar: item.location_ar
||
null
,
summary_ar: item.summary_ar
||
null
,
description_ar: item.description_ar
||
null
,
started_at: item.started_at
||
null
,
completed_at: item.completed_at
||
null
,
is_featured: item.is_featured
||
false
,
is_published: item.is_published
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const projects = await db.projects.bulkCreate(projectsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < projects.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.projects.getTableName(),
belongsToColumn: 'before_images',
belongsToId: projects[i].id,
},
data[i].before_images,
options,
);
}
for (let i = 0; i < projects.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.projects.getTableName(),
belongsToColumn: 'after_images',
belongsToId: projects[i].id,
},
data[i].after_images,
options,
);
}
for (let i = 0; i < projects.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.projects.getTableName(),
belongsToColumn: 'gallery_images',
belongsToId: projects[i].id,
},
data[i].gallery_images,
options,
);
}
for (let i = 0; i < projects.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.projects.getTableName(),
belongsToColumn: 'attachments',
belongsToId: projects[i].id,
},
data[i].attachments,
options,
);
}
return projects;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const projects = await db.projects.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name_ar !== undefined) updatePayload.name_ar = data.name_ar;
if (data.slug !== undefined) updatePayload.slug = data.slug;
if (data.project_scope !== undefined) updatePayload.project_scope = data.project_scope;
if (data.location_ar !== undefined) updatePayload.location_ar = data.location_ar;
if (data.summary_ar !== undefined) updatePayload.summary_ar = data.summary_ar;
if (data.description_ar !== undefined) updatePayload.description_ar = data.description_ar;
if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
if (data.completed_at !== undefined) updatePayload.completed_at = data.completed_at;
if (data.is_featured !== undefined) updatePayload.is_featured = data.is_featured;
if (data.is_published !== undefined) updatePayload.is_published = data.is_published;
updatePayload.updatedById = currentUser.id;
await projects.update(updatePayload, {transaction});
if (data.stones_used !== undefined) {
await projects.setStones_used(data.stones_used, { transaction });
}
if (data.applications !== undefined) {
await projects.setApplications(data.applications, { transaction });
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.projects.getTableName(),
belongsToColumn: 'before_images',
belongsToId: projects.id,
},
data.before_images,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.projects.getTableName(),
belongsToColumn: 'after_images',
belongsToId: projects.id,
},
data.after_images,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.projects.getTableName(),
belongsToColumn: 'gallery_images',
belongsToId: projects.id,
},
data.gallery_images,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.projects.getTableName(),
belongsToColumn: 'attachments',
belongsToId: projects.id,
},
data.attachments,
options,
);
return projects;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const projects = await db.projects.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of projects) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of projects) {
await record.destroy({transaction});
}
});
return projects;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const projects = await db.projects.findByPk(id, options);
await projects.update({
deletedBy: currentUser.id
}, {
transaction,
});
await projects.destroy({
transaction
});
return projects;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const projects = await db.projects.findOne(
{ where },
{ transaction },
);
if (!projects) {
return projects;
}
const output = projects.get({plain: true});
output.project_media_project = await projects.getProject_media_project({
transaction
});
output.lead_requests_related_project = await projects.getLead_requests_related_project({
transaction
});
output.stones_used = await projects.getStones_used({
transaction
});
output.applications = await projects.getApplications({
transaction
});
output.before_images = await projects.getBefore_images({
transaction
});
output.after_images = await projects.getAfter_images({
transaction
});
output.gallery_images = await projects.getGallery_images({
transaction
});
output.attachments = await projects.getAttachments({
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.stones,
as: 'stones_used',
required: false,
},
{
model: db.applications,
as: 'applications',
required: false,
},
{
model: db.file,
as: 'before_images',
},
{
model: db.file,
as: 'after_images',
},
{
model: db.file,
as: 'gallery_images',
},
{
model: db.file,
as: 'attachments',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name_ar) {
where = {
...where,
[Op.and]: Utils.ilike(
'projects',
'name_ar',
filter.name_ar,
),
};
}
if (filter.slug) {
where = {
...where,
[Op.and]: Utils.ilike(
'projects',
'slug',
filter.slug,
),
};
}
if (filter.location_ar) {
where = {
...where,
[Op.and]: Utils.ilike(
'projects',
'location_ar',
filter.location_ar,
),
};
}
if (filter.summary_ar) {
where = {
...where,
[Op.and]: Utils.ilike(
'projects',
'summary_ar',
filter.summary_ar,
),
};
}
if (filter.description_ar) {
where = {
...where,
[Op.and]: Utils.ilike(
'projects',
'description_ar',
filter.description_ar,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
started_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
completed_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.started_atRange) {
const [start, end] = filter.started_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
started_at: {
...where.started_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
started_at: {
...where.started_at,
[Op.lte]: end,
},
};
}
}
if (filter.completed_atRange) {
const [start, end] = filter.completed_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
completed_at: {
...where.completed_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
completed_at: {
...where.completed_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.project_scope) {
where = {
...where,
project_scope: filter.project_scope,
};
}
if (filter.is_featured) {
where = {
...where,
is_featured: filter.is_featured,
};
}
if (filter.is_published) {
where = {
...where,
is_published: filter.is_published,
};
}
if (filter.stones_used) {
const searchTerms = filter.stones_used.split('|');
include = [
{
model: db.stones,
as: 'stones_used_filter',
required: searchTerms.length > 0,
where: searchTerms.length > 0 ? {
[Op.or]: [
{ id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
{
name_ar: {
[Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
}
}
]
} : undefined
},
...include,
]
}
if (filter.applications) {
const searchTerms = filter.applications.split('|');
include = [
{
model: db.applications,
as: 'applications_filter',
required: searchTerms.length > 0,
where: searchTerms.length > 0 ? {
[Op.or]: [
{ id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
{
name_ar: {
[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.projects.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'projects',
'name_ar',
query,
),
],
};
}
const records = await db.projects.findAll({
attributes: [ 'id', 'name_ar' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['name_ar', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.name_ar,
}));
}
};

View File

@ -0,0 +1,669 @@
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 Quote_itemsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const quote_items = await db.quote_items.create(
{
id: data.id || undefined,
item_description_ar: data.item_description_ar
||
null
,
quantity: data.quantity
||
null
,
unit: data.unit
||
null
,
unit_price: data.unit_price
||
null
,
discount_amount: data.discount_amount
||
null
,
tax_amount: data.tax_amount
||
null
,
line_total: data.line_total
||
null
,
sort_order: data.sort_order
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await quote_items.setLead_request( data.lead_request || null, {
transaction,
});
await quote_items.setStone_variant( data.stone_variant || null, {
transaction,
});
return quote_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 quote_itemsData = data.map((item, index) => ({
id: item.id || undefined,
item_description_ar: item.item_description_ar
||
null
,
quantity: item.quantity
||
null
,
unit: item.unit
||
null
,
unit_price: item.unit_price
||
null
,
discount_amount: item.discount_amount
||
null
,
tax_amount: item.tax_amount
||
null
,
line_total: item.line_total
||
null
,
sort_order: item.sort_order
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const quote_items = await db.quote_items.bulkCreate(quote_itemsData, { transaction });
// For each item created, replace relation files
return quote_items;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const quote_items = await db.quote_items.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.item_description_ar !== undefined) updatePayload.item_description_ar = data.item_description_ar;
if (data.quantity !== undefined) updatePayload.quantity = data.quantity;
if (data.unit !== undefined) updatePayload.unit = data.unit;
if (data.unit_price !== undefined) updatePayload.unit_price = data.unit_price;
if (data.discount_amount !== undefined) updatePayload.discount_amount = data.discount_amount;
if (data.tax_amount !== undefined) updatePayload.tax_amount = data.tax_amount;
if (data.line_total !== undefined) updatePayload.line_total = data.line_total;
if (data.sort_order !== undefined) updatePayload.sort_order = data.sort_order;
updatePayload.updatedById = currentUser.id;
await quote_items.update(updatePayload, {transaction});
if (data.lead_request !== undefined) {
await quote_items.setLead_request(
data.lead_request,
{ transaction }
);
}
if (data.stone_variant !== undefined) {
await quote_items.setStone_variant(
data.stone_variant,
{ transaction }
);
}
return quote_items;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const quote_items = await db.quote_items.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of quote_items) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of quote_items) {
await record.destroy({transaction});
}
});
return quote_items;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const quote_items = await db.quote_items.findByPk(id, options);
await quote_items.update({
deletedBy: currentUser.id
}, {
transaction,
});
await quote_items.destroy({
transaction
});
return quote_items;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const quote_items = await db.quote_items.findOne(
{ where },
{ transaction },
);
if (!quote_items) {
return quote_items;
}
const output = quote_items.get({plain: true});
output.lead_request = await quote_items.getLead_request({
transaction
});
output.stone_variant = await quote_items.getStone_variant({
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.lead_requests,
as: 'lead_request',
where: filter.lead_request ? {
[Op.or]: [
{ id: { [Op.in]: filter.lead_request.split('|').map(term => Utils.uuid(term)) } },
{
full_name: {
[Op.or]: filter.lead_request.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.stone_variants,
as: 'stone_variant',
where: filter.stone_variant ? {
[Op.or]: [
{ id: { [Op.in]: filter.stone_variant.split('|').map(term => Utils.uuid(term)) } },
{
sku: {
[Op.or]: filter.stone_variant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.item_description_ar) {
where = {
...where,
[Op.and]: Utils.ilike(
'quote_items',
'item_description_ar',
filter.item_description_ar,
),
};
}
if (filter.quantityRange) {
const [start, end] = filter.quantityRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
quantity: {
...where.quantity,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
quantity: {
...where.quantity,
[Op.lte]: end,
},
};
}
}
if (filter.unit_priceRange) {
const [start, end] = filter.unit_priceRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
unit_price: {
...where.unit_price,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
unit_price: {
...where.unit_price,
[Op.lte]: end,
},
};
}
}
if (filter.discount_amountRange) {
const [start, end] = filter.discount_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
discount_amount: {
...where.discount_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
discount_amount: {
...where.discount_amount,
[Op.lte]: end,
},
};
}
}
if (filter.tax_amountRange) {
const [start, end] = filter.tax_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
tax_amount: {
...where.tax_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
tax_amount: {
...where.tax_amount,
[Op.lte]: end,
},
};
}
}
if (filter.line_totalRange) {
const [start, end] = filter.line_totalRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
line_total: {
...where.line_total,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
line_total: {
...where.line_total,
[Op.lte]: end,
},
};
}
}
if (filter.sort_orderRange) {
const [start, end] = filter.sort_orderRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sort_order: {
...where.sort_order,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sort_order: {
...where.sort_order,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.unit) {
where = {
...where,
unit: filter.unit,
};
}
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.quote_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(
'quote_items',
'item_description_ar',
query,
),
],
};
}
const records = await db.quote_items.findAll({
attributes: [ 'id', 'item_description_ar' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['item_description_ar', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.item_description_ar,
}));
}
};

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

@ -0,0 +1,423 @@
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,485 @@
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 Seo_pagesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const seo_pages = await db.seo_pages.create(
{
id: data.id || undefined,
page_key: data.page_key
||
null
,
title_ar: data.title_ar
||
null
,
description_ar: data.description_ar
||
null
,
canonical_url: data.canonical_url
||
null
,
indexable: data.indexable
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.seo_pages.getTableName(),
belongsToColumn: 'structured_data_jsonld',
belongsToId: seo_pages.id,
},
data.structured_data_jsonld,
options,
);
return seo_pages;
}
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 seo_pagesData = data.map((item, index) => ({
id: item.id || undefined,
page_key: item.page_key
||
null
,
title_ar: item.title_ar
||
null
,
description_ar: item.description_ar
||
null
,
canonical_url: item.canonical_url
||
null
,
indexable: item.indexable
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const seo_pages = await db.seo_pages.bulkCreate(seo_pagesData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < seo_pages.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.seo_pages.getTableName(),
belongsToColumn: 'structured_data_jsonld',
belongsToId: seo_pages[i].id,
},
data[i].structured_data_jsonld,
options,
);
}
return seo_pages;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const seo_pages = await db.seo_pages.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.page_key !== undefined) updatePayload.page_key = data.page_key;
if (data.title_ar !== undefined) updatePayload.title_ar = data.title_ar;
if (data.description_ar !== undefined) updatePayload.description_ar = data.description_ar;
if (data.canonical_url !== undefined) updatePayload.canonical_url = data.canonical_url;
if (data.indexable !== undefined) updatePayload.indexable = data.indexable;
updatePayload.updatedById = currentUser.id;
await seo_pages.update(updatePayload, {transaction});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.seo_pages.getTableName(),
belongsToColumn: 'structured_data_jsonld',
belongsToId: seo_pages.id,
},
data.structured_data_jsonld,
options,
);
return seo_pages;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const seo_pages = await db.seo_pages.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of seo_pages) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of seo_pages) {
await record.destroy({transaction});
}
});
return seo_pages;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const seo_pages = await db.seo_pages.findByPk(id, options);
await seo_pages.update({
deletedBy: currentUser.id
}, {
transaction,
});
await seo_pages.destroy({
transaction
});
return seo_pages;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const seo_pages = await db.seo_pages.findOne(
{ where },
{ transaction },
);
if (!seo_pages) {
return seo_pages;
}
const output = seo_pages.get({plain: true});
output.structured_data_jsonld = await seo_pages.getStructured_data_jsonld({
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.file,
as: 'structured_data_jsonld',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.title_ar) {
where = {
...where,
[Op.and]: Utils.ilike(
'seo_pages',
'title_ar',
filter.title_ar,
),
};
}
if (filter.description_ar) {
where = {
...where,
[Op.and]: Utils.ilike(
'seo_pages',
'description_ar',
filter.description_ar,
),
};
}
if (filter.canonical_url) {
where = {
...where,
[Op.and]: Utils.ilike(
'seo_pages',
'canonical_url',
filter.canonical_url,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.page_key) {
where = {
...where,
page_key: filter.page_key,
};
}
if (filter.indexable) {
where = {
...where,
indexable: filter.indexable,
};
}
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.seo_pages.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(
'seo_pages',
'title_ar',
query,
),
],
};
}
const records = await db.seo_pages.findAll({
attributes: [ 'id', 'title_ar' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['title_ar', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.title_ar,
}));
}
};

View File

@ -0,0 +1,464 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Service_technologiesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const service_technologies = await db.service_technologies.create(
{
id: data.id || undefined,
note_ar: data.note_ar
||
null
,
sort_order: data.sort_order
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await service_technologies.setService( data.service || null, {
transaction,
});
await service_technologies.setTechnology( data.technology || null, {
transaction,
});
return service_technologies;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const service_technologiesData = data.map((item, index) => ({
id: item.id || undefined,
note_ar: item.note_ar
||
null
,
sort_order: item.sort_order
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const service_technologies = await db.service_technologies.bulkCreate(service_technologiesData, { transaction });
// For each item created, replace relation files
return service_technologies;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const service_technologies = await db.service_technologies.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.note_ar !== undefined) updatePayload.note_ar = data.note_ar;
if (data.sort_order !== undefined) updatePayload.sort_order = data.sort_order;
updatePayload.updatedById = currentUser.id;
await service_technologies.update(updatePayload, {transaction});
if (data.service !== undefined) {
await service_technologies.setService(
data.service,
{ transaction }
);
}
if (data.technology !== undefined) {
await service_technologies.setTechnology(
data.technology,
{ transaction }
);
}
return service_technologies;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const service_technologies = await db.service_technologies.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of service_technologies) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of service_technologies) {
await record.destroy({transaction});
}
});
return service_technologies;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const service_technologies = await db.service_technologies.findByPk(id, options);
await service_technologies.update({
deletedBy: currentUser.id
}, {
transaction,
});
await service_technologies.destroy({
transaction
});
return service_technologies;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const service_technologies = await db.service_technologies.findOne(
{ where },
{ transaction },
);
if (!service_technologies) {
return service_technologies;
}
const output = service_technologies.get({plain: true});
output.service = await service_technologies.getService({
transaction
});
output.technology = await service_technologies.getTechnology({
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.services,
as: 'service',
where: filter.service ? {
[Op.or]: [
{ id: { [Op.in]: filter.service.split('|').map(term => Utils.uuid(term)) } },
{
name_ar: {
[Op.or]: filter.service.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.technologies,
as: 'technology',
where: filter.technology ? {
[Op.or]: [
{ id: { [Op.in]: filter.technology.split('|').map(term => Utils.uuid(term)) } },
{
name_ar: {
[Op.or]: filter.technology.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.note_ar) {
where = {
...where,
[Op.and]: Utils.ilike(
'service_technologies',
'note_ar',
filter.note_ar,
),
};
}
if (filter.sort_orderRange) {
const [start, end] = filter.sort_orderRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sort_order: {
...where.sort_order,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sort_order: {
...where.sort_order,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.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.service_technologies.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(
'service_technologies',
'note_ar',
query,
),
],
};
}
const records = await db.service_technologies.findAll({
attributes: [ 'id', 'note_ar' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['note_ar', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.note_ar,
}));
}
};

View File

@ -0,0 +1,618 @@
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 ServicesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const services = await db.services.create(
{
id: data.id || undefined,
name_ar: data.name_ar
||
null
,
slug: data.slug
||
null
,
service_type: data.service_type
||
null
,
summary_ar: data.summary_ar
||
null
,
description_ar: data.description_ar
||
null
,
sort_order: data.sort_order
||
null
,
is_featured: data.is_featured
||
false
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.services.getTableName(),
belongsToColumn: 'images',
belongsToId: services.id,
},
data.images,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.services.getTableName(),
belongsToColumn: 'brochure_files',
belongsToId: services.id,
},
data.brochure_files,
options,
);
return services;
}
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 servicesData = data.map((item, index) => ({
id: item.id || undefined,
name_ar: item.name_ar
||
null
,
slug: item.slug
||
null
,
service_type: item.service_type
||
null
,
summary_ar: item.summary_ar
||
null
,
description_ar: item.description_ar
||
null
,
sort_order: item.sort_order
||
null
,
is_featured: item.is_featured
||
false
,
is_active: item.is_active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const services = await db.services.bulkCreate(servicesData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < services.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.services.getTableName(),
belongsToColumn: 'images',
belongsToId: services[i].id,
},
data[i].images,
options,
);
}
for (let i = 0; i < services.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.services.getTableName(),
belongsToColumn: 'brochure_files',
belongsToId: services[i].id,
},
data[i].brochure_files,
options,
);
}
return services;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const services = await db.services.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name_ar !== undefined) updatePayload.name_ar = data.name_ar;
if (data.slug !== undefined) updatePayload.slug = data.slug;
if (data.service_type !== undefined) updatePayload.service_type = data.service_type;
if (data.summary_ar !== undefined) updatePayload.summary_ar = data.summary_ar;
if (data.description_ar !== undefined) updatePayload.description_ar = data.description_ar;
if (data.sort_order !== undefined) updatePayload.sort_order = data.sort_order;
if (data.is_featured !== undefined) updatePayload.is_featured = data.is_featured;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await services.update(updatePayload, {transaction});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.services.getTableName(),
belongsToColumn: 'images',
belongsToId: services.id,
},
data.images,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.services.getTableName(),
belongsToColumn: 'brochure_files',
belongsToId: services.id,
},
data.brochure_files,
options,
);
return services;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const services = await db.services.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of services) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of services) {
await record.destroy({transaction});
}
});
return services;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const services = await db.services.findByPk(id, options);
await services.update({
deletedBy: currentUser.id
}, {
transaction,
});
await services.destroy({
transaction
});
return services;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const services = await db.services.findOne(
{ where },
{ transaction },
);
if (!services) {
return services;
}
const output = services.get({plain: true});
output.service_technologies_service = await services.getService_technologies_service({
transaction
});
output.lead_requests_interested_service = await services.getLead_requests_interested_service({
transaction
});
output.images = await services.getImages({
transaction
});
output.brochure_files = await services.getBrochure_files({
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.file,
as: 'images',
},
{
model: db.file,
as: 'brochure_files',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name_ar) {
where = {
...where,
[Op.and]: Utils.ilike(
'services',
'name_ar',
filter.name_ar,
),
};
}
if (filter.slug) {
where = {
...where,
[Op.and]: Utils.ilike(
'services',
'slug',
filter.slug,
),
};
}
if (filter.summary_ar) {
where = {
...where,
[Op.and]: Utils.ilike(
'services',
'summary_ar',
filter.summary_ar,
),
};
}
if (filter.description_ar) {
where = {
...where,
[Op.and]: Utils.ilike(
'services',
'description_ar',
filter.description_ar,
),
};
}
if (filter.sort_orderRange) {
const [start, end] = filter.sort_orderRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sort_order: {
...where.sort_order,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sort_order: {
...where.sort_order,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.service_type) {
where = {
...where,
service_type: filter.service_type,
};
}
if (filter.is_featured) {
where = {
...where,
is_featured: filter.is_featured,
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
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.services.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(
'services',
'name_ar',
query,
),
],
};
}
const records = await db.services.findAll({
attributes: [ 'id', 'name_ar' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['name_ar', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.name_ar,
}));
}
};

View File

@ -0,0 +1,643 @@
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 Site_settingsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const site_settings = await db.site_settings.create(
{
id: data.id || undefined,
site_name_ar: data.site_name_ar
||
null
,
site_tagline_ar: data.site_tagline_ar
||
null
,
primary_font: data.primary_font
||
null
,
direction: data.direction
||
null
,
primary_color_hex: data.primary_color_hex
||
null
,
accent_color_hex: data.accent_color_hex
||
null
,
seo_default_title_ar: data.seo_default_title_ar
||
null
,
seo_default_description_ar: data.seo_default_description_ar
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.site_settings.getTableName(),
belongsToColumn: 'logo',
belongsToId: site_settings.id,
},
data.logo,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.site_settings.getTableName(),
belongsToColumn: 'favicon',
belongsToId: site_settings.id,
},
data.favicon,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.site_settings.getTableName(),
belongsToColumn: 'brand_guidelines',
belongsToId: site_settings.id,
},
data.brand_guidelines,
options,
);
return site_settings;
}
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 site_settingsData = data.map((item, index) => ({
id: item.id || undefined,
site_name_ar: item.site_name_ar
||
null
,
site_tagline_ar: item.site_tagline_ar
||
null
,
primary_font: item.primary_font
||
null
,
direction: item.direction
||
null
,
primary_color_hex: item.primary_color_hex
||
null
,
accent_color_hex: item.accent_color_hex
||
null
,
seo_default_title_ar: item.seo_default_title_ar
||
null
,
seo_default_description_ar: item.seo_default_description_ar
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const site_settings = await db.site_settings.bulkCreate(site_settingsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < site_settings.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.site_settings.getTableName(),
belongsToColumn: 'logo',
belongsToId: site_settings[i].id,
},
data[i].logo,
options,
);
}
for (let i = 0; i < site_settings.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.site_settings.getTableName(),
belongsToColumn: 'favicon',
belongsToId: site_settings[i].id,
},
data[i].favicon,
options,
);
}
for (let i = 0; i < site_settings.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.site_settings.getTableName(),
belongsToColumn: 'brand_guidelines',
belongsToId: site_settings[i].id,
},
data[i].brand_guidelines,
options,
);
}
return site_settings;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const site_settings = await db.site_settings.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.site_name_ar !== undefined) updatePayload.site_name_ar = data.site_name_ar;
if (data.site_tagline_ar !== undefined) updatePayload.site_tagline_ar = data.site_tagline_ar;
if (data.primary_font !== undefined) updatePayload.primary_font = data.primary_font;
if (data.direction !== undefined) updatePayload.direction = data.direction;
if (data.primary_color_hex !== undefined) updatePayload.primary_color_hex = data.primary_color_hex;
if (data.accent_color_hex !== undefined) updatePayload.accent_color_hex = data.accent_color_hex;
if (data.seo_default_title_ar !== undefined) updatePayload.seo_default_title_ar = data.seo_default_title_ar;
if (data.seo_default_description_ar !== undefined) updatePayload.seo_default_description_ar = data.seo_default_description_ar;
updatePayload.updatedById = currentUser.id;
await site_settings.update(updatePayload, {transaction});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.site_settings.getTableName(),
belongsToColumn: 'logo',
belongsToId: site_settings.id,
},
data.logo,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.site_settings.getTableName(),
belongsToColumn: 'favicon',
belongsToId: site_settings.id,
},
data.favicon,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.site_settings.getTableName(),
belongsToColumn: 'brand_guidelines',
belongsToId: site_settings.id,
},
data.brand_guidelines,
options,
);
return site_settings;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const site_settings = await db.site_settings.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of site_settings) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of site_settings) {
await record.destroy({transaction});
}
});
return site_settings;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const site_settings = await db.site_settings.findByPk(id, options);
await site_settings.update({
deletedBy: currentUser.id
}, {
transaction,
});
await site_settings.destroy({
transaction
});
return site_settings;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const site_settings = await db.site_settings.findOne(
{ where },
{ transaction },
);
if (!site_settings) {
return site_settings;
}
const output = site_settings.get({plain: true});
output.logo = await site_settings.getLogo({
transaction
});
output.favicon = await site_settings.getFavicon({
transaction
});
output.brand_guidelines = await site_settings.getBrand_guidelines({
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.file,
as: 'logo',
},
{
model: db.file,
as: 'favicon',
},
{
model: db.file,
as: 'brand_guidelines',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.site_name_ar) {
where = {
...where,
[Op.and]: Utils.ilike(
'site_settings',
'site_name_ar',
filter.site_name_ar,
),
};
}
if (filter.site_tagline_ar) {
where = {
...where,
[Op.and]: Utils.ilike(
'site_settings',
'site_tagline_ar',
filter.site_tagline_ar,
),
};
}
if (filter.primary_font) {
where = {
...where,
[Op.and]: Utils.ilike(
'site_settings',
'primary_font',
filter.primary_font,
),
};
}
if (filter.primary_color_hex) {
where = {
...where,
[Op.and]: Utils.ilike(
'site_settings',
'primary_color_hex',
filter.primary_color_hex,
),
};
}
if (filter.accent_color_hex) {
where = {
...where,
[Op.and]: Utils.ilike(
'site_settings',
'accent_color_hex',
filter.accent_color_hex,
),
};
}
if (filter.seo_default_title_ar) {
where = {
...where,
[Op.and]: Utils.ilike(
'site_settings',
'seo_default_title_ar',
filter.seo_default_title_ar,
),
};
}
if (filter.seo_default_description_ar) {
where = {
...where,
[Op.and]: Utils.ilike(
'site_settings',
'seo_default_description_ar',
filter.seo_default_description_ar,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.direction) {
where = {
...where,
direction: filter.direction,
};
}
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.site_settings.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(
'site_settings',
'site_name_ar',
query,
),
],
};
}
const records = await db.site_settings.findAll({
attributes: [ 'id', 'site_name_ar' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['site_name_ar', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.site_name_ar,
}));
}
};

View File

@ -0,0 +1,456 @@
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 Social_linksDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const social_links = await db.social_links.create(
{
id: data.id || undefined,
platform: data.platform
||
null
,
url: data.url
||
null
,
label_ar: data.label_ar
||
null
,
sort_order: data.sort_order
||
null
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return social_links;
}
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 social_linksData = data.map((item, index) => ({
id: item.id || undefined,
platform: item.platform
||
null
,
url: item.url
||
null
,
label_ar: item.label_ar
||
null
,
sort_order: item.sort_order
||
null
,
is_active: item.is_active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const social_links = await db.social_links.bulkCreate(social_linksData, { transaction });
// For each item created, replace relation files
return social_links;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const social_links = await db.social_links.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.platform !== undefined) updatePayload.platform = data.platform;
if (data.url !== undefined) updatePayload.url = data.url;
if (data.label_ar !== undefined) updatePayload.label_ar = data.label_ar;
if (data.sort_order !== undefined) updatePayload.sort_order = data.sort_order;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await social_links.update(updatePayload, {transaction});
return social_links;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const social_links = await db.social_links.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of social_links) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of social_links) {
await record.destroy({transaction});
}
});
return social_links;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const social_links = await db.social_links.findByPk(id, options);
await social_links.update({
deletedBy: currentUser.id
}, {
transaction,
});
await social_links.destroy({
transaction
});
return social_links;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const social_links = await db.social_links.findOne(
{ where },
{ transaction },
);
if (!social_links) {
return social_links;
}
const output = social_links.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.url) {
where = {
...where,
[Op.and]: Utils.ilike(
'social_links',
'url',
filter.url,
),
};
}
if (filter.label_ar) {
where = {
...where,
[Op.and]: Utils.ilike(
'social_links',
'label_ar',
filter.label_ar,
),
};
}
if (filter.sort_orderRange) {
const [start, end] = filter.sort_orderRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sort_order: {
...where.sort_order,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sort_order: {
...where.sort_order,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.platform) {
where = {
...where,
platform: filter.platform,
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
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.social_links.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(
'social_links',
'label_ar',
query,
),
],
};
}
const records = await db.social_links.findAll({
attributes: [ 'id', 'label_ar' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['label_ar', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.label_ar,
}));
}
};

View File

@ -0,0 +1,516 @@
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 Stone_3d_assetsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const stone_3d_assets = await db.stone_3d_assets.create(
{
id: data.id || undefined,
asset_type: data.asset_type
||
null
,
viewer_hint_ar: data.viewer_hint_ar
||
null
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await stone_3d_assets.setStone( data.stone || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.stone_3d_assets.getTableName(),
belongsToColumn: 'asset_file',
belongsToId: stone_3d_assets.id,
},
data.asset_file,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.stone_3d_assets.getTableName(),
belongsToColumn: 'preview_images',
belongsToId: stone_3d_assets.id,
},
data.preview_images,
options,
);
return stone_3d_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 stone_3d_assetsData = data.map((item, index) => ({
id: item.id || undefined,
asset_type: item.asset_type
||
null
,
viewer_hint_ar: item.viewer_hint_ar
||
null
,
is_active: item.is_active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const stone_3d_assets = await db.stone_3d_assets.bulkCreate(stone_3d_assetsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < stone_3d_assets.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.stone_3d_assets.getTableName(),
belongsToColumn: 'asset_file',
belongsToId: stone_3d_assets[i].id,
},
data[i].asset_file,
options,
);
}
for (let i = 0; i < stone_3d_assets.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.stone_3d_assets.getTableName(),
belongsToColumn: 'preview_images',
belongsToId: stone_3d_assets[i].id,
},
data[i].preview_images,
options,
);
}
return stone_3d_assets;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const stone_3d_assets = await db.stone_3d_assets.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.asset_type !== undefined) updatePayload.asset_type = data.asset_type;
if (data.viewer_hint_ar !== undefined) updatePayload.viewer_hint_ar = data.viewer_hint_ar;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await stone_3d_assets.update(updatePayload, {transaction});
if (data.stone !== undefined) {
await stone_3d_assets.setStone(
data.stone,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.stone_3d_assets.getTableName(),
belongsToColumn: 'asset_file',
belongsToId: stone_3d_assets.id,
},
data.asset_file,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.stone_3d_assets.getTableName(),
belongsToColumn: 'preview_images',
belongsToId: stone_3d_assets.id,
},
data.preview_images,
options,
);
return stone_3d_assets;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const stone_3d_assets = await db.stone_3d_assets.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of stone_3d_assets) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of stone_3d_assets) {
await record.destroy({transaction});
}
});
return stone_3d_assets;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const stone_3d_assets = await db.stone_3d_assets.findByPk(id, options);
await stone_3d_assets.update({
deletedBy: currentUser.id
}, {
transaction,
});
await stone_3d_assets.destroy({
transaction
});
return stone_3d_assets;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const stone_3d_assets = await db.stone_3d_assets.findOne(
{ where },
{ transaction },
);
if (!stone_3d_assets) {
return stone_3d_assets;
}
const output = stone_3d_assets.get({plain: true});
output.stone = await stone_3d_assets.getStone({
transaction
});
output.asset_file = await stone_3d_assets.getAsset_file({
transaction
});
output.preview_images = await stone_3d_assets.getPreview_images({
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.stones,
as: 'stone',
where: filter.stone ? {
[Op.or]: [
{ id: { [Op.in]: filter.stone.split('|').map(term => Utils.uuid(term)) } },
{
name_ar: {
[Op.or]: filter.stone.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.file,
as: 'asset_file',
},
{
model: db.file,
as: 'preview_images',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.viewer_hint_ar) {
where = {
...where,
[Op.and]: Utils.ilike(
'stone_3d_assets',
'viewer_hint_ar',
filter.viewer_hint_ar,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.asset_type) {
where = {
...where,
asset_type: filter.asset_type,
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
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.stone_3d_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(
'stone_3d_assets',
'viewer_hint_ar',
query,
),
],
};
}
const records = await db.stone_3d_assets.findAll({
attributes: [ 'id', 'viewer_hint_ar' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['viewer_hint_ar', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.viewer_hint_ar,
}));
}
};

View File

@ -0,0 +1,526 @@
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 Stone_categoriesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const stone_categories = await db.stone_categories.create(
{
id: data.id || undefined,
name_ar: data.name_ar
||
null
,
slug: data.slug
||
null
,
description_ar: data.description_ar
||
null
,
sort_order: data.sort_order
||
null
,
is_active: data.is_active
||
false
,
category_type: data.category_type
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.stone_categories.getTableName(),
belongsToColumn: 'cover_image',
belongsToId: stone_categories.id,
},
data.cover_image,
options,
);
return stone_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 stone_categoriesData = data.map((item, index) => ({
id: item.id || undefined,
name_ar: item.name_ar
||
null
,
slug: item.slug
||
null
,
description_ar: item.description_ar
||
null
,
sort_order: item.sort_order
||
null
,
is_active: item.is_active
||
false
,
category_type: item.category_type
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const stone_categories = await db.stone_categories.bulkCreate(stone_categoriesData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < stone_categories.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.stone_categories.getTableName(),
belongsToColumn: 'cover_image',
belongsToId: stone_categories[i].id,
},
data[i].cover_image,
options,
);
}
return stone_categories;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const stone_categories = await db.stone_categories.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name_ar !== undefined) updatePayload.name_ar = data.name_ar;
if (data.slug !== undefined) updatePayload.slug = data.slug;
if (data.description_ar !== undefined) updatePayload.description_ar = data.description_ar;
if (data.sort_order !== undefined) updatePayload.sort_order = data.sort_order;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
if (data.category_type !== undefined) updatePayload.category_type = data.category_type;
updatePayload.updatedById = currentUser.id;
await stone_categories.update(updatePayload, {transaction});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.stone_categories.getTableName(),
belongsToColumn: 'cover_image',
belongsToId: stone_categories.id,
},
data.cover_image,
options,
);
return stone_categories;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const stone_categories = await db.stone_categories.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of stone_categories) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of stone_categories) {
await record.destroy({transaction});
}
});
return stone_categories;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const stone_categories = await db.stone_categories.findByPk(id, options);
await stone_categories.update({
deletedBy: currentUser.id
}, {
transaction,
});
await stone_categories.destroy({
transaction
});
return stone_categories;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const stone_categories = await db.stone_categories.findOne(
{ where },
{ transaction },
);
if (!stone_categories) {
return stone_categories;
}
const output = stone_categories.get({plain: true});
output.stones_category = await stone_categories.getStones_category({
transaction
});
output.cover_image = await stone_categories.getCover_image({
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.file,
as: 'cover_image',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name_ar) {
where = {
...where,
[Op.and]: Utils.ilike(
'stone_categories',
'name_ar',
filter.name_ar,
),
};
}
if (filter.slug) {
where = {
...where,
[Op.and]: Utils.ilike(
'stone_categories',
'slug',
filter.slug,
),
};
}
if (filter.description_ar) {
where = {
...where,
[Op.and]: Utils.ilike(
'stone_categories',
'description_ar',
filter.description_ar,
),
};
}
if (filter.sort_orderRange) {
const [start, end] = filter.sort_orderRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sort_order: {
...where.sort_order,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sort_order: {
...where.sort_order,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
if (filter.category_type) {
where = {
...where,
category_type: filter.category_type,
};
}
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.stone_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(
'stone_categories',
'name_ar',
query,
),
],
};
}
const records = await db.stone_categories.findAll({
attributes: [ 'id', 'name_ar' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['name_ar', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.name_ar,
}));
}
};

View File

@ -0,0 +1,482 @@
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 Stone_colorsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const stone_colors = await db.stone_colors.create(
{
id: data.id || undefined,
name_ar: data.name_ar
||
null
,
hex: data.hex
||
null
,
sort_order: data.sort_order
||
null
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.stone_colors.getTableName(),
belongsToColumn: 'swatch_image',
belongsToId: stone_colors.id,
},
data.swatch_image,
options,
);
return stone_colors;
}
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 stone_colorsData = data.map((item, index) => ({
id: item.id || undefined,
name_ar: item.name_ar
||
null
,
hex: item.hex
||
null
,
sort_order: item.sort_order
||
null
,
is_active: item.is_active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const stone_colors = await db.stone_colors.bulkCreate(stone_colorsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < stone_colors.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.stone_colors.getTableName(),
belongsToColumn: 'swatch_image',
belongsToId: stone_colors[i].id,
},
data[i].swatch_image,
options,
);
}
return stone_colors;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const stone_colors = await db.stone_colors.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name_ar !== undefined) updatePayload.name_ar = data.name_ar;
if (data.hex !== undefined) updatePayload.hex = data.hex;
if (data.sort_order !== undefined) updatePayload.sort_order = data.sort_order;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await stone_colors.update(updatePayload, {transaction});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.stone_colors.getTableName(),
belongsToColumn: 'swatch_image',
belongsToId: stone_colors.id,
},
data.swatch_image,
options,
);
return stone_colors;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const stone_colors = await db.stone_colors.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of stone_colors) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of stone_colors) {
await record.destroy({transaction});
}
});
return stone_colors;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const stone_colors = await db.stone_colors.findByPk(id, options);
await stone_colors.update({
deletedBy: currentUser.id
}, {
transaction,
});
await stone_colors.destroy({
transaction
});
return stone_colors;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const stone_colors = await db.stone_colors.findOne(
{ where },
{ transaction },
);
if (!stone_colors) {
return stone_colors;
}
const output = stone_colors.get({plain: true});
output.stones_color = await stone_colors.getStones_color({
transaction
});
output.swatch_image = await stone_colors.getSwatch_image({
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.file,
as: 'swatch_image',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name_ar) {
where = {
...where,
[Op.and]: Utils.ilike(
'stone_colors',
'name_ar',
filter.name_ar,
),
};
}
if (filter.hex) {
where = {
...where,
[Op.and]: Utils.ilike(
'stone_colors',
'hex',
filter.hex,
),
};
}
if (filter.sort_orderRange) {
const [start, end] = filter.sort_orderRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sort_order: {
...where.sort_order,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sort_order: {
...where.sort_order,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
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.stone_colors.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(
'stone_colors',
'name_ar',
query,
),
],
};
}
const records = await db.stone_colors.findAll({
attributes: [ 'id', 'name_ar' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['name_ar', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.name_ar,
}));
}
};

View File

@ -0,0 +1,707 @@
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 Stone_variantsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const stone_variants = await db.stone_variants.create(
{
id: data.id || undefined,
variant_type: data.variant_type
||
null
,
sku: data.sku
||
null
,
length_mm: data.length_mm
||
null
,
width_mm: data.width_mm
||
null
,
thickness_mm: data.thickness_mm
||
null
,
weight_kg: data.weight_kg
||
null
,
availability_status: data.availability_status
||
null
,
base_price: data.base_price
||
null
,
price_note_ar: data.price_note_ar
||
null
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await stone_variants.setStone( data.stone || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.stone_variants.getTableName(),
belongsToColumn: 'images',
belongsToId: stone_variants.id,
},
data.images,
options,
);
return stone_variants;
}
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 stone_variantsData = data.map((item, index) => ({
id: item.id || undefined,
variant_type: item.variant_type
||
null
,
sku: item.sku
||
null
,
length_mm: item.length_mm
||
null
,
width_mm: item.width_mm
||
null
,
thickness_mm: item.thickness_mm
||
null
,
weight_kg: item.weight_kg
||
null
,
availability_status: item.availability_status
||
null
,
base_price: item.base_price
||
null
,
price_note_ar: item.price_note_ar
||
null
,
is_active: item.is_active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const stone_variants = await db.stone_variants.bulkCreate(stone_variantsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < stone_variants.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.stone_variants.getTableName(),
belongsToColumn: 'images',
belongsToId: stone_variants[i].id,
},
data[i].images,
options,
);
}
return stone_variants;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const stone_variants = await db.stone_variants.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.variant_type !== undefined) updatePayload.variant_type = data.variant_type;
if (data.sku !== undefined) updatePayload.sku = data.sku;
if (data.length_mm !== undefined) updatePayload.length_mm = data.length_mm;
if (data.width_mm !== undefined) updatePayload.width_mm = data.width_mm;
if (data.thickness_mm !== undefined) updatePayload.thickness_mm = data.thickness_mm;
if (data.weight_kg !== undefined) updatePayload.weight_kg = data.weight_kg;
if (data.availability_status !== undefined) updatePayload.availability_status = data.availability_status;
if (data.base_price !== undefined) updatePayload.base_price = data.base_price;
if (data.price_note_ar !== undefined) updatePayload.price_note_ar = data.price_note_ar;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await stone_variants.update(updatePayload, {transaction});
if (data.stone !== undefined) {
await stone_variants.setStone(
data.stone,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.stone_variants.getTableName(),
belongsToColumn: 'images',
belongsToId: stone_variants.id,
},
data.images,
options,
);
return stone_variants;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const stone_variants = await db.stone_variants.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of stone_variants) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of stone_variants) {
await record.destroy({transaction});
}
});
return stone_variants;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const stone_variants = await db.stone_variants.findByPk(id, options);
await stone_variants.update({
deletedBy: currentUser.id
}, {
transaction,
});
await stone_variants.destroy({
transaction
});
return stone_variants;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const stone_variants = await db.stone_variants.findOne(
{ where },
{ transaction },
);
if (!stone_variants) {
return stone_variants;
}
const output = stone_variants.get({plain: true});
output.quote_items_stone_variant = await stone_variants.getQuote_items_stone_variant({
transaction
});
output.stone = await stone_variants.getStone({
transaction
});
output.images = await stone_variants.getImages({
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.stones,
as: 'stone',
where: filter.stone ? {
[Op.or]: [
{ id: { [Op.in]: filter.stone.split('|').map(term => Utils.uuid(term)) } },
{
name_ar: {
[Op.or]: filter.stone.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.file,
as: 'images',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.sku) {
where = {
...where,
[Op.and]: Utils.ilike(
'stone_variants',
'sku',
filter.sku,
),
};
}
if (filter.price_note_ar) {
where = {
...where,
[Op.and]: Utils.ilike(
'stone_variants',
'price_note_ar',
filter.price_note_ar,
),
};
}
if (filter.length_mmRange) {
const [start, end] = filter.length_mmRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
length_mm: {
...where.length_mm,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
length_mm: {
...where.length_mm,
[Op.lte]: end,
},
};
}
}
if (filter.width_mmRange) {
const [start, end] = filter.width_mmRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
width_mm: {
...where.width_mm,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
width_mm: {
...where.width_mm,
[Op.lte]: end,
},
};
}
}
if (filter.thickness_mmRange) {
const [start, end] = filter.thickness_mmRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
thickness_mm: {
...where.thickness_mm,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
thickness_mm: {
...where.thickness_mm,
[Op.lte]: end,
},
};
}
}
if (filter.weight_kgRange) {
const [start, end] = filter.weight_kgRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
weight_kg: {
...where.weight_kg,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
weight_kg: {
...where.weight_kg,
[Op.lte]: end,
},
};
}
}
if (filter.base_priceRange) {
const [start, end] = filter.base_priceRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
base_price: {
...where.base_price,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
base_price: {
...where.base_price,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.variant_type) {
where = {
...where,
variant_type: filter.variant_type,
};
}
if (filter.availability_status) {
where = {
...where,
availability_status: filter.availability_status,
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
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.stone_variants.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(
'stone_variants',
'sku',
query,
),
],
};
}
const records = await db.stone_variants.findAll({
attributes: [ 'id', 'sku' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['sku', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.sku,
}));
}
};

View File

@ -0,0 +1,915 @@
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 StonesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const stones = await db.stones.create(
{
id: data.id || undefined,
name_ar: data.name_ar
||
null
,
slug: data.slug
||
null
,
short_description_ar: data.short_description_ar
||
null
,
description_ar: data.description_ar
||
null
,
density: data.density
||
null
,
water_absorption: data.water_absorption
||
null
,
compressive_strength: data.compressive_strength
||
null
,
flexural_strength: data.flexural_strength
||
null
,
origin_type: data.origin_type
||
null
,
origin_country: data.origin_country
||
null
,
is_featured: data.is_featured
||
false
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await stones.setCategory( data.category || null, {
transaction,
});
await stones.setColor( data.color || null, {
transaction,
});
await stones.setFinishes(data.finishes || [], {
transaction,
});
await stones.setApplications(data.applications || [], {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.stones.getTableName(),
belongsToColumn: 'gallery_images',
belongsToId: stones.id,
},
data.gallery_images,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.stones.getTableName(),
belongsToColumn: 'technical_sheet_files',
belongsToId: stones.id,
},
data.technical_sheet_files,
options,
);
return stones;
}
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 stonesData = data.map((item, index) => ({
id: item.id || undefined,
name_ar: item.name_ar
||
null
,
slug: item.slug
||
null
,
short_description_ar: item.short_description_ar
||
null
,
description_ar: item.description_ar
||
null
,
density: item.density
||
null
,
water_absorption: item.water_absorption
||
null
,
compressive_strength: item.compressive_strength
||
null
,
flexural_strength: item.flexural_strength
||
null
,
origin_type: item.origin_type
||
null
,
origin_country: item.origin_country
||
null
,
is_featured: item.is_featured
||
false
,
is_active: item.is_active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const stones = await db.stones.bulkCreate(stonesData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < stones.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.stones.getTableName(),
belongsToColumn: 'gallery_images',
belongsToId: stones[i].id,
},
data[i].gallery_images,
options,
);
}
for (let i = 0; i < stones.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.stones.getTableName(),
belongsToColumn: 'technical_sheet_files',
belongsToId: stones[i].id,
},
data[i].technical_sheet_files,
options,
);
}
return stones;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const stones = await db.stones.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name_ar !== undefined) updatePayload.name_ar = data.name_ar;
if (data.slug !== undefined) updatePayload.slug = data.slug;
if (data.short_description_ar !== undefined) updatePayload.short_description_ar = data.short_description_ar;
if (data.description_ar !== undefined) updatePayload.description_ar = data.description_ar;
if (data.density !== undefined) updatePayload.density = data.density;
if (data.water_absorption !== undefined) updatePayload.water_absorption = data.water_absorption;
if (data.compressive_strength !== undefined) updatePayload.compressive_strength = data.compressive_strength;
if (data.flexural_strength !== undefined) updatePayload.flexural_strength = data.flexural_strength;
if (data.origin_type !== undefined) updatePayload.origin_type = data.origin_type;
if (data.origin_country !== undefined) updatePayload.origin_country = data.origin_country;
if (data.is_featured !== undefined) updatePayload.is_featured = data.is_featured;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await stones.update(updatePayload, {transaction});
if (data.category !== undefined) {
await stones.setCategory(
data.category,
{ transaction }
);
}
if (data.color !== undefined) {
await stones.setColor(
data.color,
{ transaction }
);
}
if (data.finishes !== undefined) {
await stones.setFinishes(data.finishes, { transaction });
}
if (data.applications !== undefined) {
await stones.setApplications(data.applications, { transaction });
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.stones.getTableName(),
belongsToColumn: 'gallery_images',
belongsToId: stones.id,
},
data.gallery_images,
options,
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.stones.getTableName(),
belongsToColumn: 'technical_sheet_files',
belongsToId: stones.id,
},
data.technical_sheet_files,
options,
);
return stones;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const stones = await db.stones.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of stones) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of stones) {
await record.destroy({transaction});
}
});
return stones;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const stones = await db.stones.findByPk(id, options);
await stones.update({
deletedBy: currentUser.id
}, {
transaction,
});
await stones.destroy({
transaction
});
return stones;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const stones = await db.stones.findOne(
{ where },
{ transaction },
);
if (!stones) {
return stones;
}
const output = stones.get({plain: true});
output.stone_variants_stone = await stones.getStone_variants_stone({
transaction
});
output.stone_3d_assets_stone = await stones.getStone_3d_assets_stone({
transaction
});
output.lead_requests_interested_stone = await stones.getLead_requests_interested_stone({
transaction
});
output.category = await stones.getCategory({
transaction
});
output.color = await stones.getColor({
transaction
});
output.finishes = await stones.getFinishes({
transaction
});
output.applications = await stones.getApplications({
transaction
});
output.gallery_images = await stones.getGallery_images({
transaction
});
output.technical_sheet_files = await stones.getTechnical_sheet_files({
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.stone_categories,
as: 'category',
where: filter.category ? {
[Op.or]: [
{ id: { [Op.in]: filter.category.split('|').map(term => Utils.uuid(term)) } },
{
name_ar: {
[Op.or]: filter.category.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.stone_colors,
as: 'color',
where: filter.color ? {
[Op.or]: [
{ id: { [Op.in]: filter.color.split('|').map(term => Utils.uuid(term)) } },
{
name_ar: {
[Op.or]: filter.color.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.finishes,
as: 'finishes',
required: false,
},
{
model: db.applications,
as: 'applications',
required: false,
},
{
model: db.file,
as: 'gallery_images',
},
{
model: db.file,
as: 'technical_sheet_files',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name_ar) {
where = {
...where,
[Op.and]: Utils.ilike(
'stones',
'name_ar',
filter.name_ar,
),
};
}
if (filter.slug) {
where = {
...where,
[Op.and]: Utils.ilike(
'stones',
'slug',
filter.slug,
),
};
}
if (filter.short_description_ar) {
where = {
...where,
[Op.and]: Utils.ilike(
'stones',
'short_description_ar',
filter.short_description_ar,
),
};
}
if (filter.description_ar) {
where = {
...where,
[Op.and]: Utils.ilike(
'stones',
'description_ar',
filter.description_ar,
),
};
}
if (filter.origin_country) {
where = {
...where,
[Op.and]: Utils.ilike(
'stones',
'origin_country',
filter.origin_country,
),
};
}
if (filter.densityRange) {
const [start, end] = filter.densityRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
density: {
...where.density,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
density: {
...where.density,
[Op.lte]: end,
},
};
}
}
if (filter.water_absorptionRange) {
const [start, end] = filter.water_absorptionRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
water_absorption: {
...where.water_absorption,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
water_absorption: {
...where.water_absorption,
[Op.lte]: end,
},
};
}
}
if (filter.compressive_strengthRange) {
const [start, end] = filter.compressive_strengthRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
compressive_strength: {
...where.compressive_strength,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
compressive_strength: {
...where.compressive_strength,
[Op.lte]: end,
},
};
}
}
if (filter.flexural_strengthRange) {
const [start, end] = filter.flexural_strengthRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
flexural_strength: {
...where.flexural_strength,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
flexural_strength: {
...where.flexural_strength,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.origin_type) {
where = {
...where,
origin_type: filter.origin_type,
};
}
if (filter.is_featured) {
where = {
...where,
is_featured: filter.is_featured,
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
if (filter.finishes) {
const searchTerms = filter.finishes.split('|');
include = [
{
model: db.finishes,
as: 'finishes_filter',
required: searchTerms.length > 0,
where: searchTerms.length > 0 ? {
[Op.or]: [
{ id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
{
name_ar: {
[Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
}
}
]
} : undefined
},
...include,
]
}
if (filter.applications) {
const searchTerms = filter.applications.split('|');
include = [
{
model: db.applications,
as: 'applications_filter',
required: searchTerms.length > 0,
where: searchTerms.length > 0 ? {
[Op.or]: [
{ id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
{
name_ar: {
[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.stones.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(
'stones',
'name_ar',
query,
),
],
};
}
const records = await db.stones.findAll({
attributes: [ 'id', 'name_ar' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['name_ar', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.name_ar,
}));
}
};

View File

@ -0,0 +1,550 @@
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 Team_membersDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const team_members = await db.team_members.create(
{
id: data.id || undefined,
name_ar: data.name_ar
||
null
,
job_title_ar: data.job_title_ar
||
null
,
bio_ar: data.bio_ar
||
null
,
email: data.email
||
null
,
phone: data.phone
||
null
,
sort_order: data.sort_order
||
null
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.team_members.getTableName(),
belongsToColumn: 'photo',
belongsToId: team_members.id,
},
data.photo,
options,
);
return team_members;
}
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 team_membersData = data.map((item, index) => ({
id: item.id || undefined,
name_ar: item.name_ar
||
null
,
job_title_ar: item.job_title_ar
||
null
,
bio_ar: item.bio_ar
||
null
,
email: item.email
||
null
,
phone: item.phone
||
null
,
sort_order: item.sort_order
||
null
,
is_active: item.is_active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const team_members = await db.team_members.bulkCreate(team_membersData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < team_members.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.team_members.getTableName(),
belongsToColumn: 'photo',
belongsToId: team_members[i].id,
},
data[i].photo,
options,
);
}
return team_members;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const team_members = await db.team_members.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name_ar !== undefined) updatePayload.name_ar = data.name_ar;
if (data.job_title_ar !== undefined) updatePayload.job_title_ar = data.job_title_ar;
if (data.bio_ar !== undefined) updatePayload.bio_ar = data.bio_ar;
if (data.email !== undefined) updatePayload.email = data.email;
if (data.phone !== undefined) updatePayload.phone = data.phone;
if (data.sort_order !== undefined) updatePayload.sort_order = data.sort_order;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await team_members.update(updatePayload, {transaction});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.team_members.getTableName(),
belongsToColumn: 'photo',
belongsToId: team_members.id,
},
data.photo,
options,
);
return team_members;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const team_members = await db.team_members.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of team_members) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of team_members) {
await record.destroy({transaction});
}
});
return team_members;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const team_members = await db.team_members.findByPk(id, options);
await team_members.update({
deletedBy: currentUser.id
}, {
transaction,
});
await team_members.destroy({
transaction
});
return team_members;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const team_members = await db.team_members.findOne(
{ where },
{ transaction },
);
if (!team_members) {
return team_members;
}
const output = team_members.get({plain: true});
output.photo = await team_members.getPhoto({
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.file,
as: 'photo',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name_ar) {
where = {
...where,
[Op.and]: Utils.ilike(
'team_members',
'name_ar',
filter.name_ar,
),
};
}
if (filter.job_title_ar) {
where = {
...where,
[Op.and]: Utils.ilike(
'team_members',
'job_title_ar',
filter.job_title_ar,
),
};
}
if (filter.bio_ar) {
where = {
...where,
[Op.and]: Utils.ilike(
'team_members',
'bio_ar',
filter.bio_ar,
),
};
}
if (filter.email) {
where = {
...where,
[Op.and]: Utils.ilike(
'team_members',
'email',
filter.email,
),
};
}
if (filter.phone) {
where = {
...where,
[Op.and]: Utils.ilike(
'team_members',
'phone',
filter.phone,
),
};
}
if (filter.sort_orderRange) {
const [start, end] = filter.sort_orderRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sort_order: {
...where.sort_order,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sort_order: {
...where.sort_order,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
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.team_members.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(
'team_members',
'name_ar',
query,
),
],
};
}
const records = await db.team_members.findAll({
attributes: [ 'id', 'name_ar' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['name_ar', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.name_ar,
}));
}
};

View File

@ -0,0 +1,465 @@
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 TechnologiesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const technologies = await db.technologies.create(
{
id: data.id || undefined,
name_ar: data.name_ar
||
null
,
technology_type: data.technology_type
||
null
,
description_ar: data.description_ar
||
null
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.technologies.getTableName(),
belongsToColumn: 'images',
belongsToId: technologies.id,
},
data.images,
options,
);
return technologies;
}
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 technologiesData = data.map((item, index) => ({
id: item.id || undefined,
name_ar: item.name_ar
||
null
,
technology_type: item.technology_type
||
null
,
description_ar: item.description_ar
||
null
,
is_active: item.is_active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const technologies = await db.technologies.bulkCreate(technologiesData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < technologies.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.technologies.getTableName(),
belongsToColumn: 'images',
belongsToId: technologies[i].id,
},
data[i].images,
options,
);
}
return technologies;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const technologies = await db.technologies.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name_ar !== undefined) updatePayload.name_ar = data.name_ar;
if (data.technology_type !== undefined) updatePayload.technology_type = data.technology_type;
if (data.description_ar !== undefined) updatePayload.description_ar = data.description_ar;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await technologies.update(updatePayload, {transaction});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.technologies.getTableName(),
belongsToColumn: 'images',
belongsToId: technologies.id,
},
data.images,
options,
);
return technologies;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const technologies = await db.technologies.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of technologies) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of technologies) {
await record.destroy({transaction});
}
});
return technologies;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const technologies = await db.technologies.findByPk(id, options);
await technologies.update({
deletedBy: currentUser.id
}, {
transaction,
});
await technologies.destroy({
transaction
});
return technologies;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const technologies = await db.technologies.findOne(
{ where },
{ transaction },
);
if (!technologies) {
return technologies;
}
const output = technologies.get({plain: true});
output.service_technologies_technology = await technologies.getService_technologies_technology({
transaction
});
output.images = await technologies.getImages({
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.file,
as: 'images',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name_ar) {
where = {
...where,
[Op.and]: Utils.ilike(
'technologies',
'name_ar',
filter.name_ar,
),
};
}
if (filter.description_ar) {
where = {
...where,
[Op.and]: Utils.ilike(
'technologies',
'description_ar',
filter.description_ar,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.technology_type) {
where = {
...where,
technology_type: filter.technology_type,
};
}
if (filter.is_active) {
where = {
...where,
is_active: filter.is_active,
};
}
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.technologies.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(
'technologies',
'name_ar',
query,
),
],
};
}
const records = await db.technologies.findAll({
attributes: [ 'id', 'name_ar' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['name_ar', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.name_ar,
}));
}
};

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

@ -0,0 +1,963 @@
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
,
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
,
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;
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.blog_posts_author = await users.getBlog_posts_author({
transaction
});
output.lead_requests_assigned_to = await users.getLead_requests_assigned_to({
transaction
});
output.inquiries_assigned_to = await users.getInquiries_assigned_to({
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.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,33 @@
module.exports = {
production: {
dialect: 'postgres',
username: process.env.DB_USER,
password: process.env.DB_PASS,
database: process.env.DB_NAME,
host: process.env.DB_HOST,
port: process.env.DB_PORT,
logging: console.log,
seederStorage: 'sequelize',
},
development: {
username: 'postgres',
dialect: 'postgres',
password: '',
database: 'db_stone_factory_arabic_site',
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,137 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const applications = sequelize.define(
'applications',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name_ar: {
type: DataTypes.TEXT,
},
application_scope: {
type: DataTypes.ENUM,
values: [
"interior",
"exterior",
"commercial",
"residential",
"hospitality",
"public"
],
},
description_ar: {
type: DataTypes.TEXT,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
applications.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.applications.belongsTo(db.users, {
as: 'createdBy',
});
db.applications.belongsTo(db.users, {
as: 'updatedBy',
});
};
return applications;
};

View File

@ -0,0 +1,131 @@
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 blog_categories = sequelize.define(
'blog_categories',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name_ar: {
type: DataTypes.TEXT,
},
slug: {
type: DataTypes.TEXT,
},
description_ar: {
type: DataTypes.TEXT,
},
sort_order: {
type: DataTypes.INTEGER,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
blog_categories.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.blog_categories.hasMany(db.blog_posts, {
as: 'blog_posts_category',
foreignKey: {
name: 'categoryId',
},
constraints: false,
});
//end loop
db.blog_categories.belongsTo(db.users, {
as: 'createdBy',
});
db.blog_categories.belongsTo(db.users, {
as: 'updatedBy',
});
};
return blog_categories;
};

View File

@ -0,0 +1,224 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const blog_posts = sequelize.define(
'blog_posts',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
title_ar: {
type: DataTypes.TEXT,
},
slug: {
type: DataTypes.TEXT,
},
excerpt_ar: {
type: DataTypes.TEXT,
},
content_ar: {
type: DataTypes.TEXT,
},
publish_status: {
type: DataTypes.ENUM,
values: [
"draft",
"scheduled",
"published",
"archived"
],
},
published_at: {
type: DataTypes.DATE,
},
is_featured: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
blog_posts.associate = (db) => {
db.blog_posts.belongsToMany(db.stones, {
as: 'related_stones',
foreignKey: {
name: 'blog_posts_related_stonesId',
},
constraints: false,
through: 'blog_postsRelated_stonesStones',
});
db.blog_posts.belongsToMany(db.stones, {
as: 'related_stones_filter',
foreignKey: {
name: 'blog_posts_related_stonesId',
},
constraints: false,
through: 'blog_postsRelated_stonesStones',
});
db.blog_posts.belongsToMany(db.projects, {
as: 'related_projects',
foreignKey: {
name: 'blog_posts_related_projectsId',
},
constraints: false,
through: 'blog_postsRelated_projectsProjects',
});
db.blog_posts.belongsToMany(db.projects, {
as: 'related_projects_filter',
foreignKey: {
name: 'blog_posts_related_projectsId',
},
constraints: false,
through: 'blog_postsRelated_projectsProjects',
});
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.blog_posts.belongsTo(db.blog_categories, {
as: 'category',
foreignKey: {
name: 'categoryId',
},
constraints: false,
});
db.blog_posts.belongsTo(db.users, {
as: 'author',
foreignKey: {
name: 'authorId',
},
constraints: false,
});
db.blog_posts.hasMany(db.file, {
as: 'featured_image',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.blog_posts.getTableName(),
belongsToColumn: 'featured_image',
},
});
db.blog_posts.hasMany(db.file, {
as: 'attachments',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.blog_posts.getTableName(),
belongsToColumn: 'attachments',
},
});
db.blog_posts.belongsTo(db.users, {
as: 'createdBy',
});
db.blog_posts.belongsTo(db.users, {
as: 'updatedBy',
});
};
return blog_posts;
};

View File

@ -0,0 +1,152 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const contact_locations = sequelize.define(
'contact_locations',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name_ar: {
type: DataTypes.TEXT,
},
address_ar: {
type: DataTypes.TEXT,
},
phone: {
type: DataTypes.TEXT,
},
email: {
type: DataTypes.TEXT,
},
google_maps_url: {
type: DataTypes.TEXT,
},
latitude: {
type: DataTypes.DECIMAL,
},
longitude: {
type: DataTypes.DECIMAL,
},
is_primary: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
contact_locations.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.contact_locations.hasMany(db.inquiries, {
as: 'inquiries_location',
foreignKey: {
name: 'locationId',
},
constraints: false,
});
//end loop
db.contact_locations.belongsTo(db.users, {
as: 'createdBy',
});
db.contact_locations.belongsTo(db.users, {
as: 'updatedBy',
});
};
return contact_locations;
};

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,119 @@
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 finishes = sequelize.define(
'finishes',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name_ar: {
type: DataTypes.TEXT,
},
description_ar: {
type: DataTypes.TEXT,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
finishes.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.finishes.hasMany(db.file, {
as: 'example_images',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.finishes.getTableName(),
belongsToColumn: 'example_images',
},
});
db.finishes.belongsTo(db.users, {
as: 'createdBy',
});
db.finishes.belongsTo(db.users, {
as: 'updatedBy',
});
};
return finishes;
};

View File

@ -0,0 +1,178 @@
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 hero_slides = sequelize.define(
'hero_slides',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
headline_ar: {
type: DataTypes.TEXT,
},
subheadline_ar: {
type: DataTypes.TEXT,
},
cta_type: {
type: DataTypes.ENUM,
values: [
"products",
"projects",
"services",
"quote",
"contact",
"custom_url"
],
},
cta_label_ar: {
type: DataTypes.TEXT,
},
cta_url: {
type: DataTypes.TEXT,
},
sort_order: {
type: DataTypes.INTEGER,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
hero_slides.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.hero_slides.hasMany(db.file, {
as: 'background_images',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.hero_slides.getTableName(),
belongsToColumn: 'background_images',
},
});
db.hero_slides.hasMany(db.file, {
as: 'background_videos',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.hero_slides.getTableName(),
belongsToColumn: 'background_videos',
},
});
db.hero_slides.belongsTo(db.users, {
as: 'createdBy',
});
db.hero_slides.belongsTo(db.users, {
as: 'updatedBy',
});
};
return hero_slides;
};

View File

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

View File

@ -0,0 +1,169 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const inquiries = sequelize.define(
'inquiries',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
full_name: {
type: DataTypes.TEXT,
},
email: {
type: DataTypes.TEXT,
},
phone: {
type: DataTypes.TEXT,
},
subject_ar: {
type: DataTypes.TEXT,
},
message_ar: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"new",
"replied",
"closed"
],
},
received_at: {
type: DataTypes.DATE,
},
replied_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
inquiries.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.inquiries.belongsTo(db.contact_locations, {
as: 'location',
foreignKey: {
name: 'locationId',
},
constraints: false,
});
db.inquiries.belongsTo(db.users, {
as: 'assigned_to',
foreignKey: {
name: 'assigned_toId',
},
constraints: false,
});
db.inquiries.belongsTo(db.users, {
as: 'createdBy',
});
db.inquiries.belongsTo(db.users, {
as: 'updatedBy',
});
};
return inquiries;
};

View File

@ -0,0 +1,275 @@
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 lead_requests = sequelize.define(
'lead_requests',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
request_type: {
type: DataTypes.ENUM,
values: [
"quote",
"callback",
"information",
"appointment",
"custom_order"
],
},
full_name: {
type: DataTypes.TEXT,
},
company_name: {
type: DataTypes.TEXT,
},
email: {
type: DataTypes.TEXT,
},
phone: {
type: DataTypes.TEXT,
},
customer_type: {
type: DataTypes.ENUM,
values: [
"architect",
"interior_designer",
"contractor",
"developer",
"individual",
"other"
],
},
message_ar: {
type: DataTypes.TEXT,
},
lead_status: {
type: DataTypes.ENUM,
values: [
"new",
"qualified",
"in_progress",
"quoted",
"won",
"lost",
"closed"
],
},
preferred_contact_time: {
type: DataTypes.DATE,
},
last_contacted_at: {
type: DataTypes.DATE,
},
internal_notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
lead_requests.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.lead_requests.hasMany(db.quote_items, {
as: 'quote_items_lead_request',
foreignKey: {
name: 'lead_requestId',
},
constraints: false,
});
//end loop
db.lead_requests.belongsTo(db.stones, {
as: 'interested_stone',
foreignKey: {
name: 'interested_stoneId',
},
constraints: false,
});
db.lead_requests.belongsTo(db.services, {
as: 'interested_service',
foreignKey: {
name: 'interested_serviceId',
},
constraints: false,
});
db.lead_requests.belongsTo(db.projects, {
as: 'related_project',
foreignKey: {
name: 'related_projectId',
},
constraints: false,
});
db.lead_requests.belongsTo(db.users, {
as: 'assigned_to',
foreignKey: {
name: 'assigned_toId',
},
constraints: false,
});
db.lead_requests.hasMany(db.file, {
as: 'reference_files',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.lead_requests.getTableName(),
belongsToColumn: 'reference_files',
},
});
db.lead_requests.belongsTo(db.users, {
as: 'createdBy',
});
db.lead_requests.belongsTo(db.users, {
as: 'updatedBy',
});
};
return lead_requests;
};

View File

@ -0,0 +1,155 @@
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 media_library = sequelize.define(
'media_library',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
media_type: {
type: DataTypes.ENUM,
values: [
"image",
"video",
"document"
],
},
title_ar: {
type: DataTypes.TEXT,
},
alt_text_ar: {
type: DataTypes.TEXT,
},
source_note_ar: {
type: DataTypes.TEXT,
},
is_public: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
media_library.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.media_library.hasMany(db.file, {
as: 'images',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.media_library.getTableName(),
belongsToColumn: 'images',
},
});
db.media_library.hasMany(db.file, {
as: 'files',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.media_library.getTableName(),
belongsToColumn: 'files',
},
});
db.media_library.belongsTo(db.users, {
as: 'createdBy',
});
db.media_library.belongsTo(db.users, {
as: 'updatedBy',
});
};
return media_library;
};

View File

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

View File

@ -0,0 +1,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 project_media = sequelize.define(
'project_media',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
media_kind: {
type: DataTypes.ENUM,
values: [
"image",
"video"
],
},
media_role: {
type: DataTypes.ENUM,
values: [
"before",
"after",
"process",
"final",
"detail",
"other"
],
},
caption_ar: {
type: DataTypes.TEXT,
},
sort_order: {
type: DataTypes.INTEGER,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
project_media.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.project_media.belongsTo(db.projects, {
as: 'project',
foreignKey: {
name: 'projectId',
},
constraints: false,
});
db.project_media.hasMany(db.file, {
as: 'images',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.project_media.getTableName(),
belongsToColumn: 'images',
},
});
db.project_media.hasMany(db.file, {
as: 'videos',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.project_media.getTableName(),
belongsToColumn: 'videos',
},
});
db.project_media.belongsTo(db.users, {
as: 'createdBy',
});
db.project_media.belongsTo(db.users, {
as: 'updatedBy',
});
};
return project_media;
};

View File

@ -0,0 +1,268 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const projects = sequelize.define(
'projects',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name_ar: {
type: DataTypes.TEXT,
},
slug: {
type: DataTypes.TEXT,
},
project_scope: {
type: DataTypes.ENUM,
values: [
"interior",
"exterior",
"commercial",
"residential"
],
},
location_ar: {
type: DataTypes.TEXT,
},
summary_ar: {
type: DataTypes.TEXT,
},
description_ar: {
type: DataTypes.TEXT,
},
started_at: {
type: DataTypes.DATE,
},
completed_at: {
type: DataTypes.DATE,
},
is_featured: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
is_published: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
projects.associate = (db) => {
db.projects.belongsToMany(db.stones, {
as: 'stones_used',
foreignKey: {
name: 'projects_stones_usedId',
},
constraints: false,
through: 'projectsStones_usedStones',
});
db.projects.belongsToMany(db.stones, {
as: 'stones_used_filter',
foreignKey: {
name: 'projects_stones_usedId',
},
constraints: false,
through: 'projectsStones_usedStones',
});
db.projects.belongsToMany(db.applications, {
as: 'applications',
foreignKey: {
name: 'projects_applicationsId',
},
constraints: false,
through: 'projectsApplicationsApplications',
});
db.projects.belongsToMany(db.applications, {
as: 'applications_filter',
foreignKey: {
name: 'projects_applicationsId',
},
constraints: false,
through: 'projectsApplicationsApplications',
});
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.projects.hasMany(db.project_media, {
as: 'project_media_project',
foreignKey: {
name: 'projectId',
},
constraints: false,
});
db.projects.hasMany(db.lead_requests, {
as: 'lead_requests_related_project',
foreignKey: {
name: 'related_projectId',
},
constraints: false,
});
//end loop
db.projects.hasMany(db.file, {
as: 'before_images',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.projects.getTableName(),
belongsToColumn: 'before_images',
},
});
db.projects.hasMany(db.file, {
as: 'after_images',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.projects.getTableName(),
belongsToColumn: 'after_images',
},
});
db.projects.hasMany(db.file, {
as: 'gallery_images',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.projects.getTableName(),
belongsToColumn: 'gallery_images',
},
});
db.projects.hasMany(db.file, {
as: 'attachments',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.projects.getTableName(),
belongsToColumn: 'attachments',
},
});
db.projects.belongsTo(db.users, {
as: 'createdBy',
});
db.projects.belongsTo(db.users, {
as: 'updatedBy',
});
};
return projects;
};

View File

@ -0,0 +1,175 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const quote_items = sequelize.define(
'quote_items',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
item_description_ar: {
type: DataTypes.TEXT,
},
quantity: {
type: DataTypes.DECIMAL,
},
unit: {
type: DataTypes.ENUM,
values: [
"sqm",
"piece",
"ml",
"set",
"job"
],
},
unit_price: {
type: DataTypes.DECIMAL,
},
discount_amount: {
type: DataTypes.DECIMAL,
},
tax_amount: {
type: DataTypes.DECIMAL,
},
line_total: {
type: DataTypes.DECIMAL,
},
sort_order: {
type: DataTypes.INTEGER,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
quote_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.quote_items.belongsTo(db.lead_requests, {
as: 'lead_request',
foreignKey: {
name: 'lead_requestId',
},
constraints: false,
});
db.quote_items.belongsTo(db.stone_variants, {
as: 'stone_variant',
foreignKey: {
name: 'stone_variantId',
},
constraints: false,
});
db.quote_items.belongsTo(db.users, {
as: 'createdBy',
});
db.quote_items.belongsTo(db.users, {
as: 'updatedBy',
});
};
return quote_items;
};

View File

@ -0,0 +1,125 @@
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,175 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const seo_pages = sequelize.define(
'seo_pages',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
page_key: {
type: DataTypes.ENUM,
values: [
"home",
"products",
"product_detail",
"projects",
"project_detail",
"services",
"service_detail",
"about",
"contact",
"blog",
"post_detail",
"privacy",
"terms"
],
},
title_ar: {
type: DataTypes.TEXT,
},
description_ar: {
type: DataTypes.TEXT,
},
canonical_url: {
type: DataTypes.TEXT,
},
indexable: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
seo_pages.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.seo_pages.hasMany(db.file, {
as: 'structured_data_jsonld',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.seo_pages.getTableName(),
belongsToColumn: 'structured_data_jsonld',
},
});
db.seo_pages.belongsTo(db.users, {
as: 'createdBy',
});
db.seo_pages.belongsTo(db.users, {
as: 'updatedBy',
});
};
return seo_pages;
};

View File

@ -0,0 +1,115 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const service_technologies = sequelize.define(
'service_technologies',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
note_ar: {
type: DataTypes.TEXT,
},
sort_order: {
type: DataTypes.INTEGER,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
service_technologies.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.service_technologies.belongsTo(db.services, {
as: 'service',
foreignKey: {
name: 'serviceId',
},
constraints: false,
});
db.service_technologies.belongsTo(db.technologies, {
as: 'technology',
foreignKey: {
name: 'technologyId',
},
constraints: false,
});
db.service_technologies.belongsTo(db.users, {
as: 'createdBy',
});
db.service_technologies.belongsTo(db.users, {
as: 'updatedBy',
});
};
return service_technologies;
};

View File

@ -0,0 +1,216 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const services = sequelize.define(
'services',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name_ar: {
type: DataTypes.TEXT,
},
slug: {
type: DataTypes.TEXT,
},
service_type: {
type: DataTypes.ENUM,
values: [
"cnc_cutting",
"waterjet_cutting",
"polishing",
"profiling",
"edge_finishing",
"engraving",
"installation_support",
"custom_fabrication",
"consultation",
"other"
],
},
summary_ar: {
type: DataTypes.TEXT,
},
description_ar: {
type: DataTypes.TEXT,
},
sort_order: {
type: DataTypes.INTEGER,
},
is_featured: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
services.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.services.hasMany(db.service_technologies, {
as: 'service_technologies_service',
foreignKey: {
name: 'serviceId',
},
constraints: false,
});
db.services.hasMany(db.lead_requests, {
as: 'lead_requests_interested_service',
foreignKey: {
name: 'interested_serviceId',
},
constraints: false,
});
//end loop
db.services.hasMany(db.file, {
as: 'images',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.services.getTableName(),
belongsToColumn: 'images',
},
});
db.services.hasMany(db.file, {
as: 'brochure_files',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.services.getTableName(),
belongsToColumn: 'brochure_files',
},
});
db.services.belongsTo(db.users, {
as: 'createdBy',
});
db.services.belongsTo(db.users, {
as: 'updatedBy',
});
};
return services;
};

View File

@ -0,0 +1,180 @@
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 site_settings = sequelize.define(
'site_settings',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
site_name_ar: {
type: DataTypes.TEXT,
},
site_tagline_ar: {
type: DataTypes.TEXT,
},
primary_font: {
type: DataTypes.TEXT,
},
direction: {
type: DataTypes.ENUM,
values: [
"rtl",
"ltr"
],
},
primary_color_hex: {
type: DataTypes.TEXT,
},
accent_color_hex: {
type: DataTypes.TEXT,
},
seo_default_title_ar: {
type: DataTypes.TEXT,
},
seo_default_description_ar: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
site_settings.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.site_settings.hasMany(db.file, {
as: 'logo',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.site_settings.getTableName(),
belongsToColumn: 'logo',
},
});
db.site_settings.hasMany(db.file, {
as: 'favicon',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.site_settings.getTableName(),
belongsToColumn: 'favicon',
},
});
db.site_settings.hasMany(db.file, {
as: 'brand_guidelines',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.site_settings.getTableName(),
belongsToColumn: 'brand_guidelines',
},
});
db.site_settings.belongsTo(db.users, {
as: 'createdBy',
});
db.site_settings.belongsTo(db.users, {
as: 'updatedBy',
});
};
return site_settings;
};

View File

@ -0,0 +1,153 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const social_links = sequelize.define(
'social_links',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
platform: {
type: DataTypes.ENUM,
values: [
"instagram",
"facebook",
"x",
"linkedin",
"youtube",
"tiktok",
"snapchat",
"pinterest",
"whatsapp"
],
},
url: {
type: DataTypes.TEXT,
},
label_ar: {
type: DataTypes.TEXT,
},
sort_order: {
type: DataTypes.INTEGER,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
social_links.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.social_links.belongsTo(db.users, {
as: 'createdBy',
});
db.social_links.belongsTo(db.users, {
as: 'updatedBy',
});
};
return social_links;
};

View File

@ -0,0 +1,155 @@
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 stone_3d_assets = sequelize.define(
'stone_3d_assets',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
asset_type: {
type: DataTypes.ENUM,
values: [
"glb",
"gltf",
"usdz",
"texture_set",
"other"
],
},
viewer_hint_ar: {
type: DataTypes.TEXT,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
stone_3d_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.stone_3d_assets.belongsTo(db.stones, {
as: 'stone',
foreignKey: {
name: 'stoneId',
},
constraints: false,
});
db.stone_3d_assets.hasMany(db.file, {
as: 'asset_file',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.stone_3d_assets.getTableName(),
belongsToColumn: 'asset_file',
},
});
db.stone_3d_assets.hasMany(db.file, {
as: 'preview_images',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.stone_3d_assets.getTableName(),
belongsToColumn: 'preview_images',
},
});
db.stone_3d_assets.belongsTo(db.users, {
as: 'createdBy',
});
db.stone_3d_assets.belongsTo(db.users, {
as: 'updatedBy',
});
};
return stone_3d_assets;
};

View File

@ -0,0 +1,172 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const stone_categories = sequelize.define(
'stone_categories',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name_ar: {
type: DataTypes.TEXT,
},
slug: {
type: DataTypes.TEXT,
},
description_ar: {
type: DataTypes.TEXT,
},
sort_order: {
type: DataTypes.INTEGER,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
category_type: {
type: DataTypes.ENUM,
values: [
"marble",
"granite",
"travertine",
"onyx",
"limestone",
"sandstone",
"other"
],
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
stone_categories.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.stone_categories.hasMany(db.stones, {
as: 'stones_category',
foreignKey: {
name: 'categoryId',
},
constraints: false,
});
//end loop
db.stone_categories.hasMany(db.file, {
as: 'cover_image',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.stone_categories.getTableName(),
belongsToColumn: 'cover_image',
},
});
db.stone_categories.belongsTo(db.users, {
as: 'createdBy',
});
db.stone_categories.belongsTo(db.users, {
as: 'updatedBy',
});
};
return stone_categories;
};

View File

@ -0,0 +1,134 @@
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 stone_colors = sequelize.define(
'stone_colors',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name_ar: {
type: DataTypes.TEXT,
},
hex: {
type: DataTypes.TEXT,
},
sort_order: {
type: DataTypes.INTEGER,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
stone_colors.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.stone_colors.hasMany(db.stones, {
as: 'stones_color',
foreignKey: {
name: 'colorId',
},
constraints: false,
});
//end loop
db.stone_colors.hasMany(db.file, {
as: 'swatch_image',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.stone_colors.getTableName(),
belongsToColumn: 'swatch_image',
},
});
db.stone_colors.belongsTo(db.users, {
as: 'createdBy',
});
db.stone_colors.belongsTo(db.users, {
as: 'updatedBy',
});
};
return stone_colors;
};

View File

@ -0,0 +1,217 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const stone_variants = sequelize.define(
'stone_variants',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
variant_type: {
type: DataTypes.ENUM,
values: [
"slab",
"tile",
"stair",
"countertop",
"custom"
],
},
sku: {
type: DataTypes.TEXT,
},
length_mm: {
type: DataTypes.DECIMAL,
},
width_mm: {
type: DataTypes.DECIMAL,
},
thickness_mm: {
type: DataTypes.DECIMAL,
},
weight_kg: {
type: DataTypes.DECIMAL,
},
availability_status: {
type: DataTypes.ENUM,
values: [
"in_stock",
"made_to_order",
"out_of_stock",
"discontinued"
],
},
base_price: {
type: DataTypes.DECIMAL,
},
price_note_ar: {
type: DataTypes.TEXT,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
stone_variants.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.stone_variants.hasMany(db.quote_items, {
as: 'quote_items_stone_variant',
foreignKey: {
name: 'stone_variantId',
},
constraints: false,
});
//end loop
db.stone_variants.belongsTo(db.stones, {
as: 'stone',
foreignKey: {
name: 'stoneId',
},
constraints: false,
});
db.stone_variants.hasMany(db.file, {
as: 'images',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.stone_variants.getTableName(),
belongsToColumn: 'images',
},
});
db.stone_variants.belongsTo(db.users, {
as: 'createdBy',
});
db.stone_variants.belongsTo(db.users, {
as: 'updatedBy',
});
};
return stone_variants;
};

View File

@ -0,0 +1,283 @@
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 stones = sequelize.define(
'stones',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name_ar: {
type: DataTypes.TEXT,
},
slug: {
type: DataTypes.TEXT,
},
short_description_ar: {
type: DataTypes.TEXT,
},
description_ar: {
type: DataTypes.TEXT,
},
density: {
type: DataTypes.DECIMAL,
},
water_absorption: {
type: DataTypes.DECIMAL,
},
compressive_strength: {
type: DataTypes.DECIMAL,
},
flexural_strength: {
type: DataTypes.DECIMAL,
},
origin_type: {
type: DataTypes.ENUM,
values: [
"local",
"imported",
"mixed"
],
},
origin_country: {
type: DataTypes.TEXT,
},
is_featured: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
stones.associate = (db) => {
db.stones.belongsToMany(db.finishes, {
as: 'finishes',
foreignKey: {
name: 'stones_finishesId',
},
constraints: false,
through: 'stonesFinishesFinishes',
});
db.stones.belongsToMany(db.finishes, {
as: 'finishes_filter',
foreignKey: {
name: 'stones_finishesId',
},
constraints: false,
through: 'stonesFinishesFinishes',
});
db.stones.belongsToMany(db.applications, {
as: 'applications',
foreignKey: {
name: 'stones_applicationsId',
},
constraints: false,
through: 'stonesApplicationsApplications',
});
db.stones.belongsToMany(db.applications, {
as: 'applications_filter',
foreignKey: {
name: 'stones_applicationsId',
},
constraints: false,
through: 'stonesApplicationsApplications',
});
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.stones.hasMany(db.stone_variants, {
as: 'stone_variants_stone',
foreignKey: {
name: 'stoneId',
},
constraints: false,
});
db.stones.hasMany(db.stone_3d_assets, {
as: 'stone_3d_assets_stone',
foreignKey: {
name: 'stoneId',
},
constraints: false,
});
db.stones.hasMany(db.lead_requests, {
as: 'lead_requests_interested_stone',
foreignKey: {
name: 'interested_stoneId',
},
constraints: false,
});
//end loop
db.stones.belongsTo(db.stone_categories, {
as: 'category',
foreignKey: {
name: 'categoryId',
},
constraints: false,
});
db.stones.belongsTo(db.stone_colors, {
as: 'color',
foreignKey: {
name: 'colorId',
},
constraints: false,
});
db.stones.hasMany(db.file, {
as: 'gallery_images',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.stones.getTableName(),
belongsToColumn: 'gallery_images',
},
});
db.stones.hasMany(db.file, {
as: 'technical_sheet_files',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.stones.getTableName(),
belongsToColumn: 'technical_sheet_files',
},
});
db.stones.belongsTo(db.users, {
as: 'createdBy',
});
db.stones.belongsTo(db.users, {
as: 'updatedBy',
});
};
return stones;
};

View File

@ -0,0 +1,147 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const team_members = sequelize.define(
'team_members',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name_ar: {
type: DataTypes.TEXT,
},
job_title_ar: {
type: DataTypes.TEXT,
},
bio_ar: {
type: DataTypes.TEXT,
},
email: {
type: DataTypes.TEXT,
},
phone: {
type: DataTypes.TEXT,
},
sort_order: {
type: DataTypes.INTEGER,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
team_members.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.team_members.hasMany(db.file, {
as: 'photo',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.team_members.getTableName(),
belongsToColumn: 'photo',
},
});
db.team_members.belongsTo(db.users, {
as: 'createdBy',
});
db.team_members.belongsTo(db.users, {
as: 'updatedBy',
});
};
return team_members;
};

View File

@ -0,0 +1,155 @@
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 technologies = sequelize.define(
'technologies',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name_ar: {
type: DataTypes.TEXT,
},
technology_type: {
type: DataTypes.ENUM,
values: [
"cnc",
"waterjet",
"laser_measurement",
"cad_cam",
"polishing_line",
"other"
],
},
description_ar: {
type: DataTypes.TEXT,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
technologies.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.technologies.hasMany(db.service_technologies, {
as: 'service_technologies_technology',
foreignKey: {
name: 'technologyId',
},
constraints: false,
});
//end loop
db.technologies.hasMany(db.file, {
as: 'images',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.technologies.getTableName(),
belongsToColumn: 'images',
},
});
db.technologies.belongsTo(db.users, {
as: 'createdBy',
});
db.technologies.belongsTo(db.users, {
as: 'updatedBy',
});
};
return technologies;
};

View File

@ -0,0 +1,274 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const users = sequelize.define(
'users',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
firstName: {
type: DataTypes.TEXT,
},
lastName: {
type: DataTypes.TEXT,
},
phoneNumber: {
type: DataTypes.TEXT,
},
email: {
type: DataTypes.TEXT,
},
disabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
password: {
type: DataTypes.TEXT,
},
emailVerified: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
emailVerificationToken: {
type: DataTypes.TEXT,
},
emailVerificationTokenExpiresAt: {
type: DataTypes.DATE,
},
passwordResetToken: {
type: DataTypes.TEXT,
},
passwordResetTokenExpiresAt: {
type: DataTypes.DATE,
},
provider: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
users.associate = (db) => {
db.users.belongsToMany(db.permissions, {
as: 'custom_permissions',
foreignKey: {
name: 'users_custom_permissionsId',
},
constraints: false,
through: 'usersCustom_permissionsPermissions',
});
db.users.belongsToMany(db.permissions, {
as: 'custom_permissions_filter',
foreignKey: {
name: 'users_custom_permissionsId',
},
constraints: false,
through: 'usersCustom_permissionsPermissions',
});
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.users.hasMany(db.blog_posts, {
as: 'blog_posts_author',
foreignKey: {
name: 'authorId',
},
constraints: false,
});
db.users.hasMany(db.lead_requests, {
as: 'lead_requests_assigned_to',
foreignKey: {
name: 'assigned_toId',
},
constraints: false,
});
db.users.hasMany(db.inquiries, {
as: 'inquiries_assigned_to',
foreignKey: {
name: 'assigned_toId',
},
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;
}

16
backend/src/db/reset.js Normal file
View File

@ -0,0 +1,16 @@
const db = require('./models');
const {execSync} = require("child_process");
console.log('Resetting Database');
db.sequelize
.sync({ force: true })
.then(() => {
execSync("sequelize db:seed:all");
console.log('OK');
process.exit();
})
.catch((error) => {
console.error(error);
process.exit(1);
});

View File

@ -0,0 +1,66 @@
'use strict';
const bcrypt = require("bcrypt");
const config = require("../../config");
const ids = [
'193bf4b5-9f07-4bd5-9a43-e7e41f3e96af',
'af5a87be-8f9c-4630-902a-37a60b7005ba',
'5bc531ab-611f-41f3-9373-b7cc5d09c93d',
]
module.exports = {
up: async (queryInterface, Sequelize) => {
let admin_hash = bcrypt.hashSync(config.admin_pass, config.bcrypt.saltRounds);
let user_hash = bcrypt.hashSync(config.user_pass, config.bcrypt.saltRounds);
try {
await queryInterface.bulkInsert('users', [
{
id: ids[0],
firstName: 'Admin',
email: config.admin_email,
emailVerified: true,
provider: config.providers.LOCAL,
password: admin_hash,
createdAt: new Date(),
updatedAt: new Date()
},
{
id: ids[1],
firstName: 'John',
email: 'john@doe.com',
emailVerified: true,
provider: config.providers.LOCAL,
password: user_hash,
createdAt: new Date(),
updatedAt: new Date()
},
{
id: ids[2],
firstName: 'Client',
email: 'client@hello.com',
emailVerified: true,
provider: config.providers.LOCAL,
password: user_hash,
createdAt: new Date(),
updatedAt: new Date()
},
]);
} catch (error) {
console.error('Error during bulkInsert:', error);
throw error;
}
},
down: async (queryInterface, Sequelize) => {
try {
await queryInterface.bulkDelete('users', {
id: {
[Sequelize.Op.in]: ids,
},
}, {});
} catch (error) {
console.error('Error during bulkDelete:', error);
throw error;
}
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

27
backend/src/db/utils.js Normal file
View File

@ -0,0 +1,27 @@
const validator = require('validator');
const { v4: uuid } = require('uuid');
const Sequelize = require('./models').Sequelize;
module.exports = class Utils {
static uuid(value) {
let id = value;
if (!validator.isUUID(id)) {
id = uuid();
}
return id;
}
static ilike(model, column, value) {
return Sequelize.where(
Sequelize.fn(
'lower',
Sequelize.col(`${model}.${column}`),
),
{
[Sequelize.Op.like]: `%${value}%`.toLowerCase(),
},
);
}
};

23
backend/src/helpers.js Normal file
View File

@ -0,0 +1,23 @@
const jwt = require('jsonwebtoken');
const config = require('./config');
module.exports = class Helpers {
static wrapAsync(fn) {
return function (req, res, next) {
fn(req, res, next).catch(next);
};
}
static commonErrorHandler(error, req, res, next) {
if ([400, 403, 404].includes(error.code)) {
return res.status(error.code).send(error.message);
}
console.error(error);
return res.status(500).send(error.message);
}
static jwtSign(data) {
return jwt.sign(data, config.secret_key, {expiresIn: '6h'});
};
};

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

@ -0,0 +1,234 @@
const express = require('express');
const cors = require('cors');
const app = express();
const passport = require('passport');
const path = require('path');
const fs = require('fs');
const bodyParser = require('body-parser');
const db = require('./db/models');
const config = require('./config');
const swaggerUI = require('swagger-ui-express');
const swaggerJsDoc = require('swagger-jsdoc');
const authRoutes = require('./routes/auth');
const fileRoutes = require('./routes/file');
const searchRoutes = require('./routes/search');
const sqlRoutes = require('./routes/sql');
const pexelsRoutes = require('./routes/pexels');
const openaiRoutes = require('./routes/openai');
const usersRoutes = require('./routes/users');
const rolesRoutes = require('./routes/roles');
const permissionsRoutes = require('./routes/permissions');
const site_settingsRoutes = require('./routes/site_settings');
const contact_locationsRoutes = require('./routes/contact_locations');
const social_linksRoutes = require('./routes/social_links');
const hero_slidesRoutes = require('./routes/hero_slides');
const stone_categoriesRoutes = require('./routes/stone_categories');
const stone_colorsRoutes = require('./routes/stone_colors');
const finishesRoutes = require('./routes/finishes');
const applicationsRoutes = require('./routes/applications');
const stonesRoutes = require('./routes/stones');
const stone_variantsRoutes = require('./routes/stone_variants');
const stone_3d_assetsRoutes = require('./routes/stone_3d_assets');
const servicesRoutes = require('./routes/services');
const technologiesRoutes = require('./routes/technologies');
const service_technologiesRoutes = require('./routes/service_technologies');
const projectsRoutes = require('./routes/projects');
const project_mediaRoutes = require('./routes/project_media');
const team_membersRoutes = require('./routes/team_members');
const blog_categoriesRoutes = require('./routes/blog_categories');
const blog_postsRoutes = require('./routes/blog_posts');
const lead_requestsRoutes = require('./routes/lead_requests');
const quote_itemsRoutes = require('./routes/quote_items');
const inquiriesRoutes = require('./routes/inquiries');
const seo_pagesRoutes = require('./routes/seo_pages');
const media_libraryRoutes = require('./routes/media_library');
const getBaseUrl = (url) => {
if (!url) return '';
return url.endsWith('/api') ? url.slice(0, -4) : url;
};
const options = {
definition: {
openapi: "3.0.0",
info: {
version: "1.0.0",
title: "Stone Factory Arabic Site",
description: "Stone Factory Arabic Site Online REST API for Testing and Prototyping application. You can perform all major operations with your entities - create, delete and etc.",
},
servers: [
{
url: getBaseUrl(process.env.NEXT_PUBLIC_BACK_API) || config.swaggerUrl,
description: "Development server",
}
],
components: {
securitySchemes: {
bearerAuth: {
type: 'http',
scheme: 'bearer',
bearerFormat: 'JWT',
}
},
responses: {
UnauthorizedError: {
description: "Access token is missing or invalid"
}
}
},
security: [{
bearerAuth: []
}]
},
apis: ["./src/routes/*.js"],
};
const specs = swaggerJsDoc(options);
app.use('/api-docs', function (req, res, next) {
swaggerUI.host = getBaseUrl(process.env.NEXT_PUBLIC_BACK_API) || req.get('host');
next()
}, swaggerUI.serve, swaggerUI.setup(specs))
app.use(cors({origin: true}));
require('./auth/auth');
app.use(bodyParser.json());
app.use('/api/auth', authRoutes);
app.use('/api/file', fileRoutes);
app.use('/api/pexels', pexelsRoutes);
app.enable('trust proxy');
app.use('/api/users', passport.authenticate('jwt', {session: false}), usersRoutes);
app.use('/api/roles', passport.authenticate('jwt', {session: false}), rolesRoutes);
app.use('/api/permissions', passport.authenticate('jwt', {session: false}), permissionsRoutes);
app.use('/api/site_settings', passport.authenticate('jwt', {session: false}), site_settingsRoutes);
app.use('/api/contact_locations', passport.authenticate('jwt', {session: false}), contact_locationsRoutes);
app.use('/api/social_links', passport.authenticate('jwt', {session: false}), social_linksRoutes);
app.use('/api/hero_slides', passport.authenticate('jwt', {session: false}), hero_slidesRoutes);
app.use('/api/stone_categories', passport.authenticate('jwt', {session: false}), stone_categoriesRoutes);
app.use('/api/stone_colors', passport.authenticate('jwt', {session: false}), stone_colorsRoutes);
app.use('/api/finishes', passport.authenticate('jwt', {session: false}), finishesRoutes);
app.use('/api/applications', passport.authenticate('jwt', {session: false}), applicationsRoutes);
app.use('/api/stones', passport.authenticate('jwt', {session: false}), stonesRoutes);
app.use('/api/stone_variants', passport.authenticate('jwt', {session: false}), stone_variantsRoutes);
app.use('/api/stone_3d_assets', passport.authenticate('jwt', {session: false}), stone_3d_assetsRoutes);
app.use('/api/services', passport.authenticate('jwt', {session: false}), servicesRoutes);
app.use('/api/technologies', passport.authenticate('jwt', {session: false}), technologiesRoutes);
app.use('/api/service_technologies', passport.authenticate('jwt', {session: false}), service_technologiesRoutes);
app.use('/api/projects', passport.authenticate('jwt', {session: false}), projectsRoutes);
app.use('/api/project_media', passport.authenticate('jwt', {session: false}), project_mediaRoutes);
app.use('/api/team_members', passport.authenticate('jwt', {session: false}), team_membersRoutes);
app.use('/api/blog_categories', passport.authenticate('jwt', {session: false}), blog_categoriesRoutes);
app.use('/api/blog_posts', passport.authenticate('jwt', {session: false}), blog_postsRoutes);
app.use('/api/lead_requests', passport.authenticate('jwt', {session: false}), lead_requestsRoutes);
app.use('/api/quote_items', passport.authenticate('jwt', {session: false}), quote_itemsRoutes);
app.use('/api/inquiries', passport.authenticate('jwt', {session: false}), inquiriesRoutes);
app.use('/api/seo_pages', passport.authenticate('jwt', {session: false}), seo_pagesRoutes);
app.use('/api/media_library', passport.authenticate('jwt', {session: false}), media_libraryRoutes);
app.use(
'/api/openai',
passport.authenticate('jwt', { session: false }),
openaiRoutes,
);
app.use(
'/api/ai',
passport.authenticate('jwt', { session: false }),
openaiRoutes,
);
app.use(
'/api/search',
passport.authenticate('jwt', { session: false }),
searchRoutes);
app.use(
'/api/sql',
passport.authenticate('jwt', { session: false }),
sqlRoutes);
const publicDir = path.join(
__dirname,
'../public',
);
if (fs.existsSync(publicDir)) {
app.use('/', express.static(publicDir));
app.get('*', function(request, response) {
response.sendFile(
path.resolve(publicDir, 'index.html'),
);
});
}
const PORT = process.env.NODE_ENV === 'dev_stage' ? 3000 : 8080;
db.sequelize.sync().then(function () {
app.listen(PORT, () => {
console.log(`Listening on port ${PORT}`);
});
});
module.exports = app;

View File

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

View File

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

View File

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

207
backend/src/routes/auth.js Normal file
View File

@ -0,0 +1,207 @@
const express = require('express');
const passport = require('passport');
const config = require('../config');
const AuthService = require('../services/auth');
const ForbiddenError = require('../services/notifications/errors/forbidden');
const EmailSender = require('../services/email');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
/**
* @swagger
* components:
* schemas:
* Auth:
* type: object
* required:
* - email
* - password
* properties:
* email:
* type: string
* default: admin@flatlogic.com
* description: User email
* password:
* type: string
* default: password
* description: User password
*/
/**
* @swagger
* tags:
* name: Auth
* description: Authorization operations
*/
/**
* @swagger
* /api/auth/signin/local:
* post:
* tags: [Auth]
* summary: Logs user into the system
* description: Logs user into the system
* requestBody:
* description: Set valid user email and password
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Auth"
* responses:
* 200:
* description: Successful login
* 400:
* description: Invalid username/password supplied
* x-codegen-request-body-name: body
*/
router.post('/signin/local', wrapAsync(async (req, res) => {
const payload = await AuthService.signin(req.body.email, req.body.password, req,);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/auth/me:
* get:
* security:
* - bearerAuth: []
* tags: [Auth]
* summary: Get current authorized user info
* description: Get current authorized user info
* responses:
* 200:
* description: Successful retrieval of current authorized user data
* 400:
* description: Invalid username/password supplied
* x-codegen-request-body-name: body
*/
router.get('/me', passport.authenticate('jwt', {session: false}), (req, res) => {
if (!req.currentUser || !req.currentUser.id) {
throw new ForbiddenError();
}
const payload = req.currentUser;
delete payload.password;
res.status(200).send(payload);
});
router.put('/password-reset', wrapAsync(async (req, res) => {
const payload = await AuthService.passwordReset(req.body.token, req.body.password, req,);
res.status(200).send(payload);
}));
router.put('/password-update', passport.authenticate('jwt', {session: false}), wrapAsync(async (req, res) => {
const payload = await AuthService.passwordUpdate(req.body.currentPassword, req.body.newPassword, req);
res.status(200).send(payload);
}));
router.post('/send-email-address-verification-email', passport.authenticate('jwt', {session: false}), wrapAsync(async (req, res) => {
if (!req.currentUser) {
throw new ForbiddenError();
}
await AuthService.sendEmailAddressVerificationEmail(req.currentUser.email);
const payload = true;
res.status(200).send(payload);
}));
router.post('/send-password-reset-email', wrapAsync(async (req, res) => {
const link = new URL(req.headers.referer);
await AuthService.sendPasswordResetEmail(req.body.email, 'register', link.host,);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/auth/signup:
* post:
* tags: [Auth]
* summary: Register new user into the system
* description: Register new user into the system
* requestBody:
* description: Set valid user email and password
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Auth"
* responses:
* 200:
* description: New user successfully signed up
* 400:
* description: Invalid username/password supplied
* 500:
* description: Some server error
* x-codegen-request-body-name: body
*/
router.post('/signup', wrapAsync(async (req, res) => {
const link = new URL(req.headers.referer);
const payload = await AuthService.signup(
req.body.email,
req.body.password,
req,
link.host,
)
res.status(200).send(payload);
}));
router.put('/profile', passport.authenticate('jwt', {session: false}), wrapAsync(async (req, res) => {
if (!req.currentUser || !req.currentUser.id) {
throw new ForbiddenError();
}
await AuthService.updateProfile(req.body.profile, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
router.put('/verify-email', wrapAsync(async (req, res) => {
const payload = await AuthService.verifyEmail(req.body.token, req, req.headers.referer)
res.status(200).send(payload);
}));
router.get('/email-configured', (req, res) => {
const payload = EmailSender.isConfigured;
res.status(200).send(payload);
});
router.get('/signin/google', (req, res, next) => {
passport.authenticate("google", {scope: ["profile", "email"], state: req.query.app})(req, res, next);
});
router.get('/signin/google/callback', passport.authenticate("google", {failureRedirect: "/login", session: false}),
function (req, res) {
socialRedirect(res, req.query.state, req.user.token, config);
}
);
router.get('/signin/microsoft', (req, res, next) => {
passport.authenticate("microsoft", {
scope: ["https://graph.microsoft.com/user.read openid"],
state: req.query.app
})(req, res, next);
});
router.get('/signin/microsoft/callback', passport.authenticate("microsoft", {
failureRedirect: "/login",
session: false
}),
function (req, res) {
socialRedirect(res, req.query.state, req.user.token, config);
}
);
router.use('/', require('../helpers').commonErrorHandler);
function socialRedirect(res, state, token, config) {
res.redirect(config.uiUrl + "/login?token=" + token);
}
module.exports = router;

View File

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

View File

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

View File

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

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