Initial version

This commit is contained in:
Flatlogic Bot 2026-02-28 15:33:20 +00:00
commit 38186dcb77
553 changed files with 159191 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>OptiFin Mobile Fintech</h2>
<p>UK fintech app that routes payments via the cheapest funding source across linked banks, cards and wallets.</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 @@
# OptiFin Mobile Fintech
## 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`

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 @@
#OptiFin Mobile Fintech - 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_optifin_mobile_fintech;`
- Then give that new user privileges to the new database then quit the `psql`.
- `postgres=> GRANT ALL PRIVILEGES ON DATABASE db_optifin_mobile_fintech 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": "optifinmobilefintech",
"description": "OptiFin Mobile Fintech - 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: "35926c66",
user_pass: "58284bafa65a",
admin_email: "admin@flatlogic.com",
providers: {
LOCAL: 'local',
GOOGLE: 'google',
MICROSOFT: 'microsoft'
},
secret_key: process.env.SECRET_KEY || '35926c66-70dd-477c-98a8-58284bafa65a',
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: 'OptiFin Mobile Fintech <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: 'Customer',
},
project_uuid: '35926c66-70dd-477c-98a8-58284bafa65a',
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 = 'Lightning over calm ocean';
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,621 @@
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 Account_connectionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const account_connections = await db.account_connections.create(
{
id: data.id || undefined,
connection_kind: data.connection_kind
||
null
,
connection_status: data.connection_status
||
null
,
read_access_enabled: data.read_access_enabled
||
false
,
vrp_enabled: data.vrp_enabled
||
false
,
vrp_max_amount: data.vrp_max_amount
||
null
,
external_reference: data.external_reference
||
null
,
connected_at: data.connected_at
||
null
,
last_synced_at: data.last_synced_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await account_connections.setUser( data.user || null, {
transaction,
});
await account_connections.setInstitution( data.institution || null, {
transaction,
});
return account_connections;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const account_connectionsData = data.map((item, index) => ({
id: item.id || undefined,
connection_kind: item.connection_kind
||
null
,
connection_status: item.connection_status
||
null
,
read_access_enabled: item.read_access_enabled
||
false
,
vrp_enabled: item.vrp_enabled
||
false
,
vrp_max_amount: item.vrp_max_amount
||
null
,
external_reference: item.external_reference
||
null
,
connected_at: item.connected_at
||
null
,
last_synced_at: item.last_synced_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const account_connections = await db.account_connections.bulkCreate(account_connectionsData, { transaction });
// For each item created, replace relation files
return account_connections;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const account_connections = await db.account_connections.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.connection_kind !== undefined) updatePayload.connection_kind = data.connection_kind;
if (data.connection_status !== undefined) updatePayload.connection_status = data.connection_status;
if (data.read_access_enabled !== undefined) updatePayload.read_access_enabled = data.read_access_enabled;
if (data.vrp_enabled !== undefined) updatePayload.vrp_enabled = data.vrp_enabled;
if (data.vrp_max_amount !== undefined) updatePayload.vrp_max_amount = data.vrp_max_amount;
if (data.external_reference !== undefined) updatePayload.external_reference = data.external_reference;
if (data.connected_at !== undefined) updatePayload.connected_at = data.connected_at;
if (data.last_synced_at !== undefined) updatePayload.last_synced_at = data.last_synced_at;
updatePayload.updatedById = currentUser.id;
await account_connections.update(updatePayload, {transaction});
if (data.user !== undefined) {
await account_connections.setUser(
data.user,
{ transaction }
);
}
if (data.institution !== undefined) {
await account_connections.setInstitution(
data.institution,
{ transaction }
);
}
return account_connections;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const account_connections = await db.account_connections.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of account_connections) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of account_connections) {
await record.destroy({transaction});
}
});
return account_connections;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const account_connections = await db.account_connections.findByPk(id, options);
await account_connections.update({
deletedBy: currentUser.id
}, {
transaction,
});
await account_connections.destroy({
transaction
});
return account_connections;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const account_connections = await db.account_connections.findOne(
{ where },
{ transaction },
);
if (!account_connections) {
return account_connections;
}
const output = account_connections.get({plain: true});
output.financial_accounts_account_connection = await account_connections.getFinancial_accounts_account_connection({
transaction
});
output.user = await account_connections.getUser({
transaction
});
output.institution = await account_connections.getInstitution({
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.users,
as: 'user',
where: filter.user ? {
[Op.or]: [
{ id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.institutions,
as: 'institution',
where: filter.institution ? {
[Op.or]: [
{ id: { [Op.in]: filter.institution.split('|').map(term => Utils.uuid(term)) } },
{
display_name: {
[Op.or]: filter.institution.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.external_reference) {
where = {
...where,
[Op.and]: Utils.ilike(
'account_connections',
'external_reference',
filter.external_reference,
),
};
}
if (filter.vrp_max_amountRange) {
const [start, end] = filter.vrp_max_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
vrp_max_amount: {
...where.vrp_max_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
vrp_max_amount: {
...where.vrp_max_amount,
[Op.lte]: end,
},
};
}
}
if (filter.connected_atRange) {
const [start, end] = filter.connected_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
connected_at: {
...where.connected_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
connected_at: {
...where.connected_at,
[Op.lte]: end,
},
};
}
}
if (filter.last_synced_atRange) {
const [start, end] = filter.last_synced_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
last_synced_at: {
...where.last_synced_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
last_synced_at: {
...where.last_synced_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.connection_kind) {
where = {
...where,
connection_kind: filter.connection_kind,
};
}
if (filter.connection_status) {
where = {
...where,
connection_status: filter.connection_status,
};
}
if (filter.read_access_enabled) {
where = {
...where,
read_access_enabled: filter.read_access_enabled,
};
}
if (filter.vrp_enabled) {
where = {
...where,
vrp_enabled: filter.vrp_enabled,
};
}
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.account_connections.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'account_connections',
'external_reference',
query,
),
],
};
}
const records = await db.account_connections.findAll({
attributes: [ 'id', 'external_reference' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['external_reference', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.external_reference,
}));
}
};

View File

@ -0,0 +1,607 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Card_authorisationsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const card_authorisations = await db.card_authorisations.create(
{
id: data.id || undefined,
authorised_at: data.authorised_at
||
null
,
status: data.status
||
null
,
amount: data.amount
||
null
,
currency_code: data.currency_code
||
null
,
requires_user_approval: data.requires_user_approval
||
false
,
external_reference: data.external_reference
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await card_authorisations.setUser( data.user || null, {
transaction,
});
await card_authorisations.setVirtual_card( data.virtual_card || null, {
transaction,
});
await card_authorisations.setMerchant( data.merchant || null, {
transaction,
});
return card_authorisations;
}
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 card_authorisationsData = data.map((item, index) => ({
id: item.id || undefined,
authorised_at: item.authorised_at
||
null
,
status: item.status
||
null
,
amount: item.amount
||
null
,
currency_code: item.currency_code
||
null
,
requires_user_approval: item.requires_user_approval
||
false
,
external_reference: item.external_reference
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const card_authorisations = await db.card_authorisations.bulkCreate(card_authorisationsData, { transaction });
// For each item created, replace relation files
return card_authorisations;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const card_authorisations = await db.card_authorisations.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.authorised_at !== undefined) updatePayload.authorised_at = data.authorised_at;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.amount !== undefined) updatePayload.amount = data.amount;
if (data.currency_code !== undefined) updatePayload.currency_code = data.currency_code;
if (data.requires_user_approval !== undefined) updatePayload.requires_user_approval = data.requires_user_approval;
if (data.external_reference !== undefined) updatePayload.external_reference = data.external_reference;
updatePayload.updatedById = currentUser.id;
await card_authorisations.update(updatePayload, {transaction});
if (data.user !== undefined) {
await card_authorisations.setUser(
data.user,
{ transaction }
);
}
if (data.virtual_card !== undefined) {
await card_authorisations.setVirtual_card(
data.virtual_card,
{ transaction }
);
}
if (data.merchant !== undefined) {
await card_authorisations.setMerchant(
data.merchant,
{ transaction }
);
}
return card_authorisations;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const card_authorisations = await db.card_authorisations.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of card_authorisations) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of card_authorisations) {
await record.destroy({transaction});
}
});
return card_authorisations;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const card_authorisations = await db.card_authorisations.findByPk(id, options);
await card_authorisations.update({
deletedBy: currentUser.id
}, {
transaction,
});
await card_authorisations.destroy({
transaction
});
return card_authorisations;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const card_authorisations = await db.card_authorisations.findOne(
{ where },
{ transaction },
);
if (!card_authorisations) {
return card_authorisations;
}
const output = card_authorisations.get({plain: true});
output.payment_strategies_card_authorisation = await card_authorisations.getPayment_strategies_card_authorisation({
transaction
});
output.transactions_card_authorisation = await card_authorisations.getTransactions_card_authorisation({
transaction
});
output.user = await card_authorisations.getUser({
transaction
});
output.virtual_card = await card_authorisations.getVirtual_card({
transaction
});
output.merchant = await card_authorisations.getMerchant({
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.users,
as: 'user',
where: filter.user ? {
[Op.or]: [
{ id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.payment_cards,
as: 'virtual_card',
where: filter.virtual_card ? {
[Op.or]: [
{ id: { [Op.in]: filter.virtual_card.split('|').map(term => Utils.uuid(term)) } },
{
card_nickname: {
[Op.or]: filter.virtual_card.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.merchants,
as: 'merchant',
where: filter.merchant ? {
[Op.or]: [
{ id: { [Op.in]: filter.merchant.split('|').map(term => Utils.uuid(term)) } },
{
merchant_name: {
[Op.or]: filter.merchant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.currency_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'card_authorisations',
'currency_code',
filter.currency_code,
),
};
}
if (filter.external_reference) {
where = {
...where,
[Op.and]: Utils.ilike(
'card_authorisations',
'external_reference',
filter.external_reference,
),
};
}
if (filter.authorised_atRange) {
const [start, end] = filter.authorised_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
authorised_at: {
...where.authorised_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
authorised_at: {
...where.authorised_at,
[Op.lte]: end,
},
};
}
}
if (filter.amountRange) {
const [start, end] = filter.amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
amount: {
...where.amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
amount: {
...where.amount,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.requires_user_approval) {
where = {
...where,
requires_user_approval: filter.requires_user_approval,
};
}
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.card_authorisations.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(
'card_authorisations',
'external_reference',
query,
),
],
};
}
const records = await db.card_authorisations.findAll({
attributes: [ 'id', 'external_reference' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['external_reference', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.external_reference,
}));
}
};

View File

@ -0,0 +1,470 @@
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 Cashback_profilesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const cashback_profiles = await db.cashback_profiles.create(
{
id: data.id || undefined,
reward_type: data.reward_type
||
null
,
base_rate: data.base_rate
||
null
,
reward_currency: data.reward_currency
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await cashback_profiles.setFinancial_account( data.financial_account || null, {
transaction,
});
return cashback_profiles;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const cashback_profilesData = data.map((item, index) => ({
id: item.id || undefined,
reward_type: item.reward_type
||
null
,
base_rate: item.base_rate
||
null
,
reward_currency: item.reward_currency
||
null
,
notes: item.notes
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const cashback_profiles = await db.cashback_profiles.bulkCreate(cashback_profilesData, { transaction });
// For each item created, replace relation files
return cashback_profiles;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const cashback_profiles = await db.cashback_profiles.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.reward_type !== undefined) updatePayload.reward_type = data.reward_type;
if (data.base_rate !== undefined) updatePayload.base_rate = data.base_rate;
if (data.reward_currency !== undefined) updatePayload.reward_currency = data.reward_currency;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await cashback_profiles.update(updatePayload, {transaction});
if (data.financial_account !== undefined) {
await cashback_profiles.setFinancial_account(
data.financial_account,
{ transaction }
);
}
return cashback_profiles;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const cashback_profiles = await db.cashback_profiles.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of cashback_profiles) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of cashback_profiles) {
await record.destroy({transaction});
}
});
return cashback_profiles;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const cashback_profiles = await db.cashback_profiles.findByPk(id, options);
await cashback_profiles.update({
deletedBy: currentUser.id
}, {
transaction,
});
await cashback_profiles.destroy({
transaction
});
return cashback_profiles;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const cashback_profiles = await db.cashback_profiles.findOne(
{ where },
{ transaction },
);
if (!cashback_profiles) {
return cashback_profiles;
}
const output = cashback_profiles.get({plain: true});
output.category_reward_rules_cashback_profile = await cashback_profiles.getCategory_reward_rules_cashback_profile({
transaction
});
output.financial_account = await cashback_profiles.getFinancial_account({
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.financial_accounts,
as: 'financial_account',
where: filter.financial_account ? {
[Op.or]: [
{ id: { [Op.in]: filter.financial_account.split('|').map(term => Utils.uuid(term)) } },
{
account_label: {
[Op.or]: filter.financial_account.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.reward_currency) {
where = {
...where,
[Op.and]: Utils.ilike(
'cashback_profiles',
'reward_currency',
filter.reward_currency,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'cashback_profiles',
'notes',
filter.notes,
),
};
}
if (filter.base_rateRange) {
const [start, end] = filter.base_rateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
base_rate: {
...where.base_rate,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
base_rate: {
...where.base_rate,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.reward_type) {
where = {
...where,
reward_type: filter.reward_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.cashback_profiles.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'cashback_profiles',
'reward_currency',
query,
),
],
};
}
const records = await db.cashback_profiles.findAll({
attributes: [ 'id', 'reward_currency' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['reward_currency', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.reward_currency,
}));
}
};

View File

@ -0,0 +1,440 @@
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 Category_reward_rulesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const category_reward_rules = await db.category_reward_rules.create(
{
id: data.id || undefined,
merchant_category: data.merchant_category
||
null
,
reward_rate: data.reward_rate
||
null
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await category_reward_rules.setCashback_profile( data.cashback_profile || null, {
transaction,
});
return category_reward_rules;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const category_reward_rulesData = data.map((item, index) => ({
id: item.id || undefined,
merchant_category: item.merchant_category
||
null
,
reward_rate: item.reward_rate
||
null
,
is_active: item.is_active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const category_reward_rules = await db.category_reward_rules.bulkCreate(category_reward_rulesData, { transaction });
// For each item created, replace relation files
return category_reward_rules;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const category_reward_rules = await db.category_reward_rules.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.merchant_category !== undefined) updatePayload.merchant_category = data.merchant_category;
if (data.reward_rate !== undefined) updatePayload.reward_rate = data.reward_rate;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await category_reward_rules.update(updatePayload, {transaction});
if (data.cashback_profile !== undefined) {
await category_reward_rules.setCashback_profile(
data.cashback_profile,
{ transaction }
);
}
return category_reward_rules;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const category_reward_rules = await db.category_reward_rules.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of category_reward_rules) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of category_reward_rules) {
await record.destroy({transaction});
}
});
return category_reward_rules;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const category_reward_rules = await db.category_reward_rules.findByPk(id, options);
await category_reward_rules.update({
deletedBy: currentUser.id
}, {
transaction,
});
await category_reward_rules.destroy({
transaction
});
return category_reward_rules;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const category_reward_rules = await db.category_reward_rules.findOne(
{ where },
{ transaction },
);
if (!category_reward_rules) {
return category_reward_rules;
}
const output = category_reward_rules.get({plain: true});
output.cashback_profile = await category_reward_rules.getCashback_profile({
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.cashback_profiles,
as: 'cashback_profile',
where: filter.cashback_profile ? {
[Op.or]: [
{ id: { [Op.in]: filter.cashback_profile.split('|').map(term => Utils.uuid(term)) } },
{
reward_currency: {
[Op.or]: filter.cashback_profile.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.reward_rateRange) {
const [start, end] = filter.reward_rateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
reward_rate: {
...where.reward_rate,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
reward_rate: {
...where.reward_rate,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.merchant_category) {
where = {
...where,
merchant_category: filter.merchant_category,
};
}
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.category_reward_rules.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'category_reward_rules',
'merchant_category',
query,
),
],
};
}
const records = await db.category_reward_rules.findAll({
attributes: [ 'id', 'merchant_category' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['merchant_category', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.merchant_category,
}));
}
};

View File

@ -0,0 +1,547 @@
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 Consent_recordsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const consent_records = await db.consent_records.create(
{
id: data.id || undefined,
consent_type: data.consent_type
||
null
,
status: data.status
||
null
,
policy_version: data.policy_version
||
null
,
given_at: data.given_at
||
null
,
revoked_at: data.revoked_at
||
null
,
provider_name: data.provider_name
||
null
,
reference_code: data.reference_code
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await consent_records.setUser( data.user || null, {
transaction,
});
return consent_records;
}
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 consent_recordsData = data.map((item, index) => ({
id: item.id || undefined,
consent_type: item.consent_type
||
null
,
status: item.status
||
null
,
policy_version: item.policy_version
||
null
,
given_at: item.given_at
||
null
,
revoked_at: item.revoked_at
||
null
,
provider_name: item.provider_name
||
null
,
reference_code: item.reference_code
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const consent_records = await db.consent_records.bulkCreate(consent_recordsData, { transaction });
// For each item created, replace relation files
return consent_records;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const consent_records = await db.consent_records.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.consent_type !== undefined) updatePayload.consent_type = data.consent_type;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.policy_version !== undefined) updatePayload.policy_version = data.policy_version;
if (data.given_at !== undefined) updatePayload.given_at = data.given_at;
if (data.revoked_at !== undefined) updatePayload.revoked_at = data.revoked_at;
if (data.provider_name !== undefined) updatePayload.provider_name = data.provider_name;
if (data.reference_code !== undefined) updatePayload.reference_code = data.reference_code;
updatePayload.updatedById = currentUser.id;
await consent_records.update(updatePayload, {transaction});
if (data.user !== undefined) {
await consent_records.setUser(
data.user,
{ transaction }
);
}
return consent_records;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const consent_records = await db.consent_records.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of consent_records) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of consent_records) {
await record.destroy({transaction});
}
});
return consent_records;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const consent_records = await db.consent_records.findByPk(id, options);
await consent_records.update({
deletedBy: currentUser.id
}, {
transaction,
});
await consent_records.destroy({
transaction
});
return consent_records;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const consent_records = await db.consent_records.findOne(
{ where },
{ transaction },
);
if (!consent_records) {
return consent_records;
}
const output = consent_records.get({plain: true});
output.user = await consent_records.getUser({
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.users,
as: 'user',
where: filter.user ? {
[Op.or]: [
{ id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.policy_version) {
where = {
...where,
[Op.and]: Utils.ilike(
'consent_records',
'policy_version',
filter.policy_version,
),
};
}
if (filter.provider_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'consent_records',
'provider_name',
filter.provider_name,
),
};
}
if (filter.reference_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'consent_records',
'reference_code',
filter.reference_code,
),
};
}
if (filter.given_atRange) {
const [start, end] = filter.given_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
given_at: {
...where.given_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
given_at: {
...where.given_at,
[Op.lte]: end,
},
};
}
}
if (filter.revoked_atRange) {
const [start, end] = filter.revoked_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
revoked_at: {
...where.revoked_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
revoked_at: {
...where.revoked_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.consent_type) {
where = {
...where,
consent_type: filter.consent_type,
};
}
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.consent_records.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(
'consent_records',
'reference_code',
query,
),
],
};
}
const records = await db.consent_records.findAll({
attributes: [ 'id', 'reference_code' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['reference_code', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.reference_code,
}));
}
};

View File

@ -0,0 +1,578 @@
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 DisputesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const disputes = await db.disputes.create(
{
id: data.id || undefined,
dispute_reason: data.dispute_reason
||
null
,
description: data.description
||
null
,
status: data.status
||
null
,
opened_at: data.opened_at
||
null
,
resolved_at: data.resolved_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await disputes.setTransaction( data.transaction || null, {
transaction,
});
await disputes.setUser( data.user || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.disputes.getTableName(),
belongsToColumn: 'evidence_files',
belongsToId: disputes.id,
},
data.evidence_files,
options,
);
return disputes;
}
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 disputesData = data.map((item, index) => ({
id: item.id || undefined,
dispute_reason: item.dispute_reason
||
null
,
description: item.description
||
null
,
status: item.status
||
null
,
opened_at: item.opened_at
||
null
,
resolved_at: item.resolved_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const disputes = await db.disputes.bulkCreate(disputesData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < disputes.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.disputes.getTableName(),
belongsToColumn: 'evidence_files',
belongsToId: disputes[i].id,
},
data[i].evidence_files,
options,
);
}
return disputes;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const disputes = await db.disputes.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.dispute_reason !== undefined) updatePayload.dispute_reason = data.dispute_reason;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.opened_at !== undefined) updatePayload.opened_at = data.opened_at;
if (data.resolved_at !== undefined) updatePayload.resolved_at = data.resolved_at;
updatePayload.updatedById = currentUser.id;
await disputes.update(updatePayload, {transaction});
if (data.transaction !== undefined) {
await disputes.setTransaction(
data.transaction,
{ transaction }
);
}
if (data.user !== undefined) {
await disputes.setUser(
data.user,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.disputes.getTableName(),
belongsToColumn: 'evidence_files',
belongsToId: disputes.id,
},
data.evidence_files,
options,
);
return disputes;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const disputes = await db.disputes.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of disputes) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of disputes) {
await record.destroy({transaction});
}
});
return disputes;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const disputes = await db.disputes.findByPk(id, options);
await disputes.update({
deletedBy: currentUser.id
}, {
transaction,
});
await disputes.destroy({
transaction
});
return disputes;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const disputes = await db.disputes.findOne(
{ where },
{ transaction },
);
if (!disputes) {
return disputes;
}
const output = disputes.get({plain: true});
output.transaction = await disputes.getTransaction({
transaction
});
output.user = await disputes.getUser({
transaction
});
output.evidence_files = await disputes.getEvidence_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.transactions,
as: 'transaction',
where: filter.transaction ? {
[Op.or]: [
{ id: { [Op.in]: filter.transaction.split('|').map(term => Utils.uuid(term)) } },
{
notes: {
[Op.or]: filter.transaction.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.users,
as: 'user',
where: filter.user ? {
[Op.or]: [
{ id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.file,
as: 'evidence_files',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'disputes',
'description',
filter.description,
),
};
}
if (filter.opened_atRange) {
const [start, end] = filter.opened_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
opened_at: {
...where.opened_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
opened_at: {
...where.opened_at,
[Op.lte]: end,
},
};
}
}
if (filter.resolved_atRange) {
const [start, end] = filter.resolved_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
resolved_at: {
...where.resolved_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
resolved_at: {
...where.resolved_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.dispute_reason) {
where = {
...where,
dispute_reason: filter.dispute_reason,
};
}
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.disputes.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(
'disputes',
'status',
query,
),
],
};
}
const records = await db.disputes.findAll({
attributes: [ 'id', 'status' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['status', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.status,
}));
}
};

View File

@ -0,0 +1,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,759 @@
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 Financial_accountsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const financial_accounts = await db.financial_accounts.create(
{
id: data.id || undefined,
account_type: data.account_type
||
null
,
account_label: data.account_label
||
null
,
masked_identifier: data.masked_identifier
||
null
,
currency_code: data.currency_code
||
null
,
current_balance: data.current_balance
||
null
,
available_balance: data.available_balance
||
null
,
credit_limit: data.credit_limit
||
null
,
available_credit: data.available_credit
||
null
,
is_primary: data.is_primary
||
false
,
auto_transfer_enabled: data.auto_transfer_enabled
||
false
,
last_refreshed_at: data.last_refreshed_at
||
null
,
status: data.status
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await financial_accounts.setUser( data.user || null, {
transaction,
});
await financial_accounts.setAccount_connection( data.account_connection || null, {
transaction,
});
return financial_accounts;
}
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 financial_accountsData = data.map((item, index) => ({
id: item.id || undefined,
account_type: item.account_type
||
null
,
account_label: item.account_label
||
null
,
masked_identifier: item.masked_identifier
||
null
,
currency_code: item.currency_code
||
null
,
current_balance: item.current_balance
||
null
,
available_balance: item.available_balance
||
null
,
credit_limit: item.credit_limit
||
null
,
available_credit: item.available_credit
||
null
,
is_primary: item.is_primary
||
false
,
auto_transfer_enabled: item.auto_transfer_enabled
||
false
,
last_refreshed_at: item.last_refreshed_at
||
null
,
status: item.status
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const financial_accounts = await db.financial_accounts.bulkCreate(financial_accountsData, { transaction });
// For each item created, replace relation files
return financial_accounts;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const financial_accounts = await db.financial_accounts.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.account_type !== undefined) updatePayload.account_type = data.account_type;
if (data.account_label !== undefined) updatePayload.account_label = data.account_label;
if (data.masked_identifier !== undefined) updatePayload.masked_identifier = data.masked_identifier;
if (data.currency_code !== undefined) updatePayload.currency_code = data.currency_code;
if (data.current_balance !== undefined) updatePayload.current_balance = data.current_balance;
if (data.available_balance !== undefined) updatePayload.available_balance = data.available_balance;
if (data.credit_limit !== undefined) updatePayload.credit_limit = data.credit_limit;
if (data.available_credit !== undefined) updatePayload.available_credit = data.available_credit;
if (data.is_primary !== undefined) updatePayload.is_primary = data.is_primary;
if (data.auto_transfer_enabled !== undefined) updatePayload.auto_transfer_enabled = data.auto_transfer_enabled;
if (data.last_refreshed_at !== undefined) updatePayload.last_refreshed_at = data.last_refreshed_at;
if (data.status !== undefined) updatePayload.status = data.status;
updatePayload.updatedById = currentUser.id;
await financial_accounts.update(updatePayload, {transaction});
if (data.user !== undefined) {
await financial_accounts.setUser(
data.user,
{ transaction }
);
}
if (data.account_connection !== undefined) {
await financial_accounts.setAccount_connection(
data.account_connection,
{ transaction }
);
}
return financial_accounts;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const financial_accounts = await db.financial_accounts.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of financial_accounts) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of financial_accounts) {
await record.destroy({transaction});
}
});
return financial_accounts;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const financial_accounts = await db.financial_accounts.findByPk(id, options);
await financial_accounts.update({
deletedBy: currentUser.id
}, {
transaction,
});
await financial_accounts.destroy({
transaction
});
return financial_accounts;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const financial_accounts = await db.financial_accounts.findOne(
{ where },
{ transaction },
);
if (!financial_accounts) {
return financial_accounts;
}
const output = financial_accounts.get({plain: true});
output.payment_cards_linked_account = await financial_accounts.getPayment_cards_linked_account({
transaction
});
output.cashback_profiles_financial_account = await financial_accounts.getCashback_profiles_financial_account({
transaction
});
output.payment_rules_primary_account = await financial_accounts.getPayment_rules_primary_account({
transaction
});
output.payment_allocations_funding_account = await financial_accounts.getPayment_allocations_funding_account({
transaction
});
output.upcoming_payments_predicted_funding_account = await financial_accounts.getUpcoming_payments_predicted_funding_account({
transaction
});
output.user = await financial_accounts.getUser({
transaction
});
output.account_connection = await financial_accounts.getAccount_connection({
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.users,
as: 'user',
where: filter.user ? {
[Op.or]: [
{ id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.account_connections,
as: 'account_connection',
where: filter.account_connection ? {
[Op.or]: [
{ id: { [Op.in]: filter.account_connection.split('|').map(term => Utils.uuid(term)) } },
{
external_reference: {
[Op.or]: filter.account_connection.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.account_label) {
where = {
...where,
[Op.and]: Utils.ilike(
'financial_accounts',
'account_label',
filter.account_label,
),
};
}
if (filter.masked_identifier) {
where = {
...where,
[Op.and]: Utils.ilike(
'financial_accounts',
'masked_identifier',
filter.masked_identifier,
),
};
}
if (filter.currency_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'financial_accounts',
'currency_code',
filter.currency_code,
),
};
}
if (filter.current_balanceRange) {
const [start, end] = filter.current_balanceRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
current_balance: {
...where.current_balance,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
current_balance: {
...where.current_balance,
[Op.lte]: end,
},
};
}
}
if (filter.available_balanceRange) {
const [start, end] = filter.available_balanceRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
available_balance: {
...where.available_balance,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
available_balance: {
...where.available_balance,
[Op.lte]: end,
},
};
}
}
if (filter.credit_limitRange) {
const [start, end] = filter.credit_limitRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
credit_limit: {
...where.credit_limit,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
credit_limit: {
...where.credit_limit,
[Op.lte]: end,
},
};
}
}
if (filter.available_creditRange) {
const [start, end] = filter.available_creditRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
available_credit: {
...where.available_credit,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
available_credit: {
...where.available_credit,
[Op.lte]: end,
},
};
}
}
if (filter.last_refreshed_atRange) {
const [start, end] = filter.last_refreshed_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
last_refreshed_at: {
...where.last_refreshed_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
last_refreshed_at: {
...where.last_refreshed_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.account_type) {
where = {
...where,
account_type: filter.account_type,
};
}
if (filter.is_primary) {
where = {
...where,
is_primary: filter.is_primary,
};
}
if (filter.auto_transfer_enabled) {
where = {
...where,
auto_transfer_enabled: filter.auto_transfer_enabled,
};
}
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.financial_accounts.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(
'financial_accounts',
'account_label',
query,
),
],
};
}
const records = await db.financial_accounts.findAll({
attributes: [ 'id', 'account_label' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['account_label', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.account_label,
}));
}
};

View File

@ -0,0 +1,499 @@
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 InstitutionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const institutions = await db.institutions.create(
{
id: data.id || undefined,
display_name: data.display_name
||
null
,
institution_type: data.institution_type
||
null
,
country_code: data.country_code
||
null
,
brand_color: data.brand_color
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await institutions.setService_provider( data.service_provider || null, {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.institutions.getTableName(),
belongsToColumn: 'logo',
belongsToId: institutions.id,
},
data.logo,
options,
);
return institutions;
}
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 institutionsData = data.map((item, index) => ({
id: item.id || undefined,
display_name: item.display_name
||
null
,
institution_type: item.institution_type
||
null
,
country_code: item.country_code
||
null
,
brand_color: item.brand_color
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const institutions = await db.institutions.bulkCreate(institutionsData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < institutions.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.institutions.getTableName(),
belongsToColumn: 'logo',
belongsToId: institutions[i].id,
},
data[i].logo,
options,
);
}
return institutions;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const institutions = await db.institutions.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.display_name !== undefined) updatePayload.display_name = data.display_name;
if (data.institution_type !== undefined) updatePayload.institution_type = data.institution_type;
if (data.country_code !== undefined) updatePayload.country_code = data.country_code;
if (data.brand_color !== undefined) updatePayload.brand_color = data.brand_color;
updatePayload.updatedById = currentUser.id;
await institutions.update(updatePayload, {transaction});
if (data.service_provider !== undefined) {
await institutions.setService_provider(
data.service_provider,
{ transaction }
);
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.institutions.getTableName(),
belongsToColumn: 'logo',
belongsToId: institutions.id,
},
data.logo,
options,
);
return institutions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const institutions = await db.institutions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of institutions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of institutions) {
await record.destroy({transaction});
}
});
return institutions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const institutions = await db.institutions.findByPk(id, options);
await institutions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await institutions.destroy({
transaction
});
return institutions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const institutions = await db.institutions.findOne(
{ where },
{ transaction },
);
if (!institutions) {
return institutions;
}
const output = institutions.get({plain: true});
output.account_connections_institution = await institutions.getAccount_connections_institution({
transaction
});
output.logo = await institutions.getLogo({
transaction
});
output.service_provider = await institutions.getService_provider({
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.service_providers,
as: 'service_provider',
where: filter.service_provider ? {
[Op.or]: [
{ id: { [Op.in]: filter.service_provider.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.service_provider.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.file,
as: 'logo',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.display_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'institutions',
'display_name',
filter.display_name,
),
};
}
if (filter.country_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'institutions',
'country_code',
filter.country_code,
),
};
}
if (filter.brand_color) {
where = {
...where,
[Op.and]: Utils.ilike(
'institutions',
'brand_color',
filter.brand_color,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.institution_type) {
where = {
...where,
institution_type: filter.institution_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.institutions.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(
'institutions',
'display_name',
query,
),
],
};
}
const records = await db.institutions.findAll({
attributes: [ 'id', 'display_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['display_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.display_name,
}));
}
};

View File

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

View File

@ -0,0 +1,508 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class NotificationsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const notifications = await db.notifications.create(
{
id: data.id || undefined,
notification_type: data.notification_type
||
null
,
title_text: data.title_text
||
null
,
body_text: data.body_text
||
null
,
severity: data.severity
||
null
,
is_read: data.is_read
||
false
,
sent_at: data.sent_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await notifications.setUser( data.user || null, {
transaction,
});
return notifications;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const notificationsData = data.map((item, index) => ({
id: item.id || undefined,
notification_type: item.notification_type
||
null
,
title_text: item.title_text
||
null
,
body_text: item.body_text
||
null
,
severity: item.severity
||
null
,
is_read: item.is_read
||
false
,
sent_at: item.sent_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const notifications = await db.notifications.bulkCreate(notificationsData, { transaction });
// For each item created, replace relation files
return notifications;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const notifications = await db.notifications.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.notification_type !== undefined) updatePayload.notification_type = data.notification_type;
if (data.title_text !== undefined) updatePayload.title_text = data.title_text;
if (data.body_text !== undefined) updatePayload.body_text = data.body_text;
if (data.severity !== undefined) updatePayload.severity = data.severity;
if (data.is_read !== undefined) updatePayload.is_read = data.is_read;
if (data.sent_at !== undefined) updatePayload.sent_at = data.sent_at;
updatePayload.updatedById = currentUser.id;
await notifications.update(updatePayload, {transaction});
if (data.user !== undefined) {
await notifications.setUser(
data.user,
{ transaction }
);
}
return notifications;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const notifications = await db.notifications.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of notifications) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of notifications) {
await record.destroy({transaction});
}
});
return notifications;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const notifications = await db.notifications.findByPk(id, options);
await notifications.update({
deletedBy: currentUser.id
}, {
transaction,
});
await notifications.destroy({
transaction
});
return notifications;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const notifications = await db.notifications.findOne(
{ where },
{ transaction },
);
if (!notifications) {
return notifications;
}
const output = notifications.get({plain: true});
output.user = await notifications.getUser({
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.users,
as: 'user',
where: filter.user ? {
[Op.or]: [
{ id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.title_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'notifications',
'title_text',
filter.title_text,
),
};
}
if (filter.body_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'notifications',
'body_text',
filter.body_text,
),
};
}
if (filter.sent_atRange) {
const [start, end] = filter.sent_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sent_at: {
...where.sent_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sent_at: {
...where.sent_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.notification_type) {
where = {
...where,
notification_type: filter.notification_type,
};
}
if (filter.severity) {
where = {
...where,
severity: filter.severity,
};
}
if (filter.is_read) {
where = {
...where,
is_read: filter.is_read,
};
}
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.notifications.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'notifications',
'title_text',
query,
),
],
};
}
const records = await db.notifications.findAll({
attributes: [ 'id', 'title_text' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['title_text', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.title_text,
}));
}
};

View File

@ -0,0 +1,638 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Optimisation_summariesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const optimisation_summaries = await db.optimisation_summaries.create(
{
id: data.id || undefined,
period_start: data.period_start
||
null
,
period_end: data.period_end
||
null
,
total_saved_amount: data.total_saved_amount
||
null
,
optimised_transaction_count: data.optimised_transaction_count
||
null
,
total_transaction_count: data.total_transaction_count
||
null
,
total_cashback_amount: data.total_cashback_amount
||
null
,
total_fees_amount: data.total_fees_amount
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await optimisation_summaries.setUser( data.user || null, {
transaction,
});
return optimisation_summaries;
}
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 optimisation_summariesData = data.map((item, index) => ({
id: item.id || undefined,
period_start: item.period_start
||
null
,
period_end: item.period_end
||
null
,
total_saved_amount: item.total_saved_amount
||
null
,
optimised_transaction_count: item.optimised_transaction_count
||
null
,
total_transaction_count: item.total_transaction_count
||
null
,
total_cashback_amount: item.total_cashback_amount
||
null
,
total_fees_amount: item.total_fees_amount
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const optimisation_summaries = await db.optimisation_summaries.bulkCreate(optimisation_summariesData, { transaction });
// For each item created, replace relation files
return optimisation_summaries;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const optimisation_summaries = await db.optimisation_summaries.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.period_start !== undefined) updatePayload.period_start = data.period_start;
if (data.period_end !== undefined) updatePayload.period_end = data.period_end;
if (data.total_saved_amount !== undefined) updatePayload.total_saved_amount = data.total_saved_amount;
if (data.optimised_transaction_count !== undefined) updatePayload.optimised_transaction_count = data.optimised_transaction_count;
if (data.total_transaction_count !== undefined) updatePayload.total_transaction_count = data.total_transaction_count;
if (data.total_cashback_amount !== undefined) updatePayload.total_cashback_amount = data.total_cashback_amount;
if (data.total_fees_amount !== undefined) updatePayload.total_fees_amount = data.total_fees_amount;
updatePayload.updatedById = currentUser.id;
await optimisation_summaries.update(updatePayload, {transaction});
if (data.user !== undefined) {
await optimisation_summaries.setUser(
data.user,
{ transaction }
);
}
return optimisation_summaries;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const optimisation_summaries = await db.optimisation_summaries.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of optimisation_summaries) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of optimisation_summaries) {
await record.destroy({transaction});
}
});
return optimisation_summaries;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const optimisation_summaries = await db.optimisation_summaries.findByPk(id, options);
await optimisation_summaries.update({
deletedBy: currentUser.id
}, {
transaction,
});
await optimisation_summaries.destroy({
transaction
});
return optimisation_summaries;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const optimisation_summaries = await db.optimisation_summaries.findOne(
{ where },
{ transaction },
);
if (!optimisation_summaries) {
return optimisation_summaries;
}
const output = optimisation_summaries.get({plain: true});
output.user = await optimisation_summaries.getUser({
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.users,
as: 'user',
where: filter.user ? {
[Op.or]: [
{ id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
period_start: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
period_end: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.period_startRange) {
const [start, end] = filter.period_startRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
period_start: {
...where.period_start,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
period_start: {
...where.period_start,
[Op.lte]: end,
},
};
}
}
if (filter.period_endRange) {
const [start, end] = filter.period_endRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
period_end: {
...where.period_end,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
period_end: {
...where.period_end,
[Op.lte]: end,
},
};
}
}
if (filter.total_saved_amountRange) {
const [start, end] = filter.total_saved_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
total_saved_amount: {
...where.total_saved_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
total_saved_amount: {
...where.total_saved_amount,
[Op.lte]: end,
},
};
}
}
if (filter.optimised_transaction_countRange) {
const [start, end] = filter.optimised_transaction_countRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
optimised_transaction_count: {
...where.optimised_transaction_count,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
optimised_transaction_count: {
...where.optimised_transaction_count,
[Op.lte]: end,
},
};
}
}
if (filter.total_transaction_countRange) {
const [start, end] = filter.total_transaction_countRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
total_transaction_count: {
...where.total_transaction_count,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
total_transaction_count: {
...where.total_transaction_count,
[Op.lte]: end,
},
};
}
}
if (filter.total_cashback_amountRange) {
const [start, end] = filter.total_cashback_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
total_cashback_amount: {
...where.total_cashback_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
total_cashback_amount: {
...where.total_cashback_amount,
[Op.lte]: end,
},
};
}
}
if (filter.total_fees_amountRange) {
const [start, end] = filter.total_fees_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
total_fees_amount: {
...where.total_fees_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
total_fees_amount: {
...where.total_fees_amount,
[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.optimisation_summaries.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(
'optimisation_summaries',
'total_saved_amount',
query,
),
],
};
}
const records = await db.optimisation_summaries.findAll({
attributes: [ 'id', 'total_saved_amount' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['total_saved_amount', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.total_saved_amount,
}));
}
};

View File

@ -0,0 +1,570 @@
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 Payment_allocationsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const payment_allocations = await db.payment_allocations.create(
{
id: data.id || undefined,
allocated_amount: data.allocated_amount
||
null
,
currency_code: data.currency_code
||
null
,
fee_amount: data.fee_amount
||
null
,
fx_rate: data.fx_rate
||
null
,
cashback_amount: data.cashback_amount
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await payment_allocations.setPayment_strategy( data.payment_strategy || null, {
transaction,
});
await payment_allocations.setFunding_account( data.funding_account || null, {
transaction,
});
return payment_allocations;
}
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 payment_allocationsData = data.map((item, index) => ({
id: item.id || undefined,
allocated_amount: item.allocated_amount
||
null
,
currency_code: item.currency_code
||
null
,
fee_amount: item.fee_amount
||
null
,
fx_rate: item.fx_rate
||
null
,
cashback_amount: item.cashback_amount
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const payment_allocations = await db.payment_allocations.bulkCreate(payment_allocationsData, { transaction });
// For each item created, replace relation files
return payment_allocations;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const payment_allocations = await db.payment_allocations.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.allocated_amount !== undefined) updatePayload.allocated_amount = data.allocated_amount;
if (data.currency_code !== undefined) updatePayload.currency_code = data.currency_code;
if (data.fee_amount !== undefined) updatePayload.fee_amount = data.fee_amount;
if (data.fx_rate !== undefined) updatePayload.fx_rate = data.fx_rate;
if (data.cashback_amount !== undefined) updatePayload.cashback_amount = data.cashback_amount;
updatePayload.updatedById = currentUser.id;
await payment_allocations.update(updatePayload, {transaction});
if (data.payment_strategy !== undefined) {
await payment_allocations.setPayment_strategy(
data.payment_strategy,
{ transaction }
);
}
if (data.funding_account !== undefined) {
await payment_allocations.setFunding_account(
data.funding_account,
{ transaction }
);
}
return payment_allocations;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const payment_allocations = await db.payment_allocations.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of payment_allocations) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of payment_allocations) {
await record.destroy({transaction});
}
});
return payment_allocations;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const payment_allocations = await db.payment_allocations.findByPk(id, options);
await payment_allocations.update({
deletedBy: currentUser.id
}, {
transaction,
});
await payment_allocations.destroy({
transaction
});
return payment_allocations;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const payment_allocations = await db.payment_allocations.findOne(
{ where },
{ transaction },
);
if (!payment_allocations) {
return payment_allocations;
}
const output = payment_allocations.get({plain: true});
output.payment_strategy = await payment_allocations.getPayment_strategy({
transaction
});
output.funding_account = await payment_allocations.getFunding_account({
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.payment_strategies,
as: 'payment_strategy',
where: filter.payment_strategy ? {
[Op.or]: [
{ id: { [Op.in]: filter.payment_strategy.split('|').map(term => Utils.uuid(term)) } },
{
strategy_name: {
[Op.or]: filter.payment_strategy.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.financial_accounts,
as: 'funding_account',
where: filter.funding_account ? {
[Op.or]: [
{ id: { [Op.in]: filter.funding_account.split('|').map(term => Utils.uuid(term)) } },
{
account_label: {
[Op.or]: filter.funding_account.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.currency_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'payment_allocations',
'currency_code',
filter.currency_code,
),
};
}
if (filter.allocated_amountRange) {
const [start, end] = filter.allocated_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
allocated_amount: {
...where.allocated_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
allocated_amount: {
...where.allocated_amount,
[Op.lte]: end,
},
};
}
}
if (filter.fee_amountRange) {
const [start, end] = filter.fee_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
fee_amount: {
...where.fee_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
fee_amount: {
...where.fee_amount,
[Op.lte]: end,
},
};
}
}
if (filter.fx_rateRange) {
const [start, end] = filter.fx_rateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
fx_rate: {
...where.fx_rate,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
fx_rate: {
...where.fx_rate,
[Op.lte]: end,
},
};
}
}
if (filter.cashback_amountRange) {
const [start, end] = filter.cashback_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
cashback_amount: {
...where.cashback_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
cashback_amount: {
...where.cashback_amount,
[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.payment_allocations.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(
'payment_allocations',
'currency_code',
query,
),
],
};
}
const records = await db.payment_allocations.findAll({
attributes: [ 'id', 'currency_code' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['currency_code', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.currency_code,
}));
}
};

View File

@ -0,0 +1,744 @@
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 Payment_cardsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const payment_cards = await db.payment_cards.create(
{
id: data.id || undefined,
card_role: data.card_role
||
null
,
card_network: data.card_network
||
null
,
card_nickname: data.card_nickname
||
null
,
cardholder_name: data.cardholder_name
||
null
,
pan_last4: data.pan_last4
||
null
,
expiry_month: data.expiry_month
||
null
,
expiry_year: data.expiry_year
||
null
,
tokenisation_status: data.tokenisation_status
||
null
,
is_frozen: data.is_frozen
||
false
,
online_payments_enabled: data.online_payments_enabled
||
false
,
contactless_enabled: data.contactless_enabled
||
false
,
atm_withdrawals_enabled: data.atm_withdrawals_enabled
||
false
,
monthly_spend_limit: data.monthly_spend_limit
||
null
,
issued_at: data.issued_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await payment_cards.setUser( data.user || null, {
transaction,
});
await payment_cards.setLinked_account( data.linked_account || null, {
transaction,
});
return payment_cards;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const payment_cardsData = data.map((item, index) => ({
id: item.id || undefined,
card_role: item.card_role
||
null
,
card_network: item.card_network
||
null
,
card_nickname: item.card_nickname
||
null
,
cardholder_name: item.cardholder_name
||
null
,
pan_last4: item.pan_last4
||
null
,
expiry_month: item.expiry_month
||
null
,
expiry_year: item.expiry_year
||
null
,
tokenisation_status: item.tokenisation_status
||
null
,
is_frozen: item.is_frozen
||
false
,
online_payments_enabled: item.online_payments_enabled
||
false
,
contactless_enabled: item.contactless_enabled
||
false
,
atm_withdrawals_enabled: item.atm_withdrawals_enabled
||
false
,
monthly_spend_limit: item.monthly_spend_limit
||
null
,
issued_at: item.issued_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const payment_cards = await db.payment_cards.bulkCreate(payment_cardsData, { transaction });
// For each item created, replace relation files
return payment_cards;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const payment_cards = await db.payment_cards.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.card_role !== undefined) updatePayload.card_role = data.card_role;
if (data.card_network !== undefined) updatePayload.card_network = data.card_network;
if (data.card_nickname !== undefined) updatePayload.card_nickname = data.card_nickname;
if (data.cardholder_name !== undefined) updatePayload.cardholder_name = data.cardholder_name;
if (data.pan_last4 !== undefined) updatePayload.pan_last4 = data.pan_last4;
if (data.expiry_month !== undefined) updatePayload.expiry_month = data.expiry_month;
if (data.expiry_year !== undefined) updatePayload.expiry_year = data.expiry_year;
if (data.tokenisation_status !== undefined) updatePayload.tokenisation_status = data.tokenisation_status;
if (data.is_frozen !== undefined) updatePayload.is_frozen = data.is_frozen;
if (data.online_payments_enabled !== undefined) updatePayload.online_payments_enabled = data.online_payments_enabled;
if (data.contactless_enabled !== undefined) updatePayload.contactless_enabled = data.contactless_enabled;
if (data.atm_withdrawals_enabled !== undefined) updatePayload.atm_withdrawals_enabled = data.atm_withdrawals_enabled;
if (data.monthly_spend_limit !== undefined) updatePayload.monthly_spend_limit = data.monthly_spend_limit;
if (data.issued_at !== undefined) updatePayload.issued_at = data.issued_at;
updatePayload.updatedById = currentUser.id;
await payment_cards.update(updatePayload, {transaction});
if (data.user !== undefined) {
await payment_cards.setUser(
data.user,
{ transaction }
);
}
if (data.linked_account !== undefined) {
await payment_cards.setLinked_account(
data.linked_account,
{ transaction }
);
}
return payment_cards;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const payment_cards = await db.payment_cards.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of payment_cards) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of payment_cards) {
await record.destroy({transaction});
}
});
return payment_cards;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const payment_cards = await db.payment_cards.findByPk(id, options);
await payment_cards.update({
deletedBy: currentUser.id
}, {
transaction,
});
await payment_cards.destroy({
transaction
});
return payment_cards;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const payment_cards = await db.payment_cards.findOne(
{ where },
{ transaction },
);
if (!payment_cards) {
return payment_cards;
}
const output = payment_cards.get({plain: true});
output.card_authorisations_virtual_card = await payment_cards.getCard_authorisations_virtual_card({
transaction
});
output.user = await payment_cards.getUser({
transaction
});
output.linked_account = await payment_cards.getLinked_account({
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.users,
as: 'user',
where: filter.user ? {
[Op.or]: [
{ id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.financial_accounts,
as: 'linked_account',
where: filter.linked_account ? {
[Op.or]: [
{ id: { [Op.in]: filter.linked_account.split('|').map(term => Utils.uuid(term)) } },
{
account_label: {
[Op.or]: filter.linked_account.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.card_nickname) {
where = {
...where,
[Op.and]: Utils.ilike(
'payment_cards',
'card_nickname',
filter.card_nickname,
),
};
}
if (filter.cardholder_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'payment_cards',
'cardholder_name',
filter.cardholder_name,
),
};
}
if (filter.pan_last4) {
where = {
...where,
[Op.and]: Utils.ilike(
'payment_cards',
'pan_last4',
filter.pan_last4,
),
};
}
if (filter.expiry_month) {
where = {
...where,
[Op.and]: Utils.ilike(
'payment_cards',
'expiry_month',
filter.expiry_month,
),
};
}
if (filter.expiry_year) {
where = {
...where,
[Op.and]: Utils.ilike(
'payment_cards',
'expiry_year',
filter.expiry_year,
),
};
}
if (filter.monthly_spend_limitRange) {
const [start, end] = filter.monthly_spend_limitRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
monthly_spend_limit: {
...where.monthly_spend_limit,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
monthly_spend_limit: {
...where.monthly_spend_limit,
[Op.lte]: end,
},
};
}
}
if (filter.issued_atRange) {
const [start, end] = filter.issued_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
issued_at: {
...where.issued_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
issued_at: {
...where.issued_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.card_role) {
where = {
...where,
card_role: filter.card_role,
};
}
if (filter.card_network) {
where = {
...where,
card_network: filter.card_network,
};
}
if (filter.tokenisation_status) {
where = {
...where,
tokenisation_status: filter.tokenisation_status,
};
}
if (filter.is_frozen) {
where = {
...where,
is_frozen: filter.is_frozen,
};
}
if (filter.online_payments_enabled) {
where = {
...where,
online_payments_enabled: filter.online_payments_enabled,
};
}
if (filter.contactless_enabled) {
where = {
...where,
contactless_enabled: filter.contactless_enabled,
};
}
if (filter.atm_withdrawals_enabled) {
where = {
...where,
atm_withdrawals_enabled: filter.atm_withdrawals_enabled,
};
}
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.payment_cards.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'payment_cards',
'card_nickname',
query,
),
],
};
}
const records = await db.payment_cards.findAll({
attributes: [ 'id', 'card_nickname' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['card_nickname', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.card_nickname,
}));
}
};

View File

@ -0,0 +1,622 @@
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 Payment_rulesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const payment_rules = await db.payment_rules.create(
{
id: data.id || undefined,
auto_savings_transfers_enabled: data.auto_savings_transfers_enabled
||
false
,
auto_transfer_max_amount: data.auto_transfer_max_amount
||
null
,
cashback_routing_enabled: data.cashback_routing_enabled
||
false
,
require_full_statement_payoff: data.require_full_statement_payoff
||
false
,
fx_optimisation_enabled: data.fx_optimisation_enabled
||
false
,
international_transfer_policy: data.international_transfer_policy
||
null
,
international_auto_approve_threshold: data.international_auto_approve_threshold
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await payment_rules.setUser( data.user || null, {
transaction,
});
await payment_rules.setPrimary_account( data.primary_account || null, {
transaction,
});
await payment_rules.setSpending_categories(data.spending_categories || [], {
transaction,
});
return payment_rules;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const payment_rulesData = data.map((item, index) => ({
id: item.id || undefined,
auto_savings_transfers_enabled: item.auto_savings_transfers_enabled
||
false
,
auto_transfer_max_amount: item.auto_transfer_max_amount
||
null
,
cashback_routing_enabled: item.cashback_routing_enabled
||
false
,
require_full_statement_payoff: item.require_full_statement_payoff
||
false
,
fx_optimisation_enabled: item.fx_optimisation_enabled
||
false
,
international_transfer_policy: item.international_transfer_policy
||
null
,
international_auto_approve_threshold: item.international_auto_approve_threshold
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const payment_rules = await db.payment_rules.bulkCreate(payment_rulesData, { transaction });
// For each item created, replace relation files
return payment_rules;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const payment_rules = await db.payment_rules.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.auto_savings_transfers_enabled !== undefined) updatePayload.auto_savings_transfers_enabled = data.auto_savings_transfers_enabled;
if (data.auto_transfer_max_amount !== undefined) updatePayload.auto_transfer_max_amount = data.auto_transfer_max_amount;
if (data.cashback_routing_enabled !== undefined) updatePayload.cashback_routing_enabled = data.cashback_routing_enabled;
if (data.require_full_statement_payoff !== undefined) updatePayload.require_full_statement_payoff = data.require_full_statement_payoff;
if (data.fx_optimisation_enabled !== undefined) updatePayload.fx_optimisation_enabled = data.fx_optimisation_enabled;
if (data.international_transfer_policy !== undefined) updatePayload.international_transfer_policy = data.international_transfer_policy;
if (data.international_auto_approve_threshold !== undefined) updatePayload.international_auto_approve_threshold = data.international_auto_approve_threshold;
updatePayload.updatedById = currentUser.id;
await payment_rules.update(updatePayload, {transaction});
if (data.user !== undefined) {
await payment_rules.setUser(
data.user,
{ transaction }
);
}
if (data.primary_account !== undefined) {
await payment_rules.setPrimary_account(
data.primary_account,
{ transaction }
);
}
if (data.spending_categories !== undefined) {
await payment_rules.setSpending_categories(data.spending_categories, { transaction });
}
return payment_rules;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const payment_rules = await db.payment_rules.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of payment_rules) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of payment_rules) {
await record.destroy({transaction});
}
});
return payment_rules;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const payment_rules = await db.payment_rules.findByPk(id, options);
await payment_rules.update({
deletedBy: currentUser.id
}, {
transaction,
});
await payment_rules.destroy({
transaction
});
return payment_rules;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const payment_rules = await db.payment_rules.findOne(
{ where },
{ transaction },
);
if (!payment_rules) {
return payment_rules;
}
const output = payment_rules.get({plain: true});
output.user = await payment_rules.getUser({
transaction
});
output.primary_account = await payment_rules.getPrimary_account({
transaction
});
output.spending_categories = await payment_rules.getSpending_categories({
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.users,
as: 'user',
where: filter.user ? {
[Op.or]: [
{ id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.financial_accounts,
as: 'primary_account',
where: filter.primary_account ? {
[Op.or]: [
{ id: { [Op.in]: filter.primary_account.split('|').map(term => Utils.uuid(term)) } },
{
account_label: {
[Op.or]: filter.primary_account.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.spending_categories,
as: 'spending_categories',
required: false,
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.auto_transfer_max_amountRange) {
const [start, end] = filter.auto_transfer_max_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
auto_transfer_max_amount: {
...where.auto_transfer_max_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
auto_transfer_max_amount: {
...where.auto_transfer_max_amount,
[Op.lte]: end,
},
};
}
}
if (filter.international_auto_approve_thresholdRange) {
const [start, end] = filter.international_auto_approve_thresholdRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
international_auto_approve_threshold: {
...where.international_auto_approve_threshold,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
international_auto_approve_threshold: {
...where.international_auto_approve_threshold,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.auto_savings_transfers_enabled) {
where = {
...where,
auto_savings_transfers_enabled: filter.auto_savings_transfers_enabled,
};
}
if (filter.cashback_routing_enabled) {
where = {
...where,
cashback_routing_enabled: filter.cashback_routing_enabled,
};
}
if (filter.require_full_statement_payoff) {
where = {
...where,
require_full_statement_payoff: filter.require_full_statement_payoff,
};
}
if (filter.fx_optimisation_enabled) {
where = {
...where,
fx_optimisation_enabled: filter.fx_optimisation_enabled,
};
}
if (filter.international_transfer_policy) {
where = {
...where,
international_transfer_policy: filter.international_transfer_policy,
};
}
if (filter.spending_categories) {
const searchTerms = filter.spending_categories.split('|');
include = [
{
model: db.spending_categories,
as: 'spending_categories_filter',
required: searchTerms.length > 0,
where: searchTerms.length > 0 ? {
[Op.or]: [
{ id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
{
label: {
[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.payment_rules.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'payment_rules',
'international_transfer_policy',
query,
),
],
};
}
const records = await db.payment_rules.findAll({
attributes: [ 'id', 'international_transfer_policy' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['international_transfer_policy', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.international_transfer_policy,
}));
}
};

View File

@ -0,0 +1,590 @@
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 Payment_strategiesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const payment_strategies = await db.payment_strategies.create(
{
id: data.id || undefined,
strategy_name: data.strategy_name
||
null
,
strategy_type: data.strategy_type
||
null
,
decision_mode: data.decision_mode
||
null
,
estimated_total_fees: data.estimated_total_fees
||
null
,
estimated_savings: data.estimated_savings
||
null
,
estimated_cashback: data.estimated_cashback
||
null
,
is_selected: data.is_selected
||
false
,
explanation: data.explanation
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await payment_strategies.setCard_authorisation( data.card_authorisation || null, {
transaction,
});
return payment_strategies;
}
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 payment_strategiesData = data.map((item, index) => ({
id: item.id || undefined,
strategy_name: item.strategy_name
||
null
,
strategy_type: item.strategy_type
||
null
,
decision_mode: item.decision_mode
||
null
,
estimated_total_fees: item.estimated_total_fees
||
null
,
estimated_savings: item.estimated_savings
||
null
,
estimated_cashback: item.estimated_cashback
||
null
,
is_selected: item.is_selected
||
false
,
explanation: item.explanation
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const payment_strategies = await db.payment_strategies.bulkCreate(payment_strategiesData, { transaction });
// For each item created, replace relation files
return payment_strategies;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const payment_strategies = await db.payment_strategies.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.strategy_name !== undefined) updatePayload.strategy_name = data.strategy_name;
if (data.strategy_type !== undefined) updatePayload.strategy_type = data.strategy_type;
if (data.decision_mode !== undefined) updatePayload.decision_mode = data.decision_mode;
if (data.estimated_total_fees !== undefined) updatePayload.estimated_total_fees = data.estimated_total_fees;
if (data.estimated_savings !== undefined) updatePayload.estimated_savings = data.estimated_savings;
if (data.estimated_cashback !== undefined) updatePayload.estimated_cashback = data.estimated_cashback;
if (data.is_selected !== undefined) updatePayload.is_selected = data.is_selected;
if (data.explanation !== undefined) updatePayload.explanation = data.explanation;
updatePayload.updatedById = currentUser.id;
await payment_strategies.update(updatePayload, {transaction});
if (data.card_authorisation !== undefined) {
await payment_strategies.setCard_authorisation(
data.card_authorisation,
{ transaction }
);
}
return payment_strategies;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const payment_strategies = await db.payment_strategies.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of payment_strategies) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of payment_strategies) {
await record.destroy({transaction});
}
});
return payment_strategies;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const payment_strategies = await db.payment_strategies.findByPk(id, options);
await payment_strategies.update({
deletedBy: currentUser.id
}, {
transaction,
});
await payment_strategies.destroy({
transaction
});
return payment_strategies;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const payment_strategies = await db.payment_strategies.findOne(
{ where },
{ transaction },
);
if (!payment_strategies) {
return payment_strategies;
}
const output = payment_strategies.get({plain: true});
output.payment_allocations_payment_strategy = await payment_strategies.getPayment_allocations_payment_strategy({
transaction
});
output.transactions_selected_strategy = await payment_strategies.getTransactions_selected_strategy({
transaction
});
output.card_authorisation = await payment_strategies.getCard_authorisation({
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.card_authorisations,
as: 'card_authorisation',
where: filter.card_authorisation ? {
[Op.or]: [
{ id: { [Op.in]: filter.card_authorisation.split('|').map(term => Utils.uuid(term)) } },
{
external_reference: {
[Op.or]: filter.card_authorisation.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.strategy_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'payment_strategies',
'strategy_name',
filter.strategy_name,
),
};
}
if (filter.explanation) {
where = {
...where,
[Op.and]: Utils.ilike(
'payment_strategies',
'explanation',
filter.explanation,
),
};
}
if (filter.estimated_total_feesRange) {
const [start, end] = filter.estimated_total_feesRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
estimated_total_fees: {
...where.estimated_total_fees,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
estimated_total_fees: {
...where.estimated_total_fees,
[Op.lte]: end,
},
};
}
}
if (filter.estimated_savingsRange) {
const [start, end] = filter.estimated_savingsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
estimated_savings: {
...where.estimated_savings,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
estimated_savings: {
...where.estimated_savings,
[Op.lte]: end,
},
};
}
}
if (filter.estimated_cashbackRange) {
const [start, end] = filter.estimated_cashbackRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
estimated_cashback: {
...where.estimated_cashback,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
estimated_cashback: {
...where.estimated_cashback,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.strategy_type) {
where = {
...where,
strategy_type: filter.strategy_type,
};
}
if (filter.decision_mode) {
where = {
...where,
decision_mode: filter.decision_mode,
};
}
if (filter.is_selected) {
where = {
...where,
is_selected: filter.is_selected,
};
}
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.payment_strategies.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(
'payment_strategies',
'strategy_name',
query,
),
],
};
}
const records = await db.payment_strategies.findAll({
attributes: [ 'id', 'strategy_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['strategy_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.strategy_name,
}));
}
};

View File

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

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

@ -0,0 +1,418 @@
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,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_providersDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const service_providers = await db.service_providers.create(
{
id: data.id || undefined,
name: data.name
||
null
,
provider_type: data.provider_type
||
null
,
region: data.region
||
null
,
regulator: data.regulator
||
null
,
website_url: data.website_url
||
null
,
status: data.status
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return service_providers;
}
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_providersData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
provider_type: item.provider_type
||
null
,
region: item.region
||
null
,
regulator: item.regulator
||
null
,
website_url: item.website_url
||
null
,
status: item.status
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const service_providers = await db.service_providers.bulkCreate(service_providersData, { transaction });
// For each item created, replace relation files
return service_providers;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const service_providers = await db.service_providers.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.provider_type !== undefined) updatePayload.provider_type = data.provider_type;
if (data.region !== undefined) updatePayload.region = data.region;
if (data.regulator !== undefined) updatePayload.regulator = data.regulator;
if (data.website_url !== undefined) updatePayload.website_url = data.website_url;
if (data.status !== undefined) updatePayload.status = data.status;
updatePayload.updatedById = currentUser.id;
await service_providers.update(updatePayload, {transaction});
return service_providers;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const service_providers = await db.service_providers.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of service_providers) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of service_providers) {
await record.destroy({transaction});
}
});
return service_providers;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const service_providers = await db.service_providers.findByPk(id, options);
await service_providers.update({
deletedBy: currentUser.id
}, {
transaction,
});
await service_providers.destroy({
transaction
});
return service_providers;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const service_providers = await db.service_providers.findOne(
{ where },
{ transaction },
);
if (!service_providers) {
return service_providers;
}
const output = service_providers.get({plain: true});
output.institutions_service_provider = await service_providers.getInstitutions_service_provider({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'service_providers',
'name',
filter.name,
),
};
}
if (filter.region) {
where = {
...where,
[Op.and]: Utils.ilike(
'service_providers',
'region',
filter.region,
),
};
}
if (filter.regulator) {
where = {
...where,
[Op.and]: Utils.ilike(
'service_providers',
'regulator',
filter.regulator,
),
};
}
if (filter.website_url) {
where = {
...where,
[Op.and]: Utils.ilike(
'service_providers',
'website_url',
filter.website_url,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.provider_type) {
where = {
...where,
provider_type: filter.provider_type,
};
}
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.service_providers.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_providers',
'name',
query,
),
],
};
}
const records = await db.service_providers.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,414 @@
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 Spending_categoriesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const spending_categories = await db.spending_categories.create(
{
id: data.id || undefined,
label: data.label
||
null
,
category_key: data.category_key
||
null
,
icon_text: data.icon_text
||
null
,
is_active: data.is_active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return spending_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 spending_categoriesData = data.map((item, index) => ({
id: item.id || undefined,
label: item.label
||
null
,
category_key: item.category_key
||
null
,
icon_text: item.icon_text
||
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 spending_categories = await db.spending_categories.bulkCreate(spending_categoriesData, { transaction });
// For each item created, replace relation files
return spending_categories;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const spending_categories = await db.spending_categories.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.label !== undefined) updatePayload.label = data.label;
if (data.category_key !== undefined) updatePayload.category_key = data.category_key;
if (data.icon_text !== undefined) updatePayload.icon_text = data.icon_text;
if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
updatePayload.updatedById = currentUser.id;
await spending_categories.update(updatePayload, {transaction});
return spending_categories;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const spending_categories = await db.spending_categories.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of spending_categories) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of spending_categories) {
await record.destroy({transaction});
}
});
return spending_categories;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const spending_categories = await db.spending_categories.findByPk(id, options);
await spending_categories.update({
deletedBy: currentUser.id
}, {
transaction,
});
await spending_categories.destroy({
transaction
});
return spending_categories;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const spending_categories = await db.spending_categories.findOne(
{ where },
{ transaction },
);
if (!spending_categories) {
return spending_categories;
}
const output = spending_categories.get({plain: true});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.label) {
where = {
...where,
[Op.and]: Utils.ilike(
'spending_categories',
'label',
filter.label,
),
};
}
if (filter.icon_text) {
where = {
...where,
[Op.and]: Utils.ilike(
'spending_categories',
'icon_text',
filter.icon_text,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.category_key) {
where = {
...where,
category_key: filter.category_key,
};
}
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.spending_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(
'spending_categories',
'label',
query,
),
],
};
}
const records = await db.spending_categories.findAll({
attributes: [ 'id', 'label' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['label', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.label,
}));
}
};

View File

@ -0,0 +1,789 @@
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 TransactionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const transactions = await db.transactions.create(
{
id: data.id || undefined,
posted_at: data.posted_at
||
null
,
transaction_at: data.transaction_at
||
null
,
direction: data.direction
||
null
,
amount: data.amount
||
null
,
currency_code: data.currency_code
||
null
,
gbp_equivalent: data.gbp_equivalent
||
null
,
status: data.status
||
null
,
was_optimised: data.was_optimised
||
false
,
estimated_savings: data.estimated_savings
||
null
,
notes: data.notes
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await transactions.setUser( data.user || null, {
transaction,
});
await transactions.setMerchant( data.merchant || null, {
transaction,
});
await transactions.setCard_authorisation( data.card_authorisation || null, {
transaction,
});
await transactions.setSelected_strategy( data.selected_strategy || null, {
transaction,
});
return transactions;
}
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 transactionsData = data.map((item, index) => ({
id: item.id || undefined,
posted_at: item.posted_at
||
null
,
transaction_at: item.transaction_at
||
null
,
direction: item.direction
||
null
,
amount: item.amount
||
null
,
currency_code: item.currency_code
||
null
,
gbp_equivalent: item.gbp_equivalent
||
null
,
status: item.status
||
null
,
was_optimised: item.was_optimised
||
false
,
estimated_savings: item.estimated_savings
||
null
,
notes: item.notes
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const transactions = await db.transactions.bulkCreate(transactionsData, { transaction });
// For each item created, replace relation files
return transactions;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const transactions = await db.transactions.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.posted_at !== undefined) updatePayload.posted_at = data.posted_at;
if (data.transaction_at !== undefined) updatePayload.transaction_at = data.transaction_at;
if (data.direction !== undefined) updatePayload.direction = data.direction;
if (data.amount !== undefined) updatePayload.amount = data.amount;
if (data.currency_code !== undefined) updatePayload.currency_code = data.currency_code;
if (data.gbp_equivalent !== undefined) updatePayload.gbp_equivalent = data.gbp_equivalent;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.was_optimised !== undefined) updatePayload.was_optimised = data.was_optimised;
if (data.estimated_savings !== undefined) updatePayload.estimated_savings = data.estimated_savings;
if (data.notes !== undefined) updatePayload.notes = data.notes;
updatePayload.updatedById = currentUser.id;
await transactions.update(updatePayload, {transaction});
if (data.user !== undefined) {
await transactions.setUser(
data.user,
{ transaction }
);
}
if (data.merchant !== undefined) {
await transactions.setMerchant(
data.merchant,
{ transaction }
);
}
if (data.card_authorisation !== undefined) {
await transactions.setCard_authorisation(
data.card_authorisation,
{ transaction }
);
}
if (data.selected_strategy !== undefined) {
await transactions.setSelected_strategy(
data.selected_strategy,
{ transaction }
);
}
return transactions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const transactions = await db.transactions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of transactions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of transactions) {
await record.destroy({transaction});
}
});
return transactions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const transactions = await db.transactions.findByPk(id, options);
await transactions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await transactions.destroy({
transaction
});
return transactions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const transactions = await db.transactions.findOne(
{ where },
{ transaction },
);
if (!transactions) {
return transactions;
}
const output = transactions.get({plain: true});
output.disputes_transaction = await transactions.getDisputes_transaction({
transaction
});
output.user = await transactions.getUser({
transaction
});
output.merchant = await transactions.getMerchant({
transaction
});
output.card_authorisation = await transactions.getCard_authorisation({
transaction
});
output.selected_strategy = await transactions.getSelected_strategy({
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.users,
as: 'user',
where: filter.user ? {
[Op.or]: [
{ id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.merchants,
as: 'merchant',
where: filter.merchant ? {
[Op.or]: [
{ id: { [Op.in]: filter.merchant.split('|').map(term => Utils.uuid(term)) } },
{
merchant_name: {
[Op.or]: filter.merchant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.card_authorisations,
as: 'card_authorisation',
where: filter.card_authorisation ? {
[Op.or]: [
{ id: { [Op.in]: filter.card_authorisation.split('|').map(term => Utils.uuid(term)) } },
{
external_reference: {
[Op.or]: filter.card_authorisation.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.payment_strategies,
as: 'selected_strategy',
where: filter.selected_strategy ? {
[Op.or]: [
{ id: { [Op.in]: filter.selected_strategy.split('|').map(term => Utils.uuid(term)) } },
{
strategy_name: {
[Op.or]: filter.selected_strategy.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.currency_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'transactions',
'currency_code',
filter.currency_code,
),
};
}
if (filter.notes) {
where = {
...where,
[Op.and]: Utils.ilike(
'transactions',
'notes',
filter.notes,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
transaction_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
posted_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.posted_atRange) {
const [start, end] = filter.posted_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
posted_at: {
...where.posted_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
posted_at: {
...where.posted_at,
[Op.lte]: end,
},
};
}
}
if (filter.transaction_atRange) {
const [start, end] = filter.transaction_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
transaction_at: {
...where.transaction_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
transaction_at: {
...where.transaction_at,
[Op.lte]: end,
},
};
}
}
if (filter.amountRange) {
const [start, end] = filter.amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
amount: {
...where.amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
amount: {
...where.amount,
[Op.lte]: end,
},
};
}
}
if (filter.gbp_equivalentRange) {
const [start, end] = filter.gbp_equivalentRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
gbp_equivalent: {
...where.gbp_equivalent,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
gbp_equivalent: {
...where.gbp_equivalent,
[Op.lte]: end,
},
};
}
}
if (filter.estimated_savingsRange) {
const [start, end] = filter.estimated_savingsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
estimated_savings: {
...where.estimated_savings,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
estimated_savings: {
...where.estimated_savings,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.direction) {
where = {
...where,
direction: filter.direction,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.was_optimised) {
where = {
...where,
was_optimised: filter.was_optimised,
};
}
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.transactions.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(
'transactions',
'notes',
query,
),
],
};
}
const records = await db.transactions.findAll({
attributes: [ 'id', 'notes' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['notes', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.notes,
}));
}
};

View File

@ -0,0 +1,602 @@
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 Upcoming_paymentsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const upcoming_payments = await db.upcoming_payments.create(
{
id: data.id || undefined,
payee_name: data.payee_name
||
null
,
payment_type: data.payment_type
||
null
,
expected_amount: data.expected_amount
||
null
,
currency_code: data.currency_code
||
null
,
due_at: data.due_at
||
null
,
risk_level: data.risk_level
||
null
,
risk_note: data.risk_note
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await upcoming_payments.setUser( data.user || null, {
transaction,
});
await upcoming_payments.setPredicted_funding_account( data.predicted_funding_account || null, {
transaction,
});
return upcoming_payments;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const upcoming_paymentsData = data.map((item, index) => ({
id: item.id || undefined,
payee_name: item.payee_name
||
null
,
payment_type: item.payment_type
||
null
,
expected_amount: item.expected_amount
||
null
,
currency_code: item.currency_code
||
null
,
due_at: item.due_at
||
null
,
risk_level: item.risk_level
||
null
,
risk_note: item.risk_note
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const upcoming_payments = await db.upcoming_payments.bulkCreate(upcoming_paymentsData, { transaction });
// For each item created, replace relation files
return upcoming_payments;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const upcoming_payments = await db.upcoming_payments.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.payee_name !== undefined) updatePayload.payee_name = data.payee_name;
if (data.payment_type !== undefined) updatePayload.payment_type = data.payment_type;
if (data.expected_amount !== undefined) updatePayload.expected_amount = data.expected_amount;
if (data.currency_code !== undefined) updatePayload.currency_code = data.currency_code;
if (data.due_at !== undefined) updatePayload.due_at = data.due_at;
if (data.risk_level !== undefined) updatePayload.risk_level = data.risk_level;
if (data.risk_note !== undefined) updatePayload.risk_note = data.risk_note;
updatePayload.updatedById = currentUser.id;
await upcoming_payments.update(updatePayload, {transaction});
if (data.user !== undefined) {
await upcoming_payments.setUser(
data.user,
{ transaction }
);
}
if (data.predicted_funding_account !== undefined) {
await upcoming_payments.setPredicted_funding_account(
data.predicted_funding_account,
{ transaction }
);
}
return upcoming_payments;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const upcoming_payments = await db.upcoming_payments.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of upcoming_payments) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of upcoming_payments) {
await record.destroy({transaction});
}
});
return upcoming_payments;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const upcoming_payments = await db.upcoming_payments.findByPk(id, options);
await upcoming_payments.update({
deletedBy: currentUser.id
}, {
transaction,
});
await upcoming_payments.destroy({
transaction
});
return upcoming_payments;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const upcoming_payments = await db.upcoming_payments.findOne(
{ where },
{ transaction },
);
if (!upcoming_payments) {
return upcoming_payments;
}
const output = upcoming_payments.get({plain: true});
output.user = await upcoming_payments.getUser({
transaction
});
output.predicted_funding_account = await upcoming_payments.getPredicted_funding_account({
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.users,
as: 'user',
where: filter.user ? {
[Op.or]: [
{ id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
{
firstName: {
[Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.financial_accounts,
as: 'predicted_funding_account',
where: filter.predicted_funding_account ? {
[Op.or]: [
{ id: { [Op.in]: filter.predicted_funding_account.split('|').map(term => Utils.uuid(term)) } },
{
account_label: {
[Op.or]: filter.predicted_funding_account.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.payee_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'upcoming_payments',
'payee_name',
filter.payee_name,
),
};
}
if (filter.currency_code) {
where = {
...where,
[Op.and]: Utils.ilike(
'upcoming_payments',
'currency_code',
filter.currency_code,
),
};
}
if (filter.risk_note) {
where = {
...where,
[Op.and]: Utils.ilike(
'upcoming_payments',
'risk_note',
filter.risk_note,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
due_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
due_at: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.expected_amountRange) {
const [start, end] = filter.expected_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
expected_amount: {
...where.expected_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
expected_amount: {
...where.expected_amount,
[Op.lte]: end,
},
};
}
}
if (filter.due_atRange) {
const [start, end] = filter.due_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
due_at: {
...where.due_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
due_at: {
...where.due_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.payment_type) {
where = {
...where,
payment_type: filter.payment_type,
};
}
if (filter.risk_level) {
where = {
...where,
risk_level: filter.risk_level,
};
}
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.upcoming_payments.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'upcoming_payments',
'payee_name',
query,
),
],
};
}
const records = await db.upcoming_payments.findAll({
attributes: [ 'id', 'payee_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['payee_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.payee_name,
}));
}
};

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

@ -0,0 +1,990 @@
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.consent_records_user = await users.getConsent_records_user({
transaction
});
output.account_connections_user = await users.getAccount_connections_user({
transaction
});
output.financial_accounts_user = await users.getFinancial_accounts_user({
transaction
});
output.payment_cards_user = await users.getPayment_cards_user({
transaction
});
output.payment_rules_user = await users.getPayment_rules_user({
transaction
});
output.card_authorisations_user = await users.getCard_authorisations_user({
transaction
});
output.transactions_user = await users.getTransactions_user({
transaction
});
output.upcoming_payments_user = await users.getUpcoming_payments_user({
transaction
});
output.optimisation_summaries_user = await users.getOptimisation_summaries_user({
transaction
});
output.notifications_user = await users.getNotifications_user({
transaction
});
output.disputes_user = await users.getDisputes_user({
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_optifin_mobile_fintech',
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,211 @@
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 account_connections = sequelize.define(
'account_connections',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
connection_kind: {
type: DataTypes.ENUM,
values: [
"open_banking_uk",
"open_banking_eu",
"account_aggregator_india",
"cdr_australia",
"open_finance_brazil",
"wise_api",
"manual_card",
"emi_issuer"
],
},
connection_status: {
type: DataTypes.ENUM,
values: [
"pending",
"active",
"revoked",
"expired",
"error"
],
},
read_access_enabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
vrp_enabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
vrp_max_amount: {
type: DataTypes.DECIMAL,
},
external_reference: {
type: DataTypes.TEXT,
},
connected_at: {
type: DataTypes.DATE,
},
last_synced_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
account_connections.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.account_connections.hasMany(db.financial_accounts, {
as: 'financial_accounts_account_connection',
foreignKey: {
name: 'account_connectionId',
},
constraints: false,
});
//end loop
db.account_connections.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.account_connections.belongsTo(db.institutions, {
as: 'institution',
foreignKey: {
name: 'institutionId',
},
constraints: false,
});
db.account_connections.belongsTo(db.users, {
as: 'createdBy',
});
db.account_connections.belongsTo(db.users, {
as: 'updatedBy',
});
};
return account_connections;
};

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 card_authorisations = sequelize.define(
'card_authorisations',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
authorised_at: {
type: DataTypes.DATE,
},
status: {
type: DataTypes.ENUM,
values: [
"pending",
"approved",
"declined",
"reversed"
],
},
amount: {
type: DataTypes.DECIMAL,
},
currency_code: {
type: DataTypes.TEXT,
},
requires_user_approval: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
external_reference: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
card_authorisations.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.card_authorisations.hasMany(db.payment_strategies, {
as: 'payment_strategies_card_authorisation',
foreignKey: {
name: 'card_authorisationId',
},
constraints: false,
});
db.card_authorisations.hasMany(db.transactions, {
as: 'transactions_card_authorisation',
foreignKey: {
name: 'card_authorisationId',
},
constraints: false,
});
//end loop
db.card_authorisations.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.card_authorisations.belongsTo(db.payment_cards, {
as: 'virtual_card',
foreignKey: {
name: 'virtual_cardId',
},
constraints: false,
});
db.card_authorisations.belongsTo(db.merchants, {
as: 'merchant',
foreignKey: {
name: 'merchantId',
},
constraints: false,
});
db.card_authorisations.belongsTo(db.users, {
as: 'createdBy',
});
db.card_authorisations.belongsTo(db.users, {
as: 'updatedBy',
});
};
return card_authorisations;
};

View File

@ -0,0 +1,136 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const cashback_profiles = sequelize.define(
'cashback_profiles',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
reward_type: {
type: DataTypes.ENUM,
values: [
"cashback",
"points",
"miles"
],
},
base_rate: {
type: DataTypes.DECIMAL,
},
reward_currency: {
type: DataTypes.TEXT,
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
cashback_profiles.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.cashback_profiles.hasMany(db.category_reward_rules, {
as: 'category_reward_rules_cashback_profile',
foreignKey: {
name: 'cashback_profileId',
},
constraints: false,
});
//end loop
db.cashback_profiles.belongsTo(db.financial_accounts, {
as: 'financial_account',
foreignKey: {
name: 'financial_accountId',
},
constraints: false,
});
db.cashback_profiles.belongsTo(db.users, {
as: 'createdBy',
});
db.cashback_profiles.belongsTo(db.users, {
as: 'updatedBy',
});
};
return cashback_profiles;
};

View File

@ -0,0 +1,148 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const category_reward_rules = sequelize.define(
'category_reward_rules',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
merchant_category: {
type: DataTypes.ENUM,
values: [
"groceries",
"travel",
"shopping",
"hotels",
"transport",
"entertainment",
"health",
"subscriptions",
"utilities",
"rent",
"other"
],
},
reward_rate: {
type: DataTypes.DECIMAL,
},
is_active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
category_reward_rules.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.category_reward_rules.belongsTo(db.cashback_profiles, {
as: 'cashback_profile',
foreignKey: {
name: 'cashback_profileId',
},
constraints: false,
});
db.category_reward_rules.belongsTo(db.users, {
as: 'createdBy',
});
db.category_reward_rules.belongsTo(db.users, {
as: 'updatedBy',
});
};
return category_reward_rules;
};

View File

@ -0,0 +1,167 @@
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 consent_records = sequelize.define(
'consent_records',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
consent_type: {
type: DataTypes.ENUM,
values: [
"terms_of_service",
"open_banking_vrp",
"payment_optimisation",
"marketing",
"privacy_policy"
],
},
status: {
type: DataTypes.ENUM,
values: [
"given",
"revoked",
"expired"
],
},
policy_version: {
type: DataTypes.TEXT,
},
given_at: {
type: DataTypes.DATE,
},
revoked_at: {
type: DataTypes.DATE,
},
provider_name: {
type: DataTypes.TEXT,
},
reference_code: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
consent_records.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.consent_records.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.consent_records.belongsTo(db.users, {
as: 'createdBy',
});
db.consent_records.belongsTo(db.users, {
as: 'updatedBy',
});
};
return consent_records;
};

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 disputes = sequelize.define(
'disputes',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
dispute_reason: {
type: DataTypes.ENUM,
values: [
"fraud",
"duplicate",
"goods_not_received",
"service_not_provided",
"incorrect_amount",
"other"
],
},
description: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"opened",
"in_review",
"submitted_to_network",
"resolved",
"rejected"
],
},
opened_at: {
type: DataTypes.DATE,
},
resolved_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
disputes.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.disputes.belongsTo(db.transactions, {
as: 'transaction',
foreignKey: {
name: 'transactionId',
},
constraints: false,
});
db.disputes.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.disputes.hasMany(db.file, {
as: 'evidence_files',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.disputes.getTableName(),
belongsToColumn: 'evidence_files',
},
});
db.disputes.belongsTo(db.users, {
as: 'createdBy',
});
db.disputes.belongsTo(db.users, {
as: 'updatedBy',
});
};
return disputes;
};

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,262 @@
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 financial_accounts = sequelize.define(
'financial_accounts',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
account_type: {
type: DataTypes.ENUM,
values: [
"current",
"savings",
"isa",
"credit_card",
"wallet",
"international_bank",
"debit_card_funding"
],
},
account_label: {
type: DataTypes.TEXT,
},
masked_identifier: {
type: DataTypes.TEXT,
},
currency_code: {
type: DataTypes.TEXT,
},
current_balance: {
type: DataTypes.DECIMAL,
},
available_balance: {
type: DataTypes.DECIMAL,
},
credit_limit: {
type: DataTypes.DECIMAL,
},
available_credit: {
type: DataTypes.DECIMAL,
},
is_primary: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
auto_transfer_enabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
last_refreshed_at: {
type: DataTypes.DATE,
},
status: {
type: DataTypes.ENUM,
values: [
"active",
"inactive",
"closed"
],
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
financial_accounts.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.financial_accounts.hasMany(db.payment_cards, {
as: 'payment_cards_linked_account',
foreignKey: {
name: 'linked_accountId',
},
constraints: false,
});
db.financial_accounts.hasMany(db.cashback_profiles, {
as: 'cashback_profiles_financial_account',
foreignKey: {
name: 'financial_accountId',
},
constraints: false,
});
db.financial_accounts.hasMany(db.payment_rules, {
as: 'payment_rules_primary_account',
foreignKey: {
name: 'primary_accountId',
},
constraints: false,
});
db.financial_accounts.hasMany(db.payment_allocations, {
as: 'payment_allocations_funding_account',
foreignKey: {
name: 'funding_accountId',
},
constraints: false,
});
db.financial_accounts.hasMany(db.upcoming_payments, {
as: 'upcoming_payments_predicted_funding_account',
foreignKey: {
name: 'predicted_funding_accountId',
},
constraints: false,
});
//end loop
db.financial_accounts.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.financial_accounts.belongsTo(db.account_connections, {
as: 'account_connection',
foreignKey: {
name: 'account_connectionId',
},
constraints: false,
});
db.financial_accounts.belongsTo(db.users, {
as: 'createdBy',
});
db.financial_accounts.belongsTo(db.users, {
as: 'updatedBy',
});
};
return financial_accounts;
};

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,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 institutions = sequelize.define(
'institutions',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
display_name: {
type: DataTypes.TEXT,
},
institution_type: {
type: DataTypes.ENUM,
values: [
"uk_bank",
"uk_card_provider",
"international_bank",
"wise",
"emi_issuer"
],
},
country_code: {
type: DataTypes.TEXT,
},
brand_color: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
institutions.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.institutions.hasMany(db.account_connections, {
as: 'account_connections_institution',
foreignKey: {
name: 'institutionId',
},
constraints: false,
});
//end loop
db.institutions.belongsTo(db.service_providers, {
as: 'service_provider',
foreignKey: {
name: 'service_providerId',
},
constraints: false,
});
db.institutions.hasMany(db.file, {
as: 'logo',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.institutions.getTableName(),
belongsToColumn: 'logo',
},
});
db.institutions.belongsTo(db.users, {
as: 'createdBy',
});
db.institutions.belongsTo(db.users, {
as: 'updatedBy',
});
};
return institutions;
};

View File

@ -0,0 +1,160 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const merchants = sequelize.define(
'merchants',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
merchant_name: {
type: DataTypes.TEXT,
},
merchant_country: {
type: DataTypes.TEXT,
},
merchant_category: {
type: DataTypes.ENUM,
values: [
"groceries",
"travel",
"shopping",
"hotels",
"transport",
"entertainment",
"health",
"subscriptions",
"utilities",
"rent",
"other"
],
},
icon_hint: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
merchants.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.merchants.hasMany(db.card_authorisations, {
as: 'card_authorisations_merchant',
foreignKey: {
name: 'merchantId',
},
constraints: false,
});
db.merchants.hasMany(db.transactions, {
as: 'transactions_merchant',
foreignKey: {
name: 'merchantId',
},
constraints: false,
});
//end loop
db.merchants.belongsTo(db.users, {
as: 'createdBy',
});
db.merchants.belongsTo(db.users, {
as: 'updatedBy',
});
};
return merchants;
};

View File

@ -0,0 +1,163 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const notifications = sequelize.define(
'notifications',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
notification_type: {
type: DataTypes.ENUM,
values: [
"sync_status",
"low_balance_warning",
"approval_required",
"security_alert",
"optimisation_tip"
],
},
title_text: {
type: DataTypes.TEXT,
},
body_text: {
type: DataTypes.TEXT,
},
severity: {
type: DataTypes.ENUM,
values: [
"info",
"warning",
"critical"
],
},
is_read: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
sent_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
notifications.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.notifications.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.notifications.belongsTo(db.users, {
as: 'createdBy',
});
db.notifications.belongsTo(db.users, {
as: 'updatedBy',
});
};
return notifications;
};

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 optimisation_summaries = sequelize.define(
'optimisation_summaries',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
period_start: {
type: DataTypes.DATE,
},
period_end: {
type: DataTypes.DATE,
},
total_saved_amount: {
type: DataTypes.DECIMAL,
},
optimised_transaction_count: {
type: DataTypes.INTEGER,
},
total_transaction_count: {
type: DataTypes.INTEGER,
},
total_cashback_amount: {
type: DataTypes.DECIMAL,
},
total_fees_amount: {
type: DataTypes.DECIMAL,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
optimisation_summaries.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.optimisation_summaries.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.optimisation_summaries.belongsTo(db.users, {
as: 'createdBy',
});
db.optimisation_summaries.belongsTo(db.users, {
as: 'updatedBy',
});
};
return optimisation_summaries;
};

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 payment_allocations = sequelize.define(
'payment_allocations',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
allocated_amount: {
type: DataTypes.DECIMAL,
},
currency_code: {
type: DataTypes.TEXT,
},
fee_amount: {
type: DataTypes.DECIMAL,
},
fx_rate: {
type: DataTypes.DECIMAL,
},
cashback_amount: {
type: DataTypes.DECIMAL,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
payment_allocations.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.payment_allocations.belongsTo(db.payment_strategies, {
as: 'payment_strategy',
foreignKey: {
name: 'payment_strategyId',
},
constraints: false,
});
db.payment_allocations.belongsTo(db.financial_accounts, {
as: 'funding_account',
foreignKey: {
name: 'funding_accountId',
},
constraints: false,
});
db.payment_allocations.belongsTo(db.users, {
as: 'createdBy',
});
db.payment_allocations.belongsTo(db.users, {
as: 'updatedBy',
});
};
return payment_allocations;
};

View File

@ -0,0 +1,253 @@
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 payment_cards = sequelize.define(
'payment_cards',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
card_role: {
type: DataTypes.ENUM,
values: [
"virtual_optifin",
"funding_credit",
"funding_debit_international"
],
},
card_network: {
type: DataTypes.ENUM,
values: [
"visa",
"mastercard",
"amex",
"unknown"
],
},
card_nickname: {
type: DataTypes.TEXT,
},
cardholder_name: {
type: DataTypes.TEXT,
},
pan_last4: {
type: DataTypes.TEXT,
},
expiry_month: {
type: DataTypes.TEXT,
},
expiry_year: {
type: DataTypes.TEXT,
},
tokenisation_status: {
type: DataTypes.ENUM,
values: [
"not_started",
"tokenised",
"failed"
],
},
is_frozen: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
online_payments_enabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
contactless_enabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
atm_withdrawals_enabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
monthly_spend_limit: {
type: DataTypes.DECIMAL,
},
issued_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
payment_cards.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.payment_cards.hasMany(db.card_authorisations, {
as: 'card_authorisations_virtual_card',
foreignKey: {
name: 'virtual_cardId',
},
constraints: false,
});
//end loop
db.payment_cards.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.payment_cards.belongsTo(db.financial_accounts, {
as: 'linked_account',
foreignKey: {
name: 'linked_accountId',
},
constraints: false,
});
db.payment_cards.belongsTo(db.users, {
as: 'createdBy',
});
db.payment_cards.belongsTo(db.users, {
as: 'updatedBy',
});
};
return payment_cards;
};

View File

@ -0,0 +1,187 @@
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 payment_rules = sequelize.define(
'payment_rules',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
auto_savings_transfers_enabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
auto_transfer_max_amount: {
type: DataTypes.DECIMAL,
},
cashback_routing_enabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
require_full_statement_payoff: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
fx_optimisation_enabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
international_transfer_policy: {
type: DataTypes.ENUM,
values: [
"always_ask",
"auto_approve_under_threshold",
"never_use"
],
},
international_auto_approve_threshold: {
type: DataTypes.DECIMAL,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
payment_rules.associate = (db) => {
db.payment_rules.belongsToMany(db.spending_categories, {
as: 'spending_categories',
foreignKey: {
name: 'payment_rules_spending_categoriesId',
},
constraints: false,
through: 'payment_rulesSpending_categoriesSpending_categories',
});
db.payment_rules.belongsToMany(db.spending_categories, {
as: 'spending_categories_filter',
foreignKey: {
name: 'payment_rules_spending_categoriesId',
},
constraints: false,
through: 'payment_rulesSpending_categoriesSpending_categories',
});
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.payment_rules.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.payment_rules.belongsTo(db.financial_accounts, {
as: 'primary_account',
foreignKey: {
name: 'primary_accountId',
},
constraints: false,
});
db.payment_rules.belongsTo(db.users, {
as: 'createdBy',
});
db.payment_rules.belongsTo(db.users, {
as: 'updatedBy',
});
};
return payment_rules;
};

View File

@ -0,0 +1,187 @@
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 payment_strategies = sequelize.define(
'payment_strategies',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
strategy_name: {
type: DataTypes.TEXT,
},
strategy_type: {
type: DataTypes.ENUM,
values: [
"use_primary",
"earn_cashback",
"preserve_uk_cash",
"custom_split"
],
},
decision_mode: {
type: DataTypes.ENUM,
values: [
"auto",
"user_selected"
],
},
estimated_total_fees: {
type: DataTypes.DECIMAL,
},
estimated_savings: {
type: DataTypes.DECIMAL,
},
estimated_cashback: {
type: DataTypes.DECIMAL,
},
is_selected: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
explanation: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
payment_strategies.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.payment_strategies.hasMany(db.payment_allocations, {
as: 'payment_allocations_payment_strategy',
foreignKey: {
name: 'payment_strategyId',
},
constraints: false,
});
db.payment_strategies.hasMany(db.transactions, {
as: 'transactions_selected_strategy',
foreignKey: {
name: 'selected_strategyId',
},
constraints: false,
});
//end loop
db.payment_strategies.belongsTo(db.card_authorisations, {
as: 'card_authorisation',
foreignKey: {
name: 'card_authorisationId',
},
constraints: false,
});
db.payment_strategies.belongsTo(db.users, {
as: 'createdBy',
});
db.payment_strategies.belongsTo(db.users, {
as: 'updatedBy',
});
};
return payment_strategies;
};

View File

@ -0,0 +1,87 @@
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,120 @@
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,160 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const service_providers = sequelize.define(
'service_providers',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
provider_type: {
type: DataTypes.ENUM,
values: [
"open_banking_aggregator",
"emi_issuer",
"wise_api",
"international_open_banking",
"card_tokenisation"
],
},
region: {
type: DataTypes.TEXT,
},
regulator: {
type: DataTypes.TEXT,
},
website_url: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"active",
"inactive",
"degraded"
],
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
service_providers.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.service_providers.hasMany(db.institutions, {
as: 'institutions_service_provider',
foreignKey: {
name: 'service_providerId',
},
constraints: false,
});
//end loop
db.service_providers.belongsTo(db.users, {
as: 'createdBy',
});
db.service_providers.belongsTo(db.users, {
as: 'updatedBy',
});
};
return service_providers;
};

View File

@ -0,0 +1,135 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const spending_categories = sequelize.define(
'spending_categories',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
label: {
type: DataTypes.TEXT,
},
category_key: {
type: DataTypes.ENUM,
values: [
"travel",
"food",
"shopping",
"hotels",
"transport",
"entertainment",
"health"
],
},
icon_text: {
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,
},
);
spending_categories.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.spending_categories.belongsTo(db.users, {
as: 'createdBy',
});
db.spending_categories.belongsTo(db.users, {
as: 'updatedBy',
});
};
return spending_categories;
};

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 transactions = sequelize.define(
'transactions',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
posted_at: {
type: DataTypes.DATE,
},
transaction_at: {
type: DataTypes.DATE,
},
direction: {
type: DataTypes.ENUM,
values: [
"debit",
"credit"
],
},
amount: {
type: DataTypes.DECIMAL,
},
currency_code: {
type: DataTypes.TEXT,
},
gbp_equivalent: {
type: DataTypes.DECIMAL,
},
status: {
type: DataTypes.ENUM,
values: [
"pending",
"completed",
"failed",
"reversed"
],
},
was_optimised: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
estimated_savings: {
type: DataTypes.DECIMAL,
},
notes: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
transactions.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.transactions.hasMany(db.disputes, {
as: 'disputes_transaction',
foreignKey: {
name: 'transactionId',
},
constraints: false,
});
//end loop
db.transactions.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.transactions.belongsTo(db.merchants, {
as: 'merchant',
foreignKey: {
name: 'merchantId',
},
constraints: false,
});
db.transactions.belongsTo(db.card_authorisations, {
as: 'card_authorisation',
foreignKey: {
name: 'card_authorisationId',
},
constraints: false,
});
db.transactions.belongsTo(db.payment_strategies, {
as: 'selected_strategy',
foreignKey: {
name: 'selected_strategyId',
},
constraints: false,
});
db.transactions.belongsTo(db.users, {
as: 'createdBy',
});
db.transactions.belongsTo(db.users, {
as: 'updatedBy',
});
};
return transactions;
};

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 upcoming_payments = sequelize.define(
'upcoming_payments',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
payee_name: {
type: DataTypes.TEXT,
},
payment_type: {
type: DataTypes.ENUM,
values: [
"direct_debit",
"subscription",
"transfer",
"bill",
"other"
],
},
expected_amount: {
type: DataTypes.DECIMAL,
},
currency_code: {
type: DataTypes.TEXT,
},
due_at: {
type: DataTypes.DATE,
},
risk_level: {
type: DataTypes.ENUM,
values: [
"low",
"medium",
"high"
],
},
risk_note: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
upcoming_payments.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.upcoming_payments.belongsTo(db.users, {
as: 'user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.upcoming_payments.belongsTo(db.financial_accounts, {
as: 'predicted_funding_account',
foreignKey: {
name: 'predicted_funding_accountId',
},
constraints: false,
});
db.upcoming_payments.belongsTo(db.users, {
as: 'createdBy',
});
db.upcoming_payments.belongsTo(db.users, {
as: 'updatedBy',
});
};
return upcoming_payments;
};

View File

@ -0,0 +1,333 @@
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.consent_records, {
as: 'consent_records_user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.users.hasMany(db.account_connections, {
as: 'account_connections_user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.users.hasMany(db.financial_accounts, {
as: 'financial_accounts_user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.users.hasMany(db.payment_cards, {
as: 'payment_cards_user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.users.hasMany(db.payment_rules, {
as: 'payment_rules_user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.users.hasMany(db.card_authorisations, {
as: 'card_authorisations_user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.users.hasMany(db.transactions, {
as: 'transactions_user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.users.hasMany(db.upcoming_payments, {
as: 'upcoming_payments_user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.users.hasMany(db.optimisation_summaries, {
as: 'optimisation_summaries_user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.users.hasMany(db.notifications, {
as: 'notifications_user',
foreignKey: {
name: 'userId',
},
constraints: false,
});
db.users.hasMany(db.disputes, {
as: 'disputes_user',
foreignKey: {
name: 'userId',
},
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'});
};
};

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

@ -0,0 +1,214 @@
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 consent_recordsRoutes = require('./routes/consent_records');
const service_providersRoutes = require('./routes/service_providers');
const institutionsRoutes = require('./routes/institutions');
const account_connectionsRoutes = require('./routes/account_connections');
const financial_accountsRoutes = require('./routes/financial_accounts');
const payment_cardsRoutes = require('./routes/payment_cards');
const cashback_profilesRoutes = require('./routes/cashback_profiles');
const category_reward_rulesRoutes = require('./routes/category_reward_rules');
const payment_rulesRoutes = require('./routes/payment_rules');
const spending_categoriesRoutes = require('./routes/spending_categories');
const merchantsRoutes = require('./routes/merchants');
const card_authorisationsRoutes = require('./routes/card_authorisations');
const payment_strategiesRoutes = require('./routes/payment_strategies');
const payment_allocationsRoutes = require('./routes/payment_allocations');
const transactionsRoutes = require('./routes/transactions');
const upcoming_paymentsRoutes = require('./routes/upcoming_payments');
const optimisation_summariesRoutes = require('./routes/optimisation_summaries');
const notificationsRoutes = require('./routes/notifications');
const disputesRoutes = require('./routes/disputes');
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: "OptiFin Mobile Fintech",
description: "OptiFin Mobile Fintech 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/consent_records', passport.authenticate('jwt', {session: false}), consent_recordsRoutes);
app.use('/api/service_providers', passport.authenticate('jwt', {session: false}), service_providersRoutes);
app.use('/api/institutions', passport.authenticate('jwt', {session: false}), institutionsRoutes);
app.use('/api/account_connections', passport.authenticate('jwt', {session: false}), account_connectionsRoutes);
app.use('/api/financial_accounts', passport.authenticate('jwt', {session: false}), financial_accountsRoutes);
app.use('/api/payment_cards', passport.authenticate('jwt', {session: false}), payment_cardsRoutes);
app.use('/api/cashback_profiles', passport.authenticate('jwt', {session: false}), cashback_profilesRoutes);
app.use('/api/category_reward_rules', passport.authenticate('jwt', {session: false}), category_reward_rulesRoutes);
app.use('/api/payment_rules', passport.authenticate('jwt', {session: false}), payment_rulesRoutes);
app.use('/api/spending_categories', passport.authenticate('jwt', {session: false}), spending_categoriesRoutes);
app.use('/api/merchants', passport.authenticate('jwt', {session: false}), merchantsRoutes);
app.use('/api/card_authorisations', passport.authenticate('jwt', {session: false}), card_authorisationsRoutes);
app.use('/api/payment_strategies', passport.authenticate('jwt', {session: false}), payment_strategiesRoutes);
app.use('/api/payment_allocations', passport.authenticate('jwt', {session: false}), payment_allocationsRoutes);
app.use('/api/transactions', passport.authenticate('jwt', {session: false}), transactionsRoutes);
app.use('/api/upcoming_payments', passport.authenticate('jwt', {session: false}), upcoming_paymentsRoutes);
app.use('/api/optimisation_summaries', passport.authenticate('jwt', {session: false}), optimisation_summariesRoutes);
app.use('/api/notifications', passport.authenticate('jwt', {session: false}), notificationsRoutes);
app.use('/api/disputes', passport.authenticate('jwt', {session: false}), disputesRoutes);
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,434 @@
const express = require('express');
const Account_connectionsService = require('../services/account_connections');
const Account_connectionsDBApi = require('../db/api/account_connections');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('account_connections'));
/**
* @swagger
* components:
* schemas:
* Account_connections:
* type: object
* properties:
* external_reference:
* type: string
* default: external_reference
* vrp_max_amount:
* type: integer
* format: int64
*
*
*/
/**
* @swagger
* tags:
* name: Account_connections
* description: The Account_connections managing API
*/
/**
* @swagger
* /api/account_connections:
* post:
* security:
* - bearerAuth: []
* tags: [Account_connections]
* 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/Account_connections"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Account_connections"
* 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 Account_connectionsService.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: [Account_connections]
* 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/Account_connections"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Account_connections"
* 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 Account_connectionsService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/account_connections/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Account_connections]
* 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/Account_connections"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Account_connections"
* 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 Account_connectionsService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/account_connections/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Account_connections]
* 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/Account_connections"
* 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 Account_connectionsService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/account_connections/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Account_connections]
* 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/Account_connections"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await Account_connectionsService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/account_connections:
* get:
* security:
* - bearerAuth: []
* tags: [Account_connections]
* summary: Get all account_connections
* description: Get all account_connections
* responses:
* 200:
* description: Account_connections list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Account_connections"
* 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 Account_connectionsDBApi.findAll(
req.query, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','external_reference',
'vrp_max_amount',
'connected_at','last_synced_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/account_connections/count:
* get:
* security:
* - bearerAuth: []
* tags: [Account_connections]
* summary: Count all account_connections
* description: Count all account_connections
* responses:
* 200:
* description: Account_connections count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Account_connections"
* 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 Account_connectionsDBApi.findAll(
req.query,
null,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/account_connections/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Account_connections]
* summary: Find all account_connections that match search criteria
* description: Find all account_connections that match search criteria
* responses:
* 200:
* description: Account_connections list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Account_connections"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const payload = await Account_connectionsDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/account_connections/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Account_connections]
* 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/Account_connections"
* 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 Account_connectionsDBApi.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,436 @@
const express = require('express');
const Card_authorisationsService = require('../services/card_authorisations');
const Card_authorisationsDBApi = require('../db/api/card_authorisations');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('card_authorisations'));
/**
* @swagger
* components:
* schemas:
* Card_authorisations:
* type: object
* properties:
* currency_code:
* type: string
* default: currency_code
* external_reference:
* type: string
* default: external_reference
* amount:
* type: integer
* format: int64
*
*/
/**
* @swagger
* tags:
* name: Card_authorisations
* description: The Card_authorisations managing API
*/
/**
* @swagger
* /api/card_authorisations:
* post:
* security:
* - bearerAuth: []
* tags: [Card_authorisations]
* 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/Card_authorisations"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Card_authorisations"
* 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 Card_authorisationsService.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: [Card_authorisations]
* 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/Card_authorisations"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Card_authorisations"
* 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 Card_authorisationsService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/card_authorisations/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Card_authorisations]
* 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/Card_authorisations"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Card_authorisations"
* 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 Card_authorisationsService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/card_authorisations/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Card_authorisations]
* 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/Card_authorisations"
* 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 Card_authorisationsService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/card_authorisations/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Card_authorisations]
* 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/Card_authorisations"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await Card_authorisationsService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/card_authorisations:
* get:
* security:
* - bearerAuth: []
* tags: [Card_authorisations]
* summary: Get all card_authorisations
* description: Get all card_authorisations
* responses:
* 200:
* description: Card_authorisations list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Card_authorisations"
* 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 Card_authorisationsDBApi.findAll(
req.query, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','currency_code','external_reference',
'amount',
'authorised_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/card_authorisations/count:
* get:
* security:
* - bearerAuth: []
* tags: [Card_authorisations]
* summary: Count all card_authorisations
* description: Count all card_authorisations
* responses:
* 200:
* description: Card_authorisations count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Card_authorisations"
* 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 Card_authorisationsDBApi.findAll(
req.query,
null,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/card_authorisations/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Card_authorisations]
* summary: Find all card_authorisations that match search criteria
* description: Find all card_authorisations that match search criteria
* responses:
* 200:
* description: Card_authorisations list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Card_authorisations"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const payload = await Card_authorisationsDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/card_authorisations/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Card_authorisations]
* 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/Card_authorisations"
* 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 Card_authorisationsDBApi.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 Cashback_profilesService = require('../services/cashback_profiles');
const Cashback_profilesDBApi = require('../db/api/cashback_profiles');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('cashback_profiles'));
/**
* @swagger
* components:
* schemas:
* Cashback_profiles:
* type: object
* properties:
* reward_currency:
* type: string
* default: reward_currency
* notes:
* type: string
* default: notes
* base_rate:
* type: integer
* format: int64
*
*/
/**
* @swagger
* tags:
* name: Cashback_profiles
* description: The Cashback_profiles managing API
*/
/**
* @swagger
* /api/cashback_profiles:
* post:
* security:
* - bearerAuth: []
* tags: [Cashback_profiles]
* 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/Cashback_profiles"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Cashback_profiles"
* 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 Cashback_profilesService.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: [Cashback_profiles]
* 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/Cashback_profiles"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Cashback_profiles"
* 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 Cashback_profilesService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/cashback_profiles/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Cashback_profiles]
* 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/Cashback_profiles"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Cashback_profiles"
* 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 Cashback_profilesService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/cashback_profiles/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Cashback_profiles]
* 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/Cashback_profiles"
* 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 Cashback_profilesService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/cashback_profiles/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Cashback_profiles]
* 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/Cashback_profiles"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await Cashback_profilesService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/cashback_profiles:
* get:
* security:
* - bearerAuth: []
* tags: [Cashback_profiles]
* summary: Get all cashback_profiles
* description: Get all cashback_profiles
* responses:
* 200:
* description: Cashback_profiles list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Cashback_profiles"
* 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 Cashback_profilesDBApi.findAll(
req.query, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','reward_currency','notes',
'base_rate',
];
const opts = { fields };
try {
const csv = parse(payload.rows, opts);
res.status(200).attachment(csv);
res.send(csv)
} catch (err) {
console.error(err);
}
} else {
res.status(200).send(payload);
}
}));
/**
* @swagger
* /api/cashback_profiles/count:
* get:
* security:
* - bearerAuth: []
* tags: [Cashback_profiles]
* summary: Count all cashback_profiles
* description: Count all cashback_profiles
* responses:
* 200:
* description: Cashback_profiles count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Cashback_profiles"
* 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 Cashback_profilesDBApi.findAll(
req.query,
null,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/cashback_profiles/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Cashback_profiles]
* summary: Find all cashback_profiles that match search criteria
* description: Find all cashback_profiles that match search criteria
* responses:
* 200:
* description: Cashback_profiles list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Cashback_profiles"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const payload = await Cashback_profilesDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/cashback_profiles/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Cashback_profiles]
* 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/Cashback_profiles"
* 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 Cashback_profilesDBApi.findBy(
{ id: req.params.id },
);
res.status(200).send(payload);
}));
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

View File

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

View File

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

View File

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

View File

@ -0,0 +1,449 @@
const express = require('express');
const Financial_accountsService = require('../services/financial_accounts');
const Financial_accountsDBApi = require('../db/api/financial_accounts');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('financial_accounts'));
/**
* @swagger
* components:
* schemas:
* Financial_accounts:
* type: object
* properties:
* account_label:
* type: string
* default: account_label
* masked_identifier:
* type: string
* default: masked_identifier
* currency_code:
* type: string
* default: currency_code
* current_balance:
* type: integer
* format: int64
* available_balance:
* type: integer
* format: int64
* credit_limit:
* type: integer
* format: int64
* available_credit:
* type: integer
* format: int64
*
*
*/
/**
* @swagger
* tags:
* name: Financial_accounts
* description: The Financial_accounts managing API
*/
/**
* @swagger
* /api/financial_accounts:
* post:
* security:
* - bearerAuth: []
* tags: [Financial_accounts]
* 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/Financial_accounts"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Financial_accounts"
* 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 Financial_accountsService.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: [Financial_accounts]
* 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/Financial_accounts"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Financial_accounts"
* 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 Financial_accountsService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/financial_accounts/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Financial_accounts]
* 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/Financial_accounts"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Financial_accounts"
* 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 Financial_accountsService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/financial_accounts/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Financial_accounts]
* 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/Financial_accounts"
* 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 Financial_accountsService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/financial_accounts/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Financial_accounts]
* 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/Financial_accounts"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await Financial_accountsService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/financial_accounts:
* get:
* security:
* - bearerAuth: []
* tags: [Financial_accounts]
* summary: Get all financial_accounts
* description: Get all financial_accounts
* responses:
* 200:
* description: Financial_accounts list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Financial_accounts"
* 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 Financial_accountsDBApi.findAll(
req.query, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','account_label','masked_identifier','currency_code',
'current_balance','available_balance','credit_limit','available_credit',
'last_refreshed_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/financial_accounts/count:
* get:
* security:
* - bearerAuth: []
* tags: [Financial_accounts]
* summary: Count all financial_accounts
* description: Count all financial_accounts
* responses:
* 200:
* description: Financial_accounts count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Financial_accounts"
* 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 Financial_accountsDBApi.findAll(
req.query,
null,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/financial_accounts/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Financial_accounts]
* summary: Find all financial_accounts that match search criteria
* description: Find all financial_accounts that match search criteria
* responses:
* 200:
* description: Financial_accounts list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Financial_accounts"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const payload = await Financial_accountsDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/financial_accounts/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Financial_accounts]
* 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/Financial_accounts"
* 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 Financial_accountsDBApi.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 InstitutionsService = require('../services/institutions');
const InstitutionsDBApi = require('../db/api/institutions');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('institutions'));
/**
* @swagger
* components:
* schemas:
* Institutions:
* type: object
* properties:
* display_name:
* type: string
* default: display_name
* country_code:
* type: string
* default: country_code
* brand_color:
* type: string
* default: brand_color
*
*/
/**
* @swagger
* tags:
* name: Institutions
* description: The Institutions managing API
*/
/**
* @swagger
* /api/institutions:
* post:
* security:
* - bearerAuth: []
* tags: [Institutions]
* 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/Institutions"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Institutions"
* 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 InstitutionsService.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: [Institutions]
* 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/Institutions"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Institutions"
* 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 InstitutionsService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/institutions/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Institutions]
* 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/Institutions"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Institutions"
* 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 InstitutionsService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/institutions/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Institutions]
* 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/Institutions"
* 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 InstitutionsService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/institutions/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Institutions]
* 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/Institutions"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await InstitutionsService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/institutions:
* get:
* security:
* - bearerAuth: []
* tags: [Institutions]
* summary: Get all institutions
* description: Get all institutions
* responses:
* 200:
* description: Institutions list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Institutions"
* 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 InstitutionsDBApi.findAll(
req.query, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','display_name','country_code','brand_color',
];
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/institutions/count:
* get:
* security:
* - bearerAuth: []
* tags: [Institutions]
* summary: Count all institutions
* description: Count all institutions
* responses:
* 200:
* description: Institutions count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Institutions"
* 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 InstitutionsDBApi.findAll(
req.query,
null,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/institutions/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Institutions]
* summary: Find all institutions that match search criteria
* description: Find all institutions that match search criteria
* responses:
* 200:
* description: Institutions list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Institutions"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const payload = await InstitutionsDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/institutions/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Institutions]
* 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/Institutions"
* 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 InstitutionsDBApi.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 MerchantsService = require('../services/merchants');
const MerchantsDBApi = require('../db/api/merchants');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('merchants'));
/**
* @swagger
* components:
* schemas:
* Merchants:
* type: object
* properties:
* merchant_name:
* type: string
* default: merchant_name
* merchant_country:
* type: string
* default: merchant_country
* icon_hint:
* type: string
* default: icon_hint
*
*/
/**
* @swagger
* tags:
* name: Merchants
* description: The Merchants managing API
*/
/**
* @swagger
* /api/merchants:
* post:
* security:
* - bearerAuth: []
* tags: [Merchants]
* 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/Merchants"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Merchants"
* 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 MerchantsService.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: [Merchants]
* 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/Merchants"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Merchants"
* 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 MerchantsService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/merchants/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Merchants]
* 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/Merchants"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Merchants"
* 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 MerchantsService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/merchants/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Merchants]
* 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/Merchants"
* 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 MerchantsService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/merchants/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Merchants]
* 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/Merchants"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await MerchantsService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/merchants:
* get:
* security:
* - bearerAuth: []
* tags: [Merchants]
* summary: Get all merchants
* description: Get all merchants
* responses:
* 200:
* description: Merchants list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Merchants"
* 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 MerchantsDBApi.findAll(
req.query, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','merchant_name','merchant_country','icon_hint',
];
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/merchants/count:
* get:
* security:
* - bearerAuth: []
* tags: [Merchants]
* summary: Count all merchants
* description: Count all merchants
* responses:
* 200:
* description: Merchants count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Merchants"
* 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 MerchantsDBApi.findAll(
req.query,
null,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/merchants/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Merchants]
* summary: Find all merchants that match search criteria
* description: Find all merchants that match search criteria
* responses:
* 200:
* description: Merchants list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Merchants"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const payload = await MerchantsDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/merchants/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Merchants]
* 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/Merchants"
* 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 MerchantsDBApi.findBy(
{ id: req.params.id },
);
res.status(200).send(payload);
}));
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

View File

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

View File

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

View File

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

View File

@ -0,0 +1,2 @@

View File

@ -0,0 +1,441 @@
const express = require('express');
const Payment_allocationsService = require('../services/payment_allocations');
const Payment_allocationsDBApi = require('../db/api/payment_allocations');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('payment_allocations'));
/**
* @swagger
* components:
* schemas:
* Payment_allocations:
* type: object
* properties:
* currency_code:
* type: string
* default: currency_code
* allocated_amount:
* type: integer
* format: int64
* fee_amount:
* type: integer
* format: int64
* fx_rate:
* type: integer
* format: int64
* cashback_amount:
* type: integer
* format: int64
*/
/**
* @swagger
* tags:
* name: Payment_allocations
* description: The Payment_allocations managing API
*/
/**
* @swagger
* /api/payment_allocations:
* post:
* security:
* - bearerAuth: []
* tags: [Payment_allocations]
* 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/Payment_allocations"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Payment_allocations"
* 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 Payment_allocationsService.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: [Payment_allocations]
* 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/Payment_allocations"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Payment_allocations"
* 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 Payment_allocationsService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/payment_allocations/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Payment_allocations]
* 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/Payment_allocations"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Payment_allocations"
* 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 Payment_allocationsService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/payment_allocations/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Payment_allocations]
* 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/Payment_allocations"
* 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 Payment_allocationsService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/payment_allocations/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Payment_allocations]
* 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/Payment_allocations"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await Payment_allocationsService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/payment_allocations:
* get:
* security:
* - bearerAuth: []
* tags: [Payment_allocations]
* summary: Get all payment_allocations
* description: Get all payment_allocations
* responses:
* 200:
* description: Payment_allocations list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Payment_allocations"
* 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 Payment_allocationsDBApi.findAll(
req.query, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','currency_code',
'allocated_amount','fee_amount','fx_rate','cashback_amount',
];
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/payment_allocations/count:
* get:
* security:
* - bearerAuth: []
* tags: [Payment_allocations]
* summary: Count all payment_allocations
* description: Count all payment_allocations
* responses:
* 200:
* description: Payment_allocations count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Payment_allocations"
* 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 Payment_allocationsDBApi.findAll(
req.query,
null,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/payment_allocations/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Payment_allocations]
* summary: Find all payment_allocations that match search criteria
* description: Find all payment_allocations that match search criteria
* responses:
* 200:
* description: Payment_allocations list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Payment_allocations"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const payload = await Payment_allocationsDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/payment_allocations/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Payment_allocations]
* 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/Payment_allocations"
* 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 Payment_allocationsDBApi.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 Payment_cardsService = require('../services/payment_cards');
const Payment_cardsDBApi = require('../db/api/payment_cards');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
const { parse } = require('json2csv');
const {
checkCrudPermissions,
} = require('../middlewares/check-permissions');
router.use(checkCrudPermissions('payment_cards'));
/**
* @swagger
* components:
* schemas:
* Payment_cards:
* type: object
* properties:
* card_nickname:
* type: string
* default: card_nickname
* cardholder_name:
* type: string
* default: cardholder_name
* pan_last4:
* type: string
* default: pan_last4
* expiry_month:
* type: string
* default: expiry_month
* expiry_year:
* type: string
* default: expiry_year
* monthly_spend_limit:
* type: integer
* format: int64
*
*
*
*/
/**
* @swagger
* tags:
* name: Payment_cards
* description: The Payment_cards managing API
*/
/**
* @swagger
* /api/payment_cards:
* post:
* security:
* - bearerAuth: []
* tags: [Payment_cards]
* 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/Payment_cards"
* responses:
* 200:
* description: The item was successfully added
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Payment_cards"
* 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 Payment_cardsService.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: [Payment_cards]
* 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/Payment_cards"
* responses:
* 200:
* description: The items were successfully imported
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Payment_cards"
* 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 Payment_cardsService.bulkImport(req, res, true, link.host);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/payment_cards/{id}:
* put:
* security:
* - bearerAuth: []
* tags: [Payment_cards]
* 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/Payment_cards"
* required:
* - id
* responses:
* 200:
* description: The item data was successfully updated
* content:
* application/json:
* schema:
* $ref: "#/components/schemas/Payment_cards"
* 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 Payment_cardsService.update(req.body.data, req.body.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/payment_cards/{id}:
* delete:
* security:
* - bearerAuth: []
* tags: [Payment_cards]
* 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/Payment_cards"
* 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 Payment_cardsService.remove(req.params.id, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/payment_cards/deleteByIds:
* post:
* security:
* - bearerAuth: []
* tags: [Payment_cards]
* 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/Payment_cards"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Items not found
* 500:
* description: Some server error
*/
router.post('/deleteByIds', wrapAsync(async (req, res) => {
await Payment_cardsService.deleteByIds(req.body.data, req.currentUser);
const payload = true;
res.status(200).send(payload);
}));
/**
* @swagger
* /api/payment_cards:
* get:
* security:
* - bearerAuth: []
* tags: [Payment_cards]
* summary: Get all payment_cards
* description: Get all payment_cards
* responses:
* 200:
* description: Payment_cards list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Payment_cards"
* 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 Payment_cardsDBApi.findAll(
req.query, { currentUser }
);
if (filetype && filetype === 'csv') {
const fields = ['id','card_nickname','cardholder_name','pan_last4','expiry_month','expiry_year',
'monthly_spend_limit',
'issued_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/payment_cards/count:
* get:
* security:
* - bearerAuth: []
* tags: [Payment_cards]
* summary: Count all payment_cards
* description: Count all payment_cards
* responses:
* 200:
* description: Payment_cards count successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Payment_cards"
* 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 Payment_cardsDBApi.findAll(
req.query,
null,
{ countOnly: true, currentUser }
);
res.status(200).send(payload);
}));
/**
* @swagger
* /api/payment_cards/autocomplete:
* get:
* security:
* - bearerAuth: []
* tags: [Payment_cards]
* summary: Find all payment_cards that match search criteria
* description: Find all payment_cards that match search criteria
* responses:
* 200:
* description: Payment_cards list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Payment_cards"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get('/autocomplete', async (req, res) => {
const payload = await Payment_cardsDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
);
res.status(200).send(payload);
});
/**
* @swagger
* /api/payment_cards/{id}:
* get:
* security:
* - bearerAuth: []
* tags: [Payment_cards]
* 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/Payment_cards"
* 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 Payment_cardsDBApi.findBy(
{ id: req.params.id },
);
res.status(200).send(payload);
}));
router.use('/', require('../helpers').commonErrorHandler);
module.exports = router;

View File

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

View File

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

View File

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

View File

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

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

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

View File

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

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