Initial version

This commit is contained in:
Flatlogic Bot 2025-07-08 14:53:46 +00:00
commit 449acb7cc9
684 changed files with 129839 additions and 0 deletions

3
.gitignore vendored Normal file
View File

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

187
502.html Normal file
View File

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

17
Dockerfile Normal file
View File

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

73
Dockerfile.dev Normal file
View File

@ -0,0 +1,73 @@
# 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
RUN apk add --no-cache lsof procps
RUN yarn global add concurrently
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 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
# Copy all files from root to /app
COPY . /app
# 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"]

74
LICENSE.MD Normal file
View File

@ -0,0 +1,74 @@
Flatlogic Community Licence 1.0.0
---------------------------------
Required Notice: Copyright © 2025 Flatlogic sp. z o.o. (https://flatlogic.com)
## Acceptance
In order to get any licence under these terms, you must agree to them as both strict obligations and conditions to all your licences.
## Copyright Licence
The licensor grants you a copyright licence for the software to do everything you might do with the software that would otherwise infringe the licensors copyright in it for any permitted purpose. However, you may only distribute the software according to **DistributionLicence** and make changes or new works based on the software according to **ChangesandNewWorksLicence**.
## Distribution Licence
The licensor grants you an additional copyright licence to distribute copies of the software. Your licence to distribute covers distributing the software with changes and new works permitted by **ChangesandNewWorksLicence**.
## Notices
You must ensure that anyone who gets a copy of any part of the software from you also gets a copy of these terms or the URL for them above, as well as copies of any plaintext lines beginning with `Required Notice:` that the licensor provided with the software. For example:
> Required Notice: Copyright © 2025 Flatlogic sp. zo.o. (https://flatlogic.com)
## Changes and New Works Licence
The licensor grants you an additional copyright licence to make changes and new works based on the software for any permitted purpose.
## Patent Licence
The licensor grants you a patent licence for the software that covers patent claims the licensor can license, or becomes able to license, that you would infringe by using the software.
## Noncompete
Any purpose is a permitted purpose, **except for providing any product that competes with the software or any product the licensor or any of its affiliates provides using the software.**
## Competition
Goods and services compete even when they provide functionality through different kinds of interfaces or for different technical platforms. Applications can compete with services, libraries with plugins, frameworks with development tools, and so on, even if theyre written in different programming languages or for different computer architectures. Goods and services compete even when provided free of charge.
If you market a product as a practical substitute for the software or another product, it definitely competes.
## New Products
If you are using the software to provide a product that does not compete, but the licensor or any of its affiliates brings your product into competition by providing a new version of the software or another product using the software, you may continue using versions of the software available under these terms beforehand to provide your competing product, but not any later versions.
## Discontinued Products
You may begin using the software to compete with a product or service that the licensor or any of its affiliates has stopped providing, unless the licensor includes a plaintext line beginning with `Licensor Line of Business:` with the software that mentions that line of business. For example:
> Licensor Line of Business: Flatlogic Generator SaaS (https://flatlogic.com/generator)
## Sales of Business
If the licensor or any of its affiliates sells a line of business developing the software or using the software to provide a product, the buyer can also enforce **Noncompete** for that product.
## Fair Use
You may have “fair use” rights for the software under the law. These terms do not limit them.
## No Other Rights
These terms do not allow you to sublicense or transfer any of your licences to anyone else, or prevent the licensor from granting licences to anyone else. These terms do not imply any other licences.
## Patent Defence
If you make any written claim that the software infringes or contributes to infringement of any patent, your patent licence for the software granted under these terms ends immediately. If your company makes such a claim, your patent licence ends immediately for work on behalf of your company.
## Violations
The first time you are notified in writing that you have violated any of these terms, or done anything with the software not covered by your licences, your licences can nonetheless continue if you come into full compliance with these terms, and take practical steps to correct past violations, within 32days of receiving notice. Otherwise, all your licences end immediately.
## No Liability
As far as the law allows, the software comes asis, without any warranty or condition, and the licensor will not be liable to you for any damages arising out of these terms or the use or nature of the software, under any kind of legal claim.
## Definitions
*The licensor* is Flatlogic sp. zo.o., and *the software* is the **Flatlogic Community Template** we make available under these terms.
*A product* can be a good or service, or a combination of them.
*You* refers to the individual or entity agreeing to these terms.
*Your company* is any legal entity, sole proprietorship, or other kind of organisation that you work for, plus all its affiliates.
*Affiliates* means the other organisations that an organisation has control over, is under the control of, or is under common control with.
*Control* means ownership of substantially all the assets of an entity, or the power to direct its management and policies by vote, contract, or otherwise. Control can be direct or indirect.
*Your licences* are all the licences granted to you for the software under these terms.
*Use* means anything you do with the software requiring one of your licences.

170
README.MD Normal file
View File

@ -0,0 +1,170 @@
# Project Setup & Local Development
## Tech Stack
| Layer | Technology |
| --------- | -------------------- |
| Frontend | **React JS** |
| Backend | **Node JS** |
| Database | **PostgreSQL** |
| Container | **Docker & Compose** |
---
## 1  Run Locally (without Docker)
### 1.1 Backend
```bash
cd backend
# install dependencies
yarn install
```
\#### Configure PostgreSQL
<details>
<summary><strong>macOS</strong></summary>
```bash
brew install postgres
```
</details>
<details>
<summary><strong>Ubuntu</strong></summary>
```bash
sudo apt update
sudo apt install postgresql postgresql-contrib
```
</details>
\##### Create DB & Admin User
```bash
# log in as default superuser
psql postgres -U postgres
-- inside psql
CREATE ROLE admin WITH LOGIN PASSWORD 'admin_pass';
ALTER ROLE admin CREATEDB;
\q
# log in as the new user
psql postgres -U admin
-- inside psql
CREATE DATABASE db_<your_project_name>;
GRANT ALL PRIVILEGES ON DATABASE db_<your_project_name> TO admin;
\q
```
\##### Migrate & Start
```bash
yarn db:create # generate schema
yarn start # production build
```
### 1.2 Frontend
```bash
cd frontend
yarn install
yarn start
```
> Frontend devserver runs at **[http://localhost:3000](http://localhost:3000)** by default.
---
## 2  Run with Docker
```bash
cd docker
chmod +x wait-for-it.sh start-backend.sh
```
| Scenario | Command |
| ------------------------- | ---------------------------------- |
| **Fresh DB volume** | `rm -rf data && docker-compose up` |
| **Reuse existing volume** | `docker-compose up` |
Then open **[http://localhost:3000](http://localhost:3000)**.
Stop services with **Ctrl + C** or:
```bash
docker-compose down
```
> **Headsup:** Files inside the `docker/` folder and the root `Dockerfile` are used for cloud deployment. Changing them may break the pipeline.
---
## Folder Structure (toplevel)
```text
├── backend/ # Node JS API & services
├── frontend/ # React application
├── docker/ # Compose files & helper scripts
└── README.md # (this file)
```
---
## Troubleshooting
### “connection refused”
1. Port closed or backlog full.
2. Firewall (local or network).
3. Service not running.
Verify with:
```bash
telnet <host> <port>
```
### macOS
```bash
sudo service ssh status
```
### Ubuntu IP conflict check
```bash
arp-scan -I eth0 -l | grep <ipaddress>
arping <ipaddress>
```
### Reset PostgreSQL schema (macOS example)
```sql
DROP SCHEMA public CASCADE;
CREATE SCHEMA public;
GRANT ALL ON SCHEMA public TO postgres;
GRANT ALL ON SCHEMA public TO public;
```
---
## Cheatsheet
| Task | Command |
| ----------------------- | ---------------------------------- |
| **Create DB schema** | `yarn db:create` |
| **Start backend** | `yarn start` |
| **Start dev frontend** | `cd frontend && yarn start` |
| **Compose up (fresh)** | `rm -rf data && docker-compose up` |
| **Compose down** | `docker-compose down` |
<br/>
---
Made with ❤ by Flatlogic Platform.

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

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

11
app-shell/.prettierrc Normal file
View File

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

7
app-shell/.sequelizerc Normal file
View File

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

23
app-shell/Dockerfile Normal file
View File

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

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

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

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

@ -0,0 +1,42 @@
{
"name": "app-shell",
"description": "app-shell",
"scripts": {
"start": "node ./src/index.js"
},
"dependencies": {
"@babel/parser": "^7.26.7",
"adm-zip": "^0.5.16",
"axios": "^1.6.7",
"bcrypt": "5.1.1",
"cors": "2.8.5",
"eslint": "^9.13.0",
"express": "4.18.2",
"formidable": "1.2.2",
"helmet": "4.1.1",
"json2csv": "^5.0.7",
"jsonwebtoken": "8.5.1",
"lodash": "4.17.21",
"moment": "2.30.1",
"multer": "^1.4.4",
"passport": "^0.7.0",
"passport-google-oauth2": "^0.2.0",
"passport-jwt": "^4.0.1",
"passport-microsoft": "^0.1.0",
"postcss": "^8.5.1",
"sequelize-json-schema": "^2.1.1",
"pg": "^8.13.3"
},
"engines": {
"node": ">=18"
},
"private": true,
"devDependencies": {
"@typescript-eslint/eslint-plugin": "^8.12.2",
"@typescript-eslint/parser": "^8.12.2",
"cross-env": "7.0.3",
"mocha": "8.1.3",
"nodemon": "^3.1.7",
"sequelize-cli": "6.6.2"
}
}

File diff suppressed because one or more lines are too long

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

@ -0,0 +1,16 @@
const config = {
schema_encryption_key: process.env.SCHEMA_ENCRYPTION_KEY || '',
project_uuid: 'f087aa9d-30b0-40b5-857b-8f5c99381bbf',
flHost: process.env.NODE_ENV === 'production' ? 'https://flatlogic.com/projects' : 'http://localhost:3000/projects',
gitea_domain: process.env.GITEA_DOMAIN || 'gitea.flatlogic.app',
gitea_username: process.env.GITEA_USERNAME || 'admin',
gitea_api_token: process.env.GITEA_API_TOKEN || null,
github_repo_url: process.env.GITHUB_REPO_URL || null,
github_token: process.env.GITHUB_TOKEN || null,
};
module.exports = config;

23
app-shell/src/helpers.js Normal file
View File

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

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

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

View File

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

View File

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

View File

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

View File

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

View File

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

File diff suppressed because it is too large Load Diff

View File

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

View File

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

View File

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

View File

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

View File

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

File diff suppressed because it is too large Load Diff

3044
app-shell/yarn.lock Normal file

File diff suppressed because it is too large Load Diff

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

53
backend/package.json Normal file
View File

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

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

@ -0,0 +1,27 @@
const config = require('../config');
const passport = require('passport');
const JWTstrategy = require('passport-jwt').Strategy;
const ExtractJWT = require('passport-jwt').ExtractJwt;
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);
}
}));

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

@ -0,0 +1,59 @@
const os = require('os');
const config = {
gcloud: {
bucket: "fldemo-files",
hash: "5bad16aa22cf5ea65fe7a463302d6865"
},
bcrypt: {
saltRounds: 12
},
admin_pass: "f087aa9d",
user_pass: "8f5c99381bbf",
admin_email: "admin@flatlogic.com",
providers: {
LOCAL: 'local',
GOOGLE: 'google',
MICROSOFT: 'microsoft'
},
secret_key: process.env.SECRET_KEY || '',
remote: '',
port: process.env.NODE_ENV === "production" ? "" : "8080",
hostUI: process.env.NODE_ENV === "production" ? "" : "http://localhost",
portUI: process.env.NODE_ENV === "production" ? "" : "3000",
portUIProd: process.env.NODE_ENV === "production" ? "" : ":3000",
swaggerUI: process.env.NODE_ENV === "production" ? "" : "http://localhost",
swaggerPort: process.env.NODE_ENV === "production" ? "" : ":8080",
uploadDir: os.tmpdir(),
email: {
from: 'meng-leap-cash <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: 'User',
},
project_uuid: 'f087aa9d-30b0-40b5-857b-8f5c99381bbf',
flHost: process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'dev_stage' ? 'https://flatlogic.com/projects' : 'http://localhost:3000/projects',
};
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,313 @@
const db = require('../models');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class BranchesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const branches = await db.branches.create(
{
id: data.id || undefined,
code: data.code
||
null
,
name: data.name
||
null
,
description: data.description
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return branches;
}
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 branchesData = data.map((item, index) => ({
id: item.id || undefined,
code: item.code
||
null
,
name: item.name
||
null
,
description: item.description
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const branches = await db.branches.bulkCreate(branchesData, { transaction });
return branches;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const branches = await db.branches.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.code !== undefined) updatePayload.code = data.code;
if (data.name !== undefined) updatePayload.name = data.name;
if (data.description !== undefined) updatePayload.description = data.description;
updatePayload.updatedById = currentUser.id;
await branches.update(updatePayload, {transaction});
return branches;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const branches = await db.branches.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of branches) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of branches) {
await record.destroy({transaction});
}
});
return branches;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const branches = await db.branches.findByPk(id, options);
await branches.update({
deletedBy: currentUser.id
}, {
transaction,
});
await branches.destroy({
transaction
});
return branches;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const branches = await db.branches.findOne(
{ where },
{ transaction },
);
if (!branches) {
return branches;
}
const output = branches.get({plain: true});
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
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.code) {
where = {
...where,
[Op.and]: Utils.ilike(
'branches',
'code',
filter.code,
),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'branches',
'name',
filter.name,
),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'branches',
'description',
filter.description,
),
};
}
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.branches.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(
'branches',
'name',
query,
),
],
};
}
const records = await db.branches.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,368 @@
const db = require('../models');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class CalendarsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const calendars = await db.calendars.create(
{
id: data.id || undefined,
date: data.date
||
null
,
is_weekend: data.is_weekend
||
false
,
is_holiday: data.is_holiday
||
false
,
description: data.description
||
null
,
flag: data.flag
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return calendars;
}
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 calendarsData = data.map((item, index) => ({
id: item.id || undefined,
date: item.date
||
null
,
is_weekend: item.is_weekend
||
false
,
is_holiday: item.is_holiday
||
false
,
description: item.description
||
null
,
flag: item.flag
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const calendars = await db.calendars.bulkCreate(calendarsData, { transaction });
return calendars;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const calendars = await db.calendars.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.date !== undefined) updatePayload.date = data.date;
if (data.is_weekend !== undefined) updatePayload.is_weekend = data.is_weekend;
if (data.is_holiday !== undefined) updatePayload.is_holiday = data.is_holiday;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.flag !== undefined) updatePayload.flag = data.flag;
updatePayload.updatedById = currentUser.id;
await calendars.update(updatePayload, {transaction});
return calendars;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const calendars = await db.calendars.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of calendars) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of calendars) {
await record.destroy({transaction});
}
});
return calendars;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const calendars = await db.calendars.findByPk(id, options);
await calendars.update({
deletedBy: currentUser.id
}, {
transaction,
});
await calendars.destroy({
transaction
});
return calendars;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const calendars = await db.calendars.findOne(
{ where },
{ transaction },
);
if (!calendars) {
return calendars;
}
const output = calendars.get({plain: true});
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
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.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'calendars',
'description',
filter.description,
),
};
}
if (filter.flag) {
where = {
...where,
[Op.and]: Utils.ilike(
'calendars',
'flag',
filter.flag,
),
};
}
if (filter.dateRange) {
const [start, end] = filter.dateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
date: {
...where.date,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
date: {
...where.date,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.is_weekend) {
where = {
...where,
is_weekend: filter.is_weekend,
};
}
if (filter.is_holiday) {
where = {
...where,
is_holiday: filter.is_holiday,
};
}
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.calendars.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(
'calendars',
'description',
query,
),
],
};
}
const records = await db.calendars.findAll({
attributes: [ 'id', 'description' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['description', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.description,
}));
}
};

View File

@ -0,0 +1,267 @@
const db = require('../models');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Client_statusDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const client_status = await db.client_status.create(
{
id: data.id || undefined,
name: data.name
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return client_status;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const client_statusData = 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 client_status = await db.client_status.bulkCreate(client_statusData, { transaction });
return client_status;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const client_status = await db.client_status.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
updatePayload.updatedById = currentUser.id;
await client_status.update(updatePayload, {transaction});
return client_status;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const client_status = await db.client_status.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of client_status) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of client_status) {
await record.destroy({transaction});
}
});
return client_status;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const client_status = await db.client_status.findByPk(id, options);
await client_status.update({
deletedBy: currentUser.id
}, {
transaction,
});
await client_status.destroy({
transaction
});
return client_status;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const client_status = await db.client_status.findOne(
{ where },
{ transaction },
);
if (!client_status) {
return client_status;
}
const output = client_status.get({plain: true});
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
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(
'client_status',
'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.client_status.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'client_status',
'name',
query,
),
],
};
}
const records = await db.client_status.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,435 @@
const db = require('../models');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class ClientsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const clients = await db.clients.create(
{
id: data.id || undefined,
code: data.code
||
null
,
name_en: data.name_en
||
null
,
name_kh: data.name_kh
||
null
,
date_of_birth: data.date_of_birth
||
null
,
phone_number: data.phone_number
||
null
,
is_new: data.is_new
||
false
,
document_number: data.document_number
||
null
,
sex: data.sex
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return clients;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const clientsData = data.map((item, index) => ({
id: item.id || undefined,
code: item.code
||
null
,
name_en: item.name_en
||
null
,
name_kh: item.name_kh
||
null
,
date_of_birth: item.date_of_birth
||
null
,
phone_number: item.phone_number
||
null
,
is_new: item.is_new
||
false
,
document_number: item.document_number
||
null
,
sex: item.sex
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const clients = await db.clients.bulkCreate(clientsData, { transaction });
return clients;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const clients = await db.clients.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.code !== undefined) updatePayload.code = data.code;
if (data.name_en !== undefined) updatePayload.name_en = data.name_en;
if (data.name_kh !== undefined) updatePayload.name_kh = data.name_kh;
if (data.date_of_birth !== undefined) updatePayload.date_of_birth = data.date_of_birth;
if (data.phone_number !== undefined) updatePayload.phone_number = data.phone_number;
if (data.is_new !== undefined) updatePayload.is_new = data.is_new;
if (data.document_number !== undefined) updatePayload.document_number = data.document_number;
if (data.sex !== undefined) updatePayload.sex = data.sex;
updatePayload.updatedById = currentUser.id;
await clients.update(updatePayload, {transaction});
return clients;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const clients = await db.clients.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of clients) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of clients) {
await record.destroy({transaction});
}
});
return clients;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const clients = await db.clients.findByPk(id, options);
await clients.update({
deletedBy: currentUser.id
}, {
transaction,
});
await clients.destroy({
transaction
});
return clients;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const clients = await db.clients.findOne(
{ where },
{ transaction },
);
if (!clients) {
return clients;
}
const output = clients.get({plain: true});
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
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.code) {
where = {
...where,
[Op.and]: Utils.ilike(
'clients',
'code',
filter.code,
),
};
}
if (filter.name_en) {
where = {
...where,
[Op.and]: Utils.ilike(
'clients',
'name_en',
filter.name_en,
),
};
}
if (filter.name_kh) {
where = {
...where,
[Op.and]: Utils.ilike(
'clients',
'name_kh',
filter.name_kh,
),
};
}
if (filter.phone_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'clients',
'phone_number',
filter.phone_number,
),
};
}
if (filter.document_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'clients',
'document_number',
filter.document_number,
),
};
}
if (filter.date_of_birthRange) {
const [start, end] = filter.date_of_birthRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
date_of_birth: {
...where.date_of_birth,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
date_of_birth: {
...where.date_of_birth,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.is_new) {
where = {
...where,
is_new: filter.is_new,
};
}
if (filter.sex) {
where = {
...where,
sex: filter.sex,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.clients.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'clients',
'name_en',
query,
),
],
};
}
const records = await db.clients.findAll({
attributes: [ 'id', 'name_en' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['name_en', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.name_en,
}));
}
};

View File

@ -0,0 +1,290 @@
const db = require('../models');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class CommunesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const communes = await db.communes.create(
{
id: data.id || undefined,
name_kh: data.name_kh
||
null
,
name_en: data.name_en
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return communes;
}
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 communesData = data.map((item, index) => ({
id: item.id || undefined,
name_kh: item.name_kh
||
null
,
name_en: item.name_en
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const communes = await db.communes.bulkCreate(communesData, { transaction });
return communes;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const communes = await db.communes.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name_kh !== undefined) updatePayload.name_kh = data.name_kh;
if (data.name_en !== undefined) updatePayload.name_en = data.name_en;
updatePayload.updatedById = currentUser.id;
await communes.update(updatePayload, {transaction});
return communes;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const communes = await db.communes.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of communes) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of communes) {
await record.destroy({transaction});
}
});
return communes;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const communes = await db.communes.findByPk(id, options);
await communes.update({
deletedBy: currentUser.id
}, {
transaction,
});
await communes.destroy({
transaction
});
return communes;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const communes = await db.communes.findOne(
{ where },
{ transaction },
);
if (!communes) {
return communes;
}
const output = communes.get({plain: true});
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
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_kh) {
where = {
...where,
[Op.and]: Utils.ilike(
'communes',
'name_kh',
filter.name_kh,
),
};
}
if (filter.name_en) {
where = {
...where,
[Op.and]: Utils.ilike(
'communes',
'name_en',
filter.name_en,
),
};
}
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.communes.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(
'communes',
'name_en',
query,
),
],
};
}
const records = await db.communes.findAll({
attributes: [ 'id', 'name_en' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['name_en', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.name_en,
}));
}
};

View File

@ -0,0 +1,316 @@
const db = require('../models');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class DepositsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const deposits = await db.deposits.create(
{
id: data.id || undefined,
deposit_datetime: data.deposit_datetime
||
null
,
deposit_amount: data.deposit_amount
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return deposits;
}
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 depositsData = data.map((item, index) => ({
id: item.id || undefined,
deposit_datetime: item.deposit_datetime
||
null
,
deposit_amount: item.deposit_amount
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const deposits = await db.deposits.bulkCreate(depositsData, { transaction });
return deposits;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const deposits = await db.deposits.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.deposit_datetime !== undefined) updatePayload.deposit_datetime = data.deposit_datetime;
if (data.deposit_amount !== undefined) updatePayload.deposit_amount = data.deposit_amount;
updatePayload.updatedById = currentUser.id;
await deposits.update(updatePayload, {transaction});
return deposits;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const deposits = await db.deposits.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of deposits) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of deposits) {
await record.destroy({transaction});
}
});
return deposits;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const deposits = await db.deposits.findByPk(id, options);
await deposits.update({
deletedBy: currentUser.id
}, {
transaction,
});
await deposits.destroy({
transaction
});
return deposits;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const deposits = await db.deposits.findOne(
{ where },
{ transaction },
);
if (!deposits) {
return deposits;
}
const output = deposits.get({plain: true});
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
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.deposit_datetimeRange) {
const [start, end] = filter.deposit_datetimeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
deposit_datetime: {
...where.deposit_datetime,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
deposit_datetime: {
...where.deposit_datetime,
[Op.lte]: end,
},
};
}
}
if (filter.deposit_amountRange) {
const [start, end] = filter.deposit_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
deposit_amount: {
...where.deposit_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
deposit_amount: {
...where.deposit_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.deposits.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(
'deposits',
'deposit_amount',
query,
),
],
};
}
const records = await db.deposits.findAll({
attributes: [ 'id', 'deposit_amount' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['deposit_amount', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.deposit_amount,
}));
}
};

View File

@ -0,0 +1,290 @@
const db = require('../models');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class DistrictsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const districts = await db.districts.create(
{
id: data.id || undefined,
name_kh: data.name_kh
||
null
,
name_en: data.name_en
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return districts;
}
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 districtsData = data.map((item, index) => ({
id: item.id || undefined,
name_kh: item.name_kh
||
null
,
name_en: item.name_en
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const districts = await db.districts.bulkCreate(districtsData, { transaction });
return districts;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const districts = await db.districts.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name_kh !== undefined) updatePayload.name_kh = data.name_kh;
if (data.name_en !== undefined) updatePayload.name_en = data.name_en;
updatePayload.updatedById = currentUser.id;
await districts.update(updatePayload, {transaction});
return districts;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const districts = await db.districts.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of districts) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of districts) {
await record.destroy({transaction});
}
});
return districts;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const districts = await db.districts.findByPk(id, options);
await districts.update({
deletedBy: currentUser.id
}, {
transaction,
});
await districts.destroy({
transaction
});
return districts;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const districts = await db.districts.findOne(
{ where },
{ transaction },
);
if (!districts) {
return districts;
}
const output = districts.get({plain: true});
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
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_kh) {
where = {
...where,
[Op.and]: Utils.ilike(
'districts',
'name_kh',
filter.name_kh,
),
};
}
if (filter.name_en) {
where = {
...where,
[Op.and]: Utils.ilike(
'districts',
'name_en',
filter.name_en,
),
};
}
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.districts.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(
'districts',
'name_en',
query,
),
],
};
}
const records = await db.districts.findAll({
attributes: [ 'id', 'name_en' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['name_en', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.name_en,
}));
}
};

View File

@ -0,0 +1,267 @@
const db = require('../models');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Document_typeDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const document_type = await db.document_type.create(
{
id: data.id || undefined,
name: data.name
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return document_type;
}
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 document_typeData = 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 document_type = await db.document_type.bulkCreate(document_typeData, { transaction });
return document_type;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const document_type = await db.document_type.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
updatePayload.updatedById = currentUser.id;
await document_type.update(updatePayload, {transaction});
return document_type;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const document_type = await db.document_type.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of document_type) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of document_type) {
await record.destroy({transaction});
}
});
return document_type;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const document_type = await db.document_type.findByPk(id, options);
await document_type.update({
deletedBy: currentUser.id
}, {
transaction,
});
await document_type.destroy({
transaction
});
return document_type;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const document_type = await db.document_type.findOne(
{ where },
{ transaction },
);
if (!document_type) {
return document_type;
}
const output = document_type.get({plain: true});
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
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(
'document_type',
'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.document_type.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(
'document_type',
'name',
query,
),
],
};
}
const records = await db.document_type.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,339 @@
const db = require('../models');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Expense_itemsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const expense_items = await db.expense_items.create(
{
id: data.id || undefined,
expense_datetime: data.expense_datetime
||
null
,
description: data.description
||
null
,
expense_amount: data.expense_amount
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return expense_items;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const expense_itemsData = data.map((item, index) => ({
id: item.id || undefined,
expense_datetime: item.expense_datetime
||
null
,
description: item.description
||
null
,
expense_amount: item.expense_amount
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const expense_items = await db.expense_items.bulkCreate(expense_itemsData, { transaction });
return expense_items;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const expense_items = await db.expense_items.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.expense_datetime !== undefined) updatePayload.expense_datetime = data.expense_datetime;
if (data.description !== undefined) updatePayload.description = data.description;
if (data.expense_amount !== undefined) updatePayload.expense_amount = data.expense_amount;
updatePayload.updatedById = currentUser.id;
await expense_items.update(updatePayload, {transaction});
return expense_items;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const expense_items = await db.expense_items.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of expense_items) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of expense_items) {
await record.destroy({transaction});
}
});
return expense_items;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const expense_items = await db.expense_items.findByPk(id, options);
await expense_items.update({
deletedBy: currentUser.id
}, {
transaction,
});
await expense_items.destroy({
transaction
});
return expense_items;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const expense_items = await db.expense_items.findOne(
{ where },
{ transaction },
);
if (!expense_items) {
return expense_items;
}
const output = expense_items.get({plain: true});
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.description) {
where = {
...where,
[Op.and]: Utils.ilike(
'expense_items',
'description',
filter.description,
),
};
}
if (filter.expense_datetimeRange) {
const [start, end] = filter.expense_datetimeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
expense_datetime: {
...where.expense_datetime,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
expense_datetime: {
...where.expense_datetime,
[Op.lte]: end,
},
};
}
}
if (filter.expense_amountRange) {
const [start, end] = filter.expense_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
expense_amount: {
...where.expense_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
expense_amount: {
...where.expense_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.expense_items.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'expense_items',
'description',
query,
),
],
};
}
const records = await db.expense_items.findAll({
attributes: [ 'id', 'description' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['description', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.description,
}));
}
};

View File

@ -0,0 +1,290 @@
const db = require('../models');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Expense_typesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const expense_types = await db.expense_types.create(
{
id: data.id || undefined,
name_kh: data.name_kh
||
null
,
name_en: data.name_en
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return expense_types;
}
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 expense_typesData = data.map((item, index) => ({
id: item.id || undefined,
name_kh: item.name_kh
||
null
,
name_en: item.name_en
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const expense_types = await db.expense_types.bulkCreate(expense_typesData, { transaction });
return expense_types;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const expense_types = await db.expense_types.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name_kh !== undefined) updatePayload.name_kh = data.name_kh;
if (data.name_en !== undefined) updatePayload.name_en = data.name_en;
updatePayload.updatedById = currentUser.id;
await expense_types.update(updatePayload, {transaction});
return expense_types;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const expense_types = await db.expense_types.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of expense_types) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of expense_types) {
await record.destroy({transaction});
}
});
return expense_types;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const expense_types = await db.expense_types.findByPk(id, options);
await expense_types.update({
deletedBy: currentUser.id
}, {
transaction,
});
await expense_types.destroy({
transaction
});
return expense_types;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const expense_types = await db.expense_types.findOne(
{ where },
{ transaction },
);
if (!expense_types) {
return expense_types;
}
const output = expense_types.get({plain: true});
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
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_kh) {
where = {
...where,
[Op.and]: Utils.ilike(
'expense_types',
'name_kh',
filter.name_kh,
),
};
}
if (filter.name_en) {
where = {
...where,
[Op.and]: Utils.ilike(
'expense_types',
'name_en',
filter.name_en,
),
};
}
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.expense_types.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(
'expense_types',
'name_en',
query,
),
],
};
}
const records = await db.expense_types.findAll({
attributes: [ 'id', 'name_en' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['name_en', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.name_en,
}));
}
};

View File

@ -0,0 +1,288 @@
const db = require('../models');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Group_menusDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const group_menus = await db.group_menus.create(
{
id: data.id || undefined,
name: data.name
||
null
,
is_admin: data.is_admin
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return group_menus;
}
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 group_menusData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
is_admin: item.is_admin
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const group_menus = await db.group_menus.bulkCreate(group_menusData, { transaction });
return group_menus;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const group_menus = await db.group_menus.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.is_admin !== undefined) updatePayload.is_admin = data.is_admin;
updatePayload.updatedById = currentUser.id;
await group_menus.update(updatePayload, {transaction});
return group_menus;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const group_menus = await db.group_menus.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of group_menus) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of group_menus) {
await record.destroy({transaction});
}
});
return group_menus;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const group_menus = await db.group_menus.findByPk(id, options);
await group_menus.update({
deletedBy: currentUser.id
}, {
transaction,
});
await group_menus.destroy({
transaction
});
return group_menus;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const group_menus = await db.group_menus.findOne(
{ where },
{ transaction },
);
if (!group_menus) {
return group_menus;
}
const output = group_menus.get({plain: true});
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
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(
'group_menus',
'name',
filter.name,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.is_admin) {
where = {
...where,
is_admin: filter.is_admin,
};
}
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.group_menus.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(
'group_menus',
'name',
query,
),
],
};
}
const records = await db.group_menus.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 crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class GuarantorDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const guarantor = await db.guarantor.create(
{
id: data.id || undefined,
full_name: data.full_name
||
null
,
sex: data.sex
||
null
,
date_of_birth: data.date_of_birth
||
null
,
document_type: data.document_type
||
null
,
document_number: data.document_number
||
null
,
phone_number: data.phone_number
||
null
,
full_address_input: data.full_address_input
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return guarantor;
}
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 guarantorData = data.map((item, index) => ({
id: item.id || undefined,
full_name: item.full_name
||
null
,
sex: item.sex
||
null
,
date_of_birth: item.date_of_birth
||
null
,
document_type: item.document_type
||
null
,
document_number: item.document_number
||
null
,
phone_number: item.phone_number
||
null
,
full_address_input: item.full_address_input
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const guarantor = await db.guarantor.bulkCreate(guarantorData, { transaction });
return guarantor;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const guarantor = await db.guarantor.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.full_name !== undefined) updatePayload.full_name = data.full_name;
if (data.sex !== undefined) updatePayload.sex = data.sex;
if (data.date_of_birth !== undefined) updatePayload.date_of_birth = data.date_of_birth;
if (data.document_type !== undefined) updatePayload.document_type = data.document_type;
if (data.document_number !== undefined) updatePayload.document_number = data.document_number;
if (data.phone_number !== undefined) updatePayload.phone_number = data.phone_number;
if (data.full_address_input !== undefined) updatePayload.full_address_input = data.full_address_input;
updatePayload.updatedById = currentUser.id;
await guarantor.update(updatePayload, {transaction});
return guarantor;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const guarantor = await db.guarantor.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of guarantor) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of guarantor) {
await record.destroy({transaction});
}
});
return guarantor;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const guarantor = await db.guarantor.findByPk(id, options);
await guarantor.update({
deletedBy: currentUser.id
}, {
transaction,
});
await guarantor.destroy({
transaction
});
return guarantor;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const guarantor = await db.guarantor.findOne(
{ where },
{ transaction },
);
if (!guarantor) {
return guarantor;
}
const output = guarantor.get({plain: true});
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
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.full_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'guarantor',
'full_name',
filter.full_name,
),
};
}
if (filter.document_type) {
where = {
...where,
[Op.and]: Utils.ilike(
'guarantor',
'document_type',
filter.document_type,
),
};
}
if (filter.document_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'guarantor',
'document_number',
filter.document_number,
),
};
}
if (filter.phone_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'guarantor',
'phone_number',
filter.phone_number,
),
};
}
if (filter.full_address_input) {
where = {
...where,
[Op.and]: Utils.ilike(
'guarantor',
'full_address_input',
filter.full_address_input,
),
};
}
if (filter.date_of_birthRange) {
const [start, end] = filter.date_of_birthRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
date_of_birth: {
...where.date_of_birth,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
date_of_birth: {
...where.date_of_birth,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.sex) {
where = {
...where,
sex: filter.sex,
};
}
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.guarantor.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(
'guarantor',
'full_name',
query,
),
],
};
}
const records = await db.guarantor.findAll({
attributes: [ 'id', 'full_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['full_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.full_name,
}));
}
};

View File

@ -0,0 +1,480 @@
const db = require('../models');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Interest_ratesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const interest_rates = await db.interest_rates.create(
{
id: data.id || undefined,
code: data.code
||
null
,
name: data.name
||
null
,
rate: data.rate
||
null
,
commission_rate: data.commission_rate
||
null
,
interval: data.interval
||
null
,
sort: data.sort
||
null
,
css: data.css
||
null
,
setting: data.setting
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return interest_rates;
}
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 interest_ratesData = data.map((item, index) => ({
id: item.id || undefined,
code: item.code
||
null
,
name: item.name
||
null
,
rate: item.rate
||
null
,
commission_rate: item.commission_rate
||
null
,
interval: item.interval
||
null
,
sort: item.sort
||
null
,
css: item.css
||
null
,
setting: item.setting
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const interest_rates = await db.interest_rates.bulkCreate(interest_ratesData, { transaction });
return interest_rates;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const interest_rates = await db.interest_rates.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.code !== undefined) updatePayload.code = data.code;
if (data.name !== undefined) updatePayload.name = data.name;
if (data.rate !== undefined) updatePayload.rate = data.rate;
if (data.commission_rate !== undefined) updatePayload.commission_rate = data.commission_rate;
if (data.interval !== undefined) updatePayload.interval = data.interval;
if (data.sort !== undefined) updatePayload.sort = data.sort;
if (data.css !== undefined) updatePayload.css = data.css;
if (data.setting !== undefined) updatePayload.setting = data.setting;
updatePayload.updatedById = currentUser.id;
await interest_rates.update(updatePayload, {transaction});
return interest_rates;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const interest_rates = await db.interest_rates.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of interest_rates) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of interest_rates) {
await record.destroy({transaction});
}
});
return interest_rates;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const interest_rates = await db.interest_rates.findByPk(id, options);
await interest_rates.update({
deletedBy: currentUser.id
}, {
transaction,
});
await interest_rates.destroy({
transaction
});
return interest_rates;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const interest_rates = await db.interest_rates.findOne(
{ where },
{ transaction },
);
if (!interest_rates) {
return interest_rates;
}
const output = interest_rates.get({plain: true});
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
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.code) {
where = {
...where,
[Op.and]: Utils.ilike(
'interest_rates',
'code',
filter.code,
),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'interest_rates',
'name',
filter.name,
),
};
}
if (filter.css) {
where = {
...where,
[Op.and]: Utils.ilike(
'interest_rates',
'css',
filter.css,
),
};
}
if (filter.setting) {
where = {
...where,
[Op.and]: Utils.ilike(
'interest_rates',
'setting',
filter.setting,
),
};
}
if (filter.rateRange) {
const [start, end] = filter.rateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
rate: {
...where.rate,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
rate: {
...where.rate,
[Op.lte]: end,
},
};
}
}
if (filter.commission_rateRange) {
const [start, end] = filter.commission_rateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
commission_rate: {
...where.commission_rate,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
commission_rate: {
...where.commission_rate,
[Op.lte]: end,
},
};
}
}
if (filter.intervalRange) {
const [start, end] = filter.intervalRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
interval: {
...where.interval,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
interval: {
...where.interval,
[Op.lte]: end,
},
};
}
}
if (filter.sortRange) {
const [start, end] = filter.sortRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sort: {
...where.sort,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sort: {
...where.sort,
[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.interest_rates.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(
'interest_rates',
'name',
query,
),
],
};
}
const records = await db.interest_rates.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,290 @@
const db = require('../models');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Loan_statusDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const loan_status = await db.loan_status.create(
{
id: data.id || undefined,
name: data.name
||
null
,
css: data.css
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return loan_status;
}
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 loan_statusData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
css: item.css
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const loan_status = await db.loan_status.bulkCreate(loan_statusData, { transaction });
return loan_status;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const loan_status = await db.loan_status.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.css !== undefined) updatePayload.css = data.css;
updatePayload.updatedById = currentUser.id;
await loan_status.update(updatePayload, {transaction});
return loan_status;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const loan_status = await db.loan_status.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of loan_status) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of loan_status) {
await record.destroy({transaction});
}
});
return loan_status;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const loan_status = await db.loan_status.findByPk(id, options);
await loan_status.update({
deletedBy: currentUser.id
}, {
transaction,
});
await loan_status.destroy({
transaction
});
return loan_status;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const loan_status = await db.loan_status.findOne(
{ where },
{ transaction },
);
if (!loan_status) {
return loan_status;
}
const output = loan_status.get({plain: true});
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
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(
'loan_status',
'name',
filter.name,
),
};
}
if (filter.css) {
where = {
...where,
[Op.and]: Utils.ilike(
'loan_status',
'css',
filter.css,
),
};
}
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.loan_status.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(
'loan_status',
'name',
query,
),
],
};
}
const records = await db.loan_status.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,290 @@
const db = require('../models');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Loan_typesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const loan_types = await db.loan_types.create(
{
id: data.id || undefined,
name_kh: data.name_kh
||
null
,
name_en: data.name_en
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return loan_types;
}
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 loan_typesData = data.map((item, index) => ({
id: item.id || undefined,
name_kh: item.name_kh
||
null
,
name_en: item.name_en
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const loan_types = await db.loan_types.bulkCreate(loan_typesData, { transaction });
return loan_types;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const loan_types = await db.loan_types.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name_kh !== undefined) updatePayload.name_kh = data.name_kh;
if (data.name_en !== undefined) updatePayload.name_en = data.name_en;
updatePayload.updatedById = currentUser.id;
await loan_types.update(updatePayload, {transaction});
return loan_types;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const loan_types = await db.loan_types.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of loan_types) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of loan_types) {
await record.destroy({transaction});
}
});
return loan_types;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const loan_types = await db.loan_types.findByPk(id, options);
await loan_types.update({
deletedBy: currentUser.id
}, {
transaction,
});
await loan_types.destroy({
transaction
});
return loan_types;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const loan_types = await db.loan_types.findOne(
{ where },
{ transaction },
);
if (!loan_types) {
return loan_types;
}
const output = loan_types.get({plain: true});
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
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_kh) {
where = {
...where,
[Op.and]: Utils.ilike(
'loan_types',
'name_kh',
filter.name_kh,
),
};
}
if (filter.name_en) {
where = {
...where,
[Op.and]: Utils.ilike(
'loan_types',
'name_en',
filter.name_en,
),
};
}
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.loan_types.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(
'loan_types',
'name_en',
query,
),
],
};
}
const records = await db.loan_types.findAll({
attributes: [ 'id', 'name_en' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['name_en', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.name_en,
}));
}
};

794
backend/src/db/api/loans.js Normal file
View File

@ -0,0 +1,794 @@
const db = require('../models');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class LoansDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const loans = await db.loans.create(
{
id: data.id || undefined,
code: data.code
||
null
,
principal_amount: data.principal_amount
||
null
,
term: data.term
||
null
,
pending_amount: data.pending_amount
||
null
,
last_pending_amount: data.last_pending_amount
||
null
,
rate: data.rate
||
null
,
commission_rate: data.commission_rate
||
null
,
registration_date: data.registration_date
||
null
,
started_payment_date: data.started_payment_date
||
null
,
last_payment_date: data.last_payment_date
||
null
,
finish_payment_date: data.finish_payment_date
||
null
,
finish_discount: data.finish_discount
||
null
,
finish_discount_amount: data.finish_discount_amount
||
null
,
admin_rate: data.admin_rate
||
null
,
admin_amount: data.admin_amount
||
null
,
purpose: data.purpose
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return loans;
}
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 loansData = data.map((item, index) => ({
id: item.id || undefined,
code: item.code
||
null
,
principal_amount: item.principal_amount
||
null
,
term: item.term
||
null
,
pending_amount: item.pending_amount
||
null
,
last_pending_amount: item.last_pending_amount
||
null
,
rate: item.rate
||
null
,
commission_rate: item.commission_rate
||
null
,
registration_date: item.registration_date
||
null
,
started_payment_date: item.started_payment_date
||
null
,
last_payment_date: item.last_payment_date
||
null
,
finish_payment_date: item.finish_payment_date
||
null
,
finish_discount: item.finish_discount
||
null
,
finish_discount_amount: item.finish_discount_amount
||
null
,
admin_rate: item.admin_rate
||
null
,
admin_amount: item.admin_amount
||
null
,
purpose: item.purpose
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const loans = await db.loans.bulkCreate(loansData, { transaction });
return loans;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const loans = await db.loans.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.code !== undefined) updatePayload.code = data.code;
if (data.principal_amount !== undefined) updatePayload.principal_amount = data.principal_amount;
if (data.term !== undefined) updatePayload.term = data.term;
if (data.pending_amount !== undefined) updatePayload.pending_amount = data.pending_amount;
if (data.last_pending_amount !== undefined) updatePayload.last_pending_amount = data.last_pending_amount;
if (data.rate !== undefined) updatePayload.rate = data.rate;
if (data.commission_rate !== undefined) updatePayload.commission_rate = data.commission_rate;
if (data.registration_date !== undefined) updatePayload.registration_date = data.registration_date;
if (data.started_payment_date !== undefined) updatePayload.started_payment_date = data.started_payment_date;
if (data.last_payment_date !== undefined) updatePayload.last_payment_date = data.last_payment_date;
if (data.finish_payment_date !== undefined) updatePayload.finish_payment_date = data.finish_payment_date;
if (data.finish_discount !== undefined) updatePayload.finish_discount = data.finish_discount;
if (data.finish_discount_amount !== undefined) updatePayload.finish_discount_amount = data.finish_discount_amount;
if (data.admin_rate !== undefined) updatePayload.admin_rate = data.admin_rate;
if (data.admin_amount !== undefined) updatePayload.admin_amount = data.admin_amount;
if (data.purpose !== undefined) updatePayload.purpose = data.purpose;
updatePayload.updatedById = currentUser.id;
await loans.update(updatePayload, {transaction});
return loans;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const loans = await db.loans.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of loans) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of loans) {
await record.destroy({transaction});
}
});
return loans;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const loans = await db.loans.findByPk(id, options);
await loans.update({
deletedBy: currentUser.id
}, {
transaction,
});
await loans.destroy({
transaction
});
return loans;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const loans = await db.loans.findOne(
{ where },
{ transaction },
);
if (!loans) {
return loans;
}
const output = loans.get({plain: true});
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
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.code) {
where = {
...where,
[Op.and]: Utils.ilike(
'loans',
'code',
filter.code,
),
};
}
if (filter.purpose) {
where = {
...where,
[Op.and]: Utils.ilike(
'loans',
'purpose',
filter.purpose,
),
};
}
if (filter.principal_amountRange) {
const [start, end] = filter.principal_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
principal_amount: {
...where.principal_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
principal_amount: {
...where.principal_amount,
[Op.lte]: end,
},
};
}
}
if (filter.termRange) {
const [start, end] = filter.termRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
term: {
...where.term,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
term: {
...where.term,
[Op.lte]: end,
},
};
}
}
if (filter.pending_amountRange) {
const [start, end] = filter.pending_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
pending_amount: {
...where.pending_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
pending_amount: {
...where.pending_amount,
[Op.lte]: end,
},
};
}
}
if (filter.last_pending_amountRange) {
const [start, end] = filter.last_pending_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
last_pending_amount: {
...where.last_pending_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
last_pending_amount: {
...where.last_pending_amount,
[Op.lte]: end,
},
};
}
}
if (filter.rateRange) {
const [start, end] = filter.rateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
rate: {
...where.rate,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
rate: {
...where.rate,
[Op.lte]: end,
},
};
}
}
if (filter.commission_rateRange) {
const [start, end] = filter.commission_rateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
commission_rate: {
...where.commission_rate,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
commission_rate: {
...where.commission_rate,
[Op.lte]: end,
},
};
}
}
if (filter.registration_dateRange) {
const [start, end] = filter.registration_dateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
registration_date: {
...where.registration_date,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
registration_date: {
...where.registration_date,
[Op.lte]: end,
},
};
}
}
if (filter.started_payment_dateRange) {
const [start, end] = filter.started_payment_dateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
started_payment_date: {
...where.started_payment_date,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
started_payment_date: {
...where.started_payment_date,
[Op.lte]: end,
},
};
}
}
if (filter.last_payment_dateRange) {
const [start, end] = filter.last_payment_dateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
last_payment_date: {
...where.last_payment_date,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
last_payment_date: {
...where.last_payment_date,
[Op.lte]: end,
},
};
}
}
if (filter.finish_payment_dateRange) {
const [start, end] = filter.finish_payment_dateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
finish_payment_date: {
...where.finish_payment_date,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
finish_payment_date: {
...where.finish_payment_date,
[Op.lte]: end,
},
};
}
}
if (filter.finish_discountRange) {
const [start, end] = filter.finish_discountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
finish_discount: {
...where.finish_discount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
finish_discount: {
...where.finish_discount,
[Op.lte]: end,
},
};
}
}
if (filter.finish_discount_amountRange) {
const [start, end] = filter.finish_discount_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
finish_discount_amount: {
...where.finish_discount_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
finish_discount_amount: {
...where.finish_discount_amount,
[Op.lte]: end,
},
};
}
}
if (filter.admin_rateRange) {
const [start, end] = filter.admin_rateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
admin_rate: {
...where.admin_rate,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
admin_rate: {
...where.admin_rate,
[Op.lte]: end,
},
};
}
}
if (filter.admin_amountRange) {
const [start, end] = filter.admin_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
admin_amount: {
...where.admin_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
admin_amount: {
...where.admin_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.loans.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(
'loans',
'code',
query,
),
],
};
}
const records = await db.loans.findAll({
attributes: [ 'id', 'code' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['code', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.code,
}));
}
};

View File

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

359
backend/src/db/api/menus.js Normal file
View File

@ -0,0 +1,359 @@
const db = require('../models');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class MenusDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const menus = await db.menus.create(
{
id: data.id || undefined,
label: data.label
||
null
,
url: data.url
||
null
,
active_url: data.active_url
||
null
,
permission: data.permission
||
null
,
icon: data.icon
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return menus;
}
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 menusData = data.map((item, index) => ({
id: item.id || undefined,
label: item.label
||
null
,
url: item.url
||
null
,
active_url: item.active_url
||
null
,
permission: item.permission
||
null
,
icon: item.icon
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const menus = await db.menus.bulkCreate(menusData, { transaction });
return menus;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const menus = await db.menus.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.label !== undefined) updatePayload.label = data.label;
if (data.url !== undefined) updatePayload.url = data.url;
if (data.active_url !== undefined) updatePayload.active_url = data.active_url;
if (data.permission !== undefined) updatePayload.permission = data.permission;
if (data.icon !== undefined) updatePayload.icon = data.icon;
updatePayload.updatedById = currentUser.id;
await menus.update(updatePayload, {transaction});
return menus;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const menus = await db.menus.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of menus) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of menus) {
await record.destroy({transaction});
}
});
return menus;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const menus = await db.menus.findByPk(id, options);
await menus.update({
deletedBy: currentUser.id
}, {
transaction,
});
await menus.destroy({
transaction
});
return menus;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const menus = await db.menus.findOne(
{ where },
{ transaction },
);
if (!menus) {
return menus;
}
const output = menus.get({plain: true});
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
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(
'menus',
'label',
filter.label,
),
};
}
if (filter.url) {
where = {
...where,
[Op.and]: Utils.ilike(
'menus',
'url',
filter.url,
),
};
}
if (filter.active_url) {
where = {
...where,
[Op.and]: Utils.ilike(
'menus',
'active_url',
filter.active_url,
),
};
}
if (filter.permission) {
where = {
...where,
[Op.and]: Utils.ilike(
'menus',
'permission',
filter.permission,
),
};
}
if (filter.icon) {
where = {
...where,
[Op.and]: Utils.ilike(
'menus',
'icon',
filter.icon,
),
};
}
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.menus.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(
'menus',
'label',
query,
),
],
};
}
const records = await db.menus.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,460 @@
const db = require('../models');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Payment_revenuesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const payment_revenues = await db.payment_revenues.create(
{
id: data.id || undefined,
transaction_date: data.transaction_date
||
null
,
admin_fee_amount: data.admin_fee_amount
||
null
,
interest_amount: data.interest_amount
||
null
,
commission_amount: data.commission_amount
||
null
,
expense_amount: data.expense_amount
||
null
,
setlement_datetime: data.setlement_datetime
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return payment_revenues;
}
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_revenuesData = data.map((item, index) => ({
id: item.id || undefined,
transaction_date: item.transaction_date
||
null
,
admin_fee_amount: item.admin_fee_amount
||
null
,
interest_amount: item.interest_amount
||
null
,
commission_amount: item.commission_amount
||
null
,
expense_amount: item.expense_amount
||
null
,
setlement_datetime: item.setlement_datetime
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const payment_revenues = await db.payment_revenues.bulkCreate(payment_revenuesData, { transaction });
return payment_revenues;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const payment_revenues = await db.payment_revenues.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.transaction_date !== undefined) updatePayload.transaction_date = data.transaction_date;
if (data.admin_fee_amount !== undefined) updatePayload.admin_fee_amount = data.admin_fee_amount;
if (data.interest_amount !== undefined) updatePayload.interest_amount = data.interest_amount;
if (data.commission_amount !== undefined) updatePayload.commission_amount = data.commission_amount;
if (data.expense_amount !== undefined) updatePayload.expense_amount = data.expense_amount;
if (data.setlement_datetime !== undefined) updatePayload.setlement_datetime = data.setlement_datetime;
updatePayload.updatedById = currentUser.id;
await payment_revenues.update(updatePayload, {transaction});
return payment_revenues;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const payment_revenues = await db.payment_revenues.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of payment_revenues) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of payment_revenues) {
await record.destroy({transaction});
}
});
return payment_revenues;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const payment_revenues = await db.payment_revenues.findByPk(id, options);
await payment_revenues.update({
deletedBy: currentUser.id
}, {
transaction,
});
await payment_revenues.destroy({
transaction
});
return payment_revenues;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const payment_revenues = await db.payment_revenues.findOne(
{ where },
{ transaction },
);
if (!payment_revenues) {
return payment_revenues;
}
const output = payment_revenues.get({plain: true});
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
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.transaction_dateRange) {
const [start, end] = filter.transaction_dateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
transaction_date: {
...where.transaction_date,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
transaction_date: {
...where.transaction_date,
[Op.lte]: end,
},
};
}
}
if (filter.admin_fee_amountRange) {
const [start, end] = filter.admin_fee_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
admin_fee_amount: {
...where.admin_fee_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
admin_fee_amount: {
...where.admin_fee_amount,
[Op.lte]: end,
},
};
}
}
if (filter.interest_amountRange) {
const [start, end] = filter.interest_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
interest_amount: {
...where.interest_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
interest_amount: {
...where.interest_amount,
[Op.lte]: end,
},
};
}
}
if (filter.commission_amountRange) {
const [start, end] = filter.commission_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
commission_amount: {
...where.commission_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
commission_amount: {
...where.commission_amount,
[Op.lte]: end,
},
};
}
}
if (filter.expense_amountRange) {
const [start, end] = filter.expense_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
expense_amount: {
...where.expense_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
expense_amount: {
...where.expense_amount,
[Op.lte]: end,
},
};
}
}
if (filter.setlement_datetimeRange) {
const [start, end] = filter.setlement_datetimeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
setlement_datetime: {
...where.setlement_datetime,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
setlement_datetime: {
...where.setlement_datetime,
[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_revenues.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_revenues',
'transaction_date',
query,
),
],
};
}
const records = await db.payment_revenues.findAll({
attributes: [ 'id', 'transaction_date' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['transaction_date', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.transaction_date,
}));
}
};

View File

@ -0,0 +1,311 @@
const db = require('../models');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Payment_statusDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const payment_status = await db.payment_status.create(
{
id: data.id || undefined,
name: data.name
||
null
,
css: data.css
||
null
,
visible: data.visible
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return payment_status;
}
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_statusData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
css: item.css
||
null
,
visible: item.visible
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const payment_status = await db.payment_status.bulkCreate(payment_statusData, { transaction });
return payment_status;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const payment_status = await db.payment_status.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.css !== undefined) updatePayload.css = data.css;
if (data.visible !== undefined) updatePayload.visible = data.visible;
updatePayload.updatedById = currentUser.id;
await payment_status.update(updatePayload, {transaction});
return payment_status;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const payment_status = await db.payment_status.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of payment_status) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of payment_status) {
await record.destroy({transaction});
}
});
return payment_status;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const payment_status = await db.payment_status.findByPk(id, options);
await payment_status.update({
deletedBy: currentUser.id
}, {
transaction,
});
await payment_status.destroy({
transaction
});
return payment_status;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const payment_status = await db.payment_status.findOne(
{ where },
{ transaction },
);
if (!payment_status) {
return payment_status;
}
const output = payment_status.get({plain: true});
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
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(
'payment_status',
'name',
filter.name,
),
};
}
if (filter.css) {
where = {
...where,
[Op.and]: Utils.ilike(
'payment_status',
'css',
filter.css,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.visible) {
where = {
...where,
visible: filter.visible,
};
}
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_status.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_status',
'name',
query,
),
],
};
}
const records = await db.payment_status.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,515 @@
const db = require('../models');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Payment_transactionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const payment_transactions = await db.payment_transactions.create(
{
id: data.id || undefined,
transaction_datetime: data.transaction_datetime
||
null
,
transaction_amount: data.transaction_amount
||
null
,
deduct_amount: data.deduct_amount
||
null
,
interest_amount: data.interest_amount
||
null
,
commission_amount: data.commission_amount
||
null
,
revenue_amount: data.revenue_amount
||
null
,
setlement_datetime: data.setlement_datetime
||
null
,
type: data.type
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return payment_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 payment_transactionsData = data.map((item, index) => ({
id: item.id || undefined,
transaction_datetime: item.transaction_datetime
||
null
,
transaction_amount: item.transaction_amount
||
null
,
deduct_amount: item.deduct_amount
||
null
,
interest_amount: item.interest_amount
||
null
,
commission_amount: item.commission_amount
||
null
,
revenue_amount: item.revenue_amount
||
null
,
setlement_datetime: item.setlement_datetime
||
null
,
type: item.type
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const payment_transactions = await db.payment_transactions.bulkCreate(payment_transactionsData, { transaction });
return payment_transactions;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const payment_transactions = await db.payment_transactions.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.transaction_datetime !== undefined) updatePayload.transaction_datetime = data.transaction_datetime;
if (data.transaction_amount !== undefined) updatePayload.transaction_amount = data.transaction_amount;
if (data.deduct_amount !== undefined) updatePayload.deduct_amount = data.deduct_amount;
if (data.interest_amount !== undefined) updatePayload.interest_amount = data.interest_amount;
if (data.commission_amount !== undefined) updatePayload.commission_amount = data.commission_amount;
if (data.revenue_amount !== undefined) updatePayload.revenue_amount = data.revenue_amount;
if (data.setlement_datetime !== undefined) updatePayload.setlement_datetime = data.setlement_datetime;
if (data.type !== undefined) updatePayload.type = data.type;
updatePayload.updatedById = currentUser.id;
await payment_transactions.update(updatePayload, {transaction});
return payment_transactions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const payment_transactions = await db.payment_transactions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of payment_transactions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of payment_transactions) {
await record.destroy({transaction});
}
});
return payment_transactions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const payment_transactions = await db.payment_transactions.findByPk(id, options);
await payment_transactions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await payment_transactions.destroy({
transaction
});
return payment_transactions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const payment_transactions = await db.payment_transactions.findOne(
{ where },
{ transaction },
);
if (!payment_transactions) {
return payment_transactions;
}
const output = payment_transactions.get({plain: true});
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
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.transaction_datetimeRange) {
const [start, end] = filter.transaction_datetimeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
transaction_datetime: {
...where.transaction_datetime,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
transaction_datetime: {
...where.transaction_datetime,
[Op.lte]: end,
},
};
}
}
if (filter.transaction_amountRange) {
const [start, end] = filter.transaction_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
transaction_amount: {
...where.transaction_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
transaction_amount: {
...where.transaction_amount,
[Op.lte]: end,
},
};
}
}
if (filter.deduct_amountRange) {
const [start, end] = filter.deduct_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
deduct_amount: {
...where.deduct_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
deduct_amount: {
...where.deduct_amount,
[Op.lte]: end,
},
};
}
}
if (filter.interest_amountRange) {
const [start, end] = filter.interest_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
interest_amount: {
...where.interest_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
interest_amount: {
...where.interest_amount,
[Op.lte]: end,
},
};
}
}
if (filter.commission_amountRange) {
const [start, end] = filter.commission_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
commission_amount: {
...where.commission_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
commission_amount: {
...where.commission_amount,
[Op.lte]: end,
},
};
}
}
if (filter.revenue_amountRange) {
const [start, end] = filter.revenue_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
revenue_amount: {
...where.revenue_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
revenue_amount: {
...where.revenue_amount,
[Op.lte]: end,
},
};
}
}
if (filter.setlement_datetimeRange) {
const [start, end] = filter.setlement_datetimeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
setlement_datetime: {
...where.setlement_datetime,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
setlement_datetime: {
...where.setlement_datetime,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.type) {
where = {
...where,
type: filter.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.payment_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(
'payment_transactions',
'transaction_amount',
query,
),
],
};
}
const records = await db.payment_transactions.findAll({
attributes: [ 'id', 'transaction_amount' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['transaction_amount', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.transaction_amount,
}));
}
};

View File

@ -0,0 +1,771 @@
const db = require('../models');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class PaymentsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const payments = await db.payments.create(
{
id: data.id || undefined,
start_payment_date: data.start_payment_date
||
null
,
payment_date: data.payment_date
||
null
,
last_payment_paid_date: data.last_payment_paid_date
||
null
,
sort: data.sort
||
null
,
deduct_amount: data.deduct_amount
||
null
,
deduct_paid_amount: data.deduct_paid_amount
||
null
,
interval: data.interval
||
null
,
interest_amount: data.interest_amount
||
null
,
commission_amount: data.commission_amount
||
null
,
total_amount: data.total_amount
||
null
,
total_paid_amount: data.total_paid_amount
||
null
,
penalty_amount: data.penalty_amount
||
null
,
pending_amount: data.pending_amount
||
null
,
cross_amount: data.cross_amount
||
null
,
remark: data.remark
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return payments;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const paymentsData = data.map((item, index) => ({
id: item.id || undefined,
start_payment_date: item.start_payment_date
||
null
,
payment_date: item.payment_date
||
null
,
last_payment_paid_date: item.last_payment_paid_date
||
null
,
sort: item.sort
||
null
,
deduct_amount: item.deduct_amount
||
null
,
deduct_paid_amount: item.deduct_paid_amount
||
null
,
interval: item.interval
||
null
,
interest_amount: item.interest_amount
||
null
,
commission_amount: item.commission_amount
||
null
,
total_amount: item.total_amount
||
null
,
total_paid_amount: item.total_paid_amount
||
null
,
penalty_amount: item.penalty_amount
||
null
,
pending_amount: item.pending_amount
||
null
,
cross_amount: item.cross_amount
||
null
,
remark: item.remark
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const payments = await db.payments.bulkCreate(paymentsData, { transaction });
return payments;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const payments = await db.payments.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.start_payment_date !== undefined) updatePayload.start_payment_date = data.start_payment_date;
if (data.payment_date !== undefined) updatePayload.payment_date = data.payment_date;
if (data.last_payment_paid_date !== undefined) updatePayload.last_payment_paid_date = data.last_payment_paid_date;
if (data.sort !== undefined) updatePayload.sort = data.sort;
if (data.deduct_amount !== undefined) updatePayload.deduct_amount = data.deduct_amount;
if (data.deduct_paid_amount !== undefined) updatePayload.deduct_paid_amount = data.deduct_paid_amount;
if (data.interval !== undefined) updatePayload.interval = data.interval;
if (data.interest_amount !== undefined) updatePayload.interest_amount = data.interest_amount;
if (data.commission_amount !== undefined) updatePayload.commission_amount = data.commission_amount;
if (data.total_amount !== undefined) updatePayload.total_amount = data.total_amount;
if (data.total_paid_amount !== undefined) updatePayload.total_paid_amount = data.total_paid_amount;
if (data.penalty_amount !== undefined) updatePayload.penalty_amount = data.penalty_amount;
if (data.pending_amount !== undefined) updatePayload.pending_amount = data.pending_amount;
if (data.cross_amount !== undefined) updatePayload.cross_amount = data.cross_amount;
if (data.remark !== undefined) updatePayload.remark = data.remark;
updatePayload.updatedById = currentUser.id;
await payments.update(updatePayload, {transaction});
return payments;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const payments = await db.payments.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of payments) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of payments) {
await record.destroy({transaction});
}
});
return payments;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const payments = await db.payments.findByPk(id, options);
await payments.update({
deletedBy: currentUser.id
}, {
transaction,
});
await payments.destroy({
transaction
});
return payments;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const payments = await db.payments.findOne(
{ where },
{ transaction },
);
if (!payments) {
return payments;
}
const output = payments.get({plain: true});
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
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.remark) {
where = {
...where,
[Op.and]: Utils.ilike(
'payments',
'remark',
filter.remark,
),
};
}
if (filter.start_payment_dateRange) {
const [start, end] = filter.start_payment_dateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
start_payment_date: {
...where.start_payment_date,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
start_payment_date: {
...where.start_payment_date,
[Op.lte]: end,
},
};
}
}
if (filter.payment_dateRange) {
const [start, end] = filter.payment_dateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
payment_date: {
...where.payment_date,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
payment_date: {
...where.payment_date,
[Op.lte]: end,
},
};
}
}
if (filter.last_payment_paid_dateRange) {
const [start, end] = filter.last_payment_paid_dateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
last_payment_paid_date: {
...where.last_payment_paid_date,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
last_payment_paid_date: {
...where.last_payment_paid_date,
[Op.lte]: end,
},
};
}
}
if (filter.sortRange) {
const [start, end] = filter.sortRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sort: {
...where.sort,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sort: {
...where.sort,
[Op.lte]: end,
},
};
}
}
if (filter.deduct_amountRange) {
const [start, end] = filter.deduct_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
deduct_amount: {
...where.deduct_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
deduct_amount: {
...where.deduct_amount,
[Op.lte]: end,
},
};
}
}
if (filter.deduct_paid_amountRange) {
const [start, end] = filter.deduct_paid_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
deduct_paid_amount: {
...where.deduct_paid_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
deduct_paid_amount: {
...where.deduct_paid_amount,
[Op.lte]: end,
},
};
}
}
if (filter.intervalRange) {
const [start, end] = filter.intervalRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
interval: {
...where.interval,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
interval: {
...where.interval,
[Op.lte]: end,
},
};
}
}
if (filter.interest_amountRange) {
const [start, end] = filter.interest_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
interest_amount: {
...where.interest_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
interest_amount: {
...where.interest_amount,
[Op.lte]: end,
},
};
}
}
if (filter.commission_amountRange) {
const [start, end] = filter.commission_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
commission_amount: {
...where.commission_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
commission_amount: {
...where.commission_amount,
[Op.lte]: end,
},
};
}
}
if (filter.total_amountRange) {
const [start, end] = filter.total_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
total_amount: {
...where.total_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
total_amount: {
...where.total_amount,
[Op.lte]: end,
},
};
}
}
if (filter.total_paid_amountRange) {
const [start, end] = filter.total_paid_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
total_paid_amount: {
...where.total_paid_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
total_paid_amount: {
...where.total_paid_amount,
[Op.lte]: end,
},
};
}
}
if (filter.penalty_amountRange) {
const [start, end] = filter.penalty_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
penalty_amount: {
...where.penalty_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
penalty_amount: {
...where.penalty_amount,
[Op.lte]: end,
},
};
}
}
if (filter.pending_amountRange) {
const [start, end] = filter.pending_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
pending_amount: {
...where.pending_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
pending_amount: {
...where.pending_amount,
[Op.lte]: end,
},
};
}
}
if (filter.cross_amountRange) {
const [start, end] = filter.cross_amountRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
cross_amount: {
...where.cross_amount,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
cross_amount: {
...where.cross_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.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(
'payments',
'remark',
query,
),
],
};
}
const records = await db.payments.findAll({
attributes: [ 'id', 'remark' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['remark', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.remark,
}));
}
};

View File

@ -0,0 +1,311 @@
const db = require('../models');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class ProvincesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const provinces = await db.provinces.create(
{
id: data.id || undefined,
name_kh: data.name_kh
||
null
,
name_en: data.name_en
||
null
,
active: data.active
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return provinces;
}
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 provincesData = data.map((item, index) => ({
id: item.id || undefined,
name_kh: item.name_kh
||
null
,
name_en: item.name_en
||
null
,
active: item.active
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const provinces = await db.provinces.bulkCreate(provincesData, { transaction });
return provinces;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const provinces = await db.provinces.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name_kh !== undefined) updatePayload.name_kh = data.name_kh;
if (data.name_en !== undefined) updatePayload.name_en = data.name_en;
if (data.active !== undefined) updatePayload.active = data.active;
updatePayload.updatedById = currentUser.id;
await provinces.update(updatePayload, {transaction});
return provinces;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const provinces = await db.provinces.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of provinces) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of provinces) {
await record.destroy({transaction});
}
});
return provinces;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const provinces = await db.provinces.findByPk(id, options);
await provinces.update({
deletedBy: currentUser.id
}, {
transaction,
});
await provinces.destroy({
transaction
});
return provinces;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const provinces = await db.provinces.findOne(
{ where },
{ transaction },
);
if (!provinces) {
return provinces;
}
const output = provinces.get({plain: true});
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
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_kh) {
where = {
...where,
[Op.and]: Utils.ilike(
'provinces',
'name_kh',
filter.name_kh,
),
};
}
if (filter.name_en) {
where = {
...where,
[Op.and]: Utils.ilike(
'provinces',
'name_en',
filter.name_en,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.active) {
where = {
...where,
active: filter.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.provinces.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(
'provinces',
'name_en',
query,
),
],
};
}
const records = await db.provinces.findAll({
attributes: [ 'id', 'name_en' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['name_en', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.name_en,
}));
}
};

267
backend/src/db/api/sexes.js Normal file
View File

@ -0,0 +1,267 @@
const db = require('../models');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class SexesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const sexes = await db.sexes.create(
{
id: data.id || undefined,
name: data.name
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return sexes;
}
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 sexesData = 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 sexes = await db.sexes.bulkCreate(sexesData, { transaction });
return sexes;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const sexes = await db.sexes.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
updatePayload.updatedById = currentUser.id;
await sexes.update(updatePayload, {transaction});
return sexes;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const sexes = await db.sexes.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of sexes) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of sexes) {
await record.destroy({transaction});
}
});
return sexes;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const sexes = await db.sexes.findByPk(id, options);
await sexes.update({
deletedBy: currentUser.id
}, {
transaction,
});
await sexes.destroy({
transaction
});
return sexes;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const sexes = await db.sexes.findOne(
{ where },
{ transaction },
);
if (!sexes) {
return sexes;
}
const output = sexes.get({plain: true});
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
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(
'sexes',
'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.sexes.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(
'sexes',
'name',
query,
),
],
};
}
const records = await db.sexes.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,555 @@
const db = require('../models');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class ShareholdersDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const shareholders = await db.shareholders.create(
{
id: data.id || undefined,
name_en: data.name_en
||
null
,
name_kh: data.name_kh
||
null
,
earn_rate: data.earn_rate
||
null
,
date_of_birth: data.date_of_birth
||
null
,
phone_number: data.phone_number
||
null
,
start_work_date: data.start_work_date
||
null
,
born_place: data.born_place
||
null
,
document_type: data.document_type
||
null
,
document_number: data.document_number
||
null
,
emergency_number: data.emergency_number
||
null
,
current_place: data.current_place
||
null
,
sex: data.sex
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return shareholders;
}
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 shareholdersData = data.map((item, index) => ({
id: item.id || undefined,
name_en: item.name_en
||
null
,
name_kh: item.name_kh
||
null
,
earn_rate: item.earn_rate
||
null
,
date_of_birth: item.date_of_birth
||
null
,
phone_number: item.phone_number
||
null
,
start_work_date: item.start_work_date
||
null
,
born_place: item.born_place
||
null
,
document_type: item.document_type
||
null
,
document_number: item.document_number
||
null
,
emergency_number: item.emergency_number
||
null
,
current_place: item.current_place
||
null
,
sex: item.sex
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const shareholders = await db.shareholders.bulkCreate(shareholdersData, { transaction });
return shareholders;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const shareholders = await db.shareholders.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name_en !== undefined) updatePayload.name_en = data.name_en;
if (data.name_kh !== undefined) updatePayload.name_kh = data.name_kh;
if (data.earn_rate !== undefined) updatePayload.earn_rate = data.earn_rate;
if (data.date_of_birth !== undefined) updatePayload.date_of_birth = data.date_of_birth;
if (data.phone_number !== undefined) updatePayload.phone_number = data.phone_number;
if (data.start_work_date !== undefined) updatePayload.start_work_date = data.start_work_date;
if (data.born_place !== undefined) updatePayload.born_place = data.born_place;
if (data.document_type !== undefined) updatePayload.document_type = data.document_type;
if (data.document_number !== undefined) updatePayload.document_number = data.document_number;
if (data.emergency_number !== undefined) updatePayload.emergency_number = data.emergency_number;
if (data.current_place !== undefined) updatePayload.current_place = data.current_place;
if (data.sex !== undefined) updatePayload.sex = data.sex;
updatePayload.updatedById = currentUser.id;
await shareholders.update(updatePayload, {transaction});
return shareholders;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const shareholders = await db.shareholders.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of shareholders) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of shareholders) {
await record.destroy({transaction});
}
});
return shareholders;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const shareholders = await db.shareholders.findByPk(id, options);
await shareholders.update({
deletedBy: currentUser.id
}, {
transaction,
});
await shareholders.destroy({
transaction
});
return shareholders;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const shareholders = await db.shareholders.findOne(
{ where },
{ transaction },
);
if (!shareholders) {
return shareholders;
}
const output = shareholders.get({plain: true});
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
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_en) {
where = {
...where,
[Op.and]: Utils.ilike(
'shareholders',
'name_en',
filter.name_en,
),
};
}
if (filter.name_kh) {
where = {
...where,
[Op.and]: Utils.ilike(
'shareholders',
'name_kh',
filter.name_kh,
),
};
}
if (filter.phone_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'shareholders',
'phone_number',
filter.phone_number,
),
};
}
if (filter.born_place) {
where = {
...where,
[Op.and]: Utils.ilike(
'shareholders',
'born_place',
filter.born_place,
),
};
}
if (filter.document_type) {
where = {
...where,
[Op.and]: Utils.ilike(
'shareholders',
'document_type',
filter.document_type,
),
};
}
if (filter.document_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'shareholders',
'document_number',
filter.document_number,
),
};
}
if (filter.emergency_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'shareholders',
'emergency_number',
filter.emergency_number,
),
};
}
if (filter.current_place) {
where = {
...where,
[Op.and]: Utils.ilike(
'shareholders',
'current_place',
filter.current_place,
),
};
}
if (filter.earn_rateRange) {
const [start, end] = filter.earn_rateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
earn_rate: {
...where.earn_rate,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
earn_rate: {
...where.earn_rate,
[Op.lte]: end,
},
};
}
}
if (filter.date_of_birthRange) {
const [start, end] = filter.date_of_birthRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
date_of_birth: {
...where.date_of_birth,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
date_of_birth: {
...where.date_of_birth,
[Op.lte]: end,
},
};
}
}
if (filter.start_work_dateRange) {
const [start, end] = filter.start_work_dateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
start_work_date: {
...where.start_work_date,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
start_work_date: {
...where.start_work_date,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.sex) {
where = {
...where,
sex: filter.sex,
};
}
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.shareholders.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(
'shareholders',
'name_en',
query,
),
],
};
}
const records = await db.shareholders.findAll({
attributes: [ 'id', 'name_en' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['name_en', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.name_en,
}));
}
};

View File

@ -0,0 +1,290 @@
const db = require('../models');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Staff_statusDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const staff_status = await db.staff_status.create(
{
id: data.id || undefined,
name: data.name
||
null
,
css: data.css
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return staff_status;
}
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 staff_statusData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
css: item.css
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const staff_status = await db.staff_status.bulkCreate(staff_statusData, { transaction });
return staff_status;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const staff_status = await db.staff_status.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.css !== undefined) updatePayload.css = data.css;
updatePayload.updatedById = currentUser.id;
await staff_status.update(updatePayload, {transaction});
return staff_status;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const staff_status = await db.staff_status.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of staff_status) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of staff_status) {
await record.destroy({transaction});
}
});
return staff_status;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const staff_status = await db.staff_status.findByPk(id, options);
await staff_status.update({
deletedBy: currentUser.id
}, {
transaction,
});
await staff_status.destroy({
transaction
});
return staff_status;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const staff_status = await db.staff_status.findOne(
{ where },
{ transaction },
);
if (!staff_status) {
return staff_status;
}
const output = staff_status.get({plain: true});
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
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(
'staff_status',
'name',
filter.name,
),
};
}
if (filter.css) {
where = {
...where,
[Op.and]: Utils.ilike(
'staff_status',
'css',
filter.css,
),
};
}
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.staff_status.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(
'staff_status',
'name',
query,
),
],
};
}
const records = await db.staff_status.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,519 @@
const db = require('../models');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class StaffsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const staffs = await db.staffs.create(
{
id: data.id || undefined,
name_en: data.name_en
||
null
,
name_kh: data.name_kh
||
null
,
date_of_birth: data.date_of_birth
||
null
,
phone_number: data.phone_number
||
null
,
start_work_date: data.start_work_date
||
null
,
born_place: data.born_place
||
null
,
document_type: data.document_type
||
null
,
document_number: data.document_number
||
null
,
emergency_number: data.emergency_number
||
null
,
current_place: data.current_place
||
null
,
sex: data.sex
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return staffs;
}
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 staffsData = data.map((item, index) => ({
id: item.id || undefined,
name_en: item.name_en
||
null
,
name_kh: item.name_kh
||
null
,
date_of_birth: item.date_of_birth
||
null
,
phone_number: item.phone_number
||
null
,
start_work_date: item.start_work_date
||
null
,
born_place: item.born_place
||
null
,
document_type: item.document_type
||
null
,
document_number: item.document_number
||
null
,
emergency_number: item.emergency_number
||
null
,
current_place: item.current_place
||
null
,
sex: item.sex
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const staffs = await db.staffs.bulkCreate(staffsData, { transaction });
return staffs;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const staffs = await db.staffs.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name_en !== undefined) updatePayload.name_en = data.name_en;
if (data.name_kh !== undefined) updatePayload.name_kh = data.name_kh;
if (data.date_of_birth !== undefined) updatePayload.date_of_birth = data.date_of_birth;
if (data.phone_number !== undefined) updatePayload.phone_number = data.phone_number;
if (data.start_work_date !== undefined) updatePayload.start_work_date = data.start_work_date;
if (data.born_place !== undefined) updatePayload.born_place = data.born_place;
if (data.document_type !== undefined) updatePayload.document_type = data.document_type;
if (data.document_number !== undefined) updatePayload.document_number = data.document_number;
if (data.emergency_number !== undefined) updatePayload.emergency_number = data.emergency_number;
if (data.current_place !== undefined) updatePayload.current_place = data.current_place;
if (data.sex !== undefined) updatePayload.sex = data.sex;
updatePayload.updatedById = currentUser.id;
await staffs.update(updatePayload, {transaction});
return staffs;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const staffs = await db.staffs.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of staffs) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of staffs) {
await record.destroy({transaction});
}
});
return staffs;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const staffs = await db.staffs.findByPk(id, options);
await staffs.update({
deletedBy: currentUser.id
}, {
transaction,
});
await staffs.destroy({
transaction
});
return staffs;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const staffs = await db.staffs.findOne(
{ where },
{ transaction },
);
if (!staffs) {
return staffs;
}
const output = staffs.get({plain: true});
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
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_en) {
where = {
...where,
[Op.and]: Utils.ilike(
'staffs',
'name_en',
filter.name_en,
),
};
}
if (filter.name_kh) {
where = {
...where,
[Op.and]: Utils.ilike(
'staffs',
'name_kh',
filter.name_kh,
),
};
}
if (filter.phone_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'staffs',
'phone_number',
filter.phone_number,
),
};
}
if (filter.born_place) {
where = {
...where,
[Op.and]: Utils.ilike(
'staffs',
'born_place',
filter.born_place,
),
};
}
if (filter.document_type) {
where = {
...where,
[Op.and]: Utils.ilike(
'staffs',
'document_type',
filter.document_type,
),
};
}
if (filter.document_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'staffs',
'document_number',
filter.document_number,
),
};
}
if (filter.emergency_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'staffs',
'emergency_number',
filter.emergency_number,
),
};
}
if (filter.current_place) {
where = {
...where,
[Op.and]: Utils.ilike(
'staffs',
'current_place',
filter.current_place,
),
};
}
if (filter.date_of_birthRange) {
const [start, end] = filter.date_of_birthRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
date_of_birth: {
...where.date_of_birth,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
date_of_birth: {
...where.date_of_birth,
[Op.lte]: end,
},
};
}
}
if (filter.start_work_dateRange) {
const [start, end] = filter.start_work_dateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
start_work_date: {
...where.start_work_date,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
start_work_date: {
...where.start_work_date,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.sex) {
where = {
...where,
sex: filter.sex,
};
}
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.staffs.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(
'staffs',
'name_en',
query,
),
],
};
}
const records = await db.staffs.findAll({
attributes: [ 'id', 'name_en' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['name_en', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.name_en,
}));
}
};

351
backend/src/db/api/urls.js Normal file
View File

@ -0,0 +1,351 @@
const db = require('../models');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class UrlsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const urls = await db.urls.create(
{
id: data.id || undefined,
method: data.method
||
null
,
uri: data.uri
||
null
,
route_name: data.route_name
||
null
,
acitve: data.acitve
||
false
,
is_menu: data.is_menu
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return urls;
}
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 urlsData = data.map((item, index) => ({
id: item.id || undefined,
method: item.method
||
null
,
uri: item.uri
||
null
,
route_name: item.route_name
||
null
,
acitve: item.acitve
||
false
,
is_menu: item.is_menu
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const urls = await db.urls.bulkCreate(urlsData, { transaction });
return urls;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const urls = await db.urls.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.method !== undefined) updatePayload.method = data.method;
if (data.uri !== undefined) updatePayload.uri = data.uri;
if (data.route_name !== undefined) updatePayload.route_name = data.route_name;
if (data.acitve !== undefined) updatePayload.acitve = data.acitve;
if (data.is_menu !== undefined) updatePayload.is_menu = data.is_menu;
updatePayload.updatedById = currentUser.id;
await urls.update(updatePayload, {transaction});
return urls;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const urls = await db.urls.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of urls) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of urls) {
await record.destroy({transaction});
}
});
return urls;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const urls = await db.urls.findByPk(id, options);
await urls.update({
deletedBy: currentUser.id
}, {
transaction,
});
await urls.destroy({
transaction
});
return urls;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const urls = await db.urls.findOne(
{ where },
{ transaction },
);
if (!urls) {
return urls;
}
const output = urls.get({plain: true});
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
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.uri) {
where = {
...where,
[Op.and]: Utils.ilike(
'urls',
'uri',
filter.uri,
),
};
}
if (filter.route_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'urls',
'route_name',
filter.route_name,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.method) {
where = {
...where,
method: filter.method,
};
}
if (filter.acitve) {
where = {
...where,
acitve: filter.acitve,
};
}
if (filter.is_menu) {
where = {
...where,
is_menu: filter.is_menu,
};
}
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.urls.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(
'urls',
'uri',
query,
),
],
};
}
const records = await db.urls.findAll({
attributes: [ 'id', 'uri' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['uri', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.uri,
}));
}
};

View File

@ -0,0 +1,267 @@
const db = require('../models');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class User_has_menuDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const user_has_menu = await db.user_has_menu.create(
{
id: data.id || undefined,
status: data.status
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return user_has_menu;
}
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 user_has_menuData = data.map((item, index) => ({
id: item.id || undefined,
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 user_has_menu = await db.user_has_menu.bulkCreate(user_has_menuData, { transaction });
return user_has_menu;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const user_has_menu = await db.user_has_menu.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.status !== undefined) updatePayload.status = data.status;
updatePayload.updatedById = currentUser.id;
await user_has_menu.update(updatePayload, {transaction});
return user_has_menu;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const user_has_menu = await db.user_has_menu.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of user_has_menu) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of user_has_menu) {
await record.destroy({transaction});
}
});
return user_has_menu;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const user_has_menu = await db.user_has_menu.findByPk(id, options);
await user_has_menu.update({
deletedBy: currentUser.id
}, {
transaction,
});
await user_has_menu.destroy({
transaction
});
return user_has_menu;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const user_has_menu = await db.user_has_menu.findOne(
{ where },
{ transaction },
);
if (!user_has_menu) {
return user_has_menu;
}
const output = user_has_menu.get({plain: true});
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
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.status) {
where = {
...where,
[Op.and]: Utils.ilike(
'user_has_menu',
'status',
filter.status,
),
};
}
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.user_has_menu.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(
'user_has_menu',
'status',
query,
),
],
};
}
const records = await db.user_has_menu.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,244 @@
const db = require('../models');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class User_type_urlsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const user_type_urls = await db.user_type_urls.create(
{
id: data.id || undefined,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return user_type_urls;
}
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 user_type_urlsData = data.map((item, index) => ({
id: item.id || undefined,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const user_type_urls = await db.user_type_urls.bulkCreate(user_type_urlsData, { transaction });
return user_type_urls;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const user_type_urls = await db.user_type_urls.findByPk(id, {}, {transaction});
const updatePayload = {};
updatePayload.updatedById = currentUser.id;
await user_type_urls.update(updatePayload, {transaction});
return user_type_urls;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const user_type_urls = await db.user_type_urls.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of user_type_urls) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of user_type_urls) {
await record.destroy({transaction});
}
});
return user_type_urls;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const user_type_urls = await db.user_type_urls.findByPk(id, options);
await user_type_urls.update({
deletedBy: currentUser.id
}, {
transaction,
});
await user_type_urls.destroy({
transaction
});
return user_type_urls;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const user_type_urls = await db.user_type_urls.findOne(
{ where },
{ transaction },
);
if (!user_type_urls) {
return user_type_urls;
}
const output = user_type_urls.get({plain: true});
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.user_type_urls.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(
'user_type_urls',
'user_type',
query,
),
],
};
}
const records = await db.user_type_urls.findAll({
attributes: [ 'id', 'user_type' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['user_type', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.user_type,
}));
}
};

View File

@ -0,0 +1,288 @@
const db = require('../models');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class User_typesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const user_types = await db.user_types.create(
{
id: data.id || undefined,
is_admin: data.is_admin
||
false
,
name: data.name
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return user_types;
}
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 user_typesData = data.map((item, index) => ({
id: item.id || undefined,
is_admin: item.is_admin
||
false
,
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 user_types = await db.user_types.bulkCreate(user_typesData, { transaction });
return user_types;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const user_types = await db.user_types.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.is_admin !== undefined) updatePayload.is_admin = data.is_admin;
if (data.name !== undefined) updatePayload.name = data.name;
updatePayload.updatedById = currentUser.id;
await user_types.update(updatePayload, {transaction});
return user_types;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const user_types = await db.user_types.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of user_types) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of user_types) {
await record.destroy({transaction});
}
});
return user_types;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const user_types = await db.user_types.findByPk(id, options);
await user_types.update({
deletedBy: currentUser.id
}, {
transaction,
});
await user_types.destroy({
transaction
});
return user_types;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const user_types = await db.user_types.findOne(
{ where },
{ transaction },
);
if (!user_types) {
return user_types;
}
const output = user_types.get({plain: true});
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
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(
'user_types',
'name',
filter.name,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.is_admin) {
where = {
...where,
is_admin: filter.is_admin,
};
}
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.user_types.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(
'user_types',
'name',
query,
),
],
};
}
const records = await db.user_types.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,
}));
}
};

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

@ -0,0 +1,692 @@
const db = require('../models');
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 },
);
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 });
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});
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});
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
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.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.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,290 @@
const db = require('../models');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class VillagesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const villages = await db.villages.create(
{
id: data.id || undefined,
name_kh: data.name_kh
||
null
,
name_en: data.name_en
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return villages;
}
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 villagesData = data.map((item, index) => ({
id: item.id || undefined,
name_kh: item.name_kh
||
null
,
name_en: item.name_en
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const villages = await db.villages.bulkCreate(villagesData, { transaction });
return villages;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const villages = await db.villages.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name_kh !== undefined) updatePayload.name_kh = data.name_kh;
if (data.name_en !== undefined) updatePayload.name_en = data.name_en;
updatePayload.updatedById = currentUser.id;
await villages.update(updatePayload, {transaction});
return villages;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const villages = await db.villages.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of villages) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of villages) {
await record.destroy({transaction});
}
});
return villages;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const villages = await db.villages.findByPk(id, options);
await villages.update({
deletedBy: currentUser.id
}, {
transaction,
});
await villages.destroy({
transaction
});
return villages;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const villages = await db.villages.findOne(
{ where },
{ transaction },
);
if (!villages) {
return villages;
}
const output = villages.get({plain: true});
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
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_kh) {
where = {
...where,
[Op.and]: Utils.ilike(
'villages',
'name_kh',
filter.name_kh,
),
};
}
if (filter.name_en) {
where = {
...where,
[Op.and]: Utils.ilike(
'villages',
'name_en',
filter.name_en,
),
};
}
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.villages.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(
'villages',
'name_en',
query,
),
],
};
}
const records = await db.villages.findAll({
attributes: [ 'id', 'name_en' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['name_en', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.name_en,
}));
}
};

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_meng_leap_cash',
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,58 @@
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 branches = sequelize.define(
'branches',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
code: {
type: DataTypes.TEXT,
},
name: {
type: DataTypes.TEXT,
},
description: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
branches.associate = (db) => {
db.branches.belongsTo(db.users, {
as: 'createdBy',
});
db.branches.belongsTo(db.users, {
as: 'updatedBy',
});
};
return branches;
};

View File

@ -0,0 +1,74 @@
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 calendars = sequelize.define(
'calendars',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
date: {
type: DataTypes.DATE,
},
is_weekend: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
is_holiday: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
description: {
type: DataTypes.TEXT,
},
flag: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
calendars.associate = (db) => {
db.calendars.belongsTo(db.users, {
as: 'createdBy',
});
db.calendars.belongsTo(db.users, {
as: 'updatedBy',
});
};
return calendars;
};

View File

@ -0,0 +1,48 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const client_status = sequelize.define(
'client_status',
{
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,
},
);
client_status.associate = (db) => {
db.client_status.belongsTo(db.users, {
as: 'createdBy',
});
db.client_status.belongsTo(db.users, {
as: 'updatedBy',
});
};
return client_status;
};

View File

@ -0,0 +1,94 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const clients = sequelize.define(
'clients',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
code: {
type: DataTypes.TEXT,
},
name_en: {
type: DataTypes.TEXT,
},
name_kh: {
type: DataTypes.TEXT,
},
date_of_birth: {
type: DataTypes.DATE,
},
phone_number: {
type: DataTypes.TEXT,
},
is_new: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
document_number: {
type: DataTypes.TEXT,
},
sex: {
type: DataTypes.ENUM,
values: [
"M",
"F"
],
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
clients.associate = (db) => {
db.clients.belongsTo(db.users, {
as: 'createdBy',
});
db.clients.belongsTo(db.users, {
as: 'updatedBy',
});
};
return clients;
};

View File

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

View File

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

View File

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

View File

@ -0,0 +1,48 @@
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 document_type = sequelize.define(
'document_type',
{
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,
},
);
document_type.associate = (db) => {
db.document_type.belongsTo(db.users, {
as: 'createdBy',
});
db.document_type.belongsTo(db.users, {
as: 'updatedBy',
});
};
return document_type;
};

View File

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

View File

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

View File

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

View File

@ -0,0 +1,86 @@
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 guarantor = sequelize.define(
'guarantor',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
full_name: {
type: DataTypes.TEXT,
},
sex: {
type: DataTypes.ENUM,
values: [
"M",
"F"
],
},
date_of_birth: {
type: DataTypes.DATE,
},
document_type: {
type: DataTypes.TEXT,
},
document_number: {
type: DataTypes.TEXT,
},
phone_number: {
type: DataTypes.TEXT,
},
full_address_input: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
guarantor.associate = (db) => {
db.guarantor.belongsTo(db.users, {
as: 'createdBy',
});
db.guarantor.belongsTo(db.users, {
as: 'updatedBy',
});
};
return guarantor;
};

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,83 @@
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 interest_rates = sequelize.define(
'interest_rates',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
code: {
type: DataTypes.TEXT,
},
name: {
type: DataTypes.TEXT,
},
rate: {
type: DataTypes.DECIMAL,
},
commission_rate: {
type: DataTypes.DECIMAL,
},
interval: {
type: DataTypes.INTEGER,
},
sort: {
type: DataTypes.INTEGER,
},
css: {
type: DataTypes.TEXT,
},
setting: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
interest_rates.associate = (db) => {
db.interest_rates.belongsTo(db.users, {
as: 'createdBy',
});
db.interest_rates.belongsTo(db.users, {
as: 'updatedBy',
});
};
return interest_rates;
};

View File

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

View File

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

View File

@ -0,0 +1,123 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const loans = sequelize.define(
'loans',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
code: {
type: DataTypes.TEXT,
},
principal_amount: {
type: DataTypes.DECIMAL,
},
term: {
type: DataTypes.INTEGER,
},
pending_amount: {
type: DataTypes.DECIMAL,
},
last_pending_amount: {
type: DataTypes.DECIMAL,
},
rate: {
type: DataTypes.DECIMAL,
},
commission_rate: {
type: DataTypes.DECIMAL,
},
registration_date: {
type: DataTypes.DATE,
},
started_payment_date: {
type: DataTypes.DATE,
},
last_payment_date: {
type: DataTypes.DATE,
},
finish_payment_date: {
type: DataTypes.DATE,
},
finish_discount: {
type: DataTypes.DECIMAL,
},
finish_discount_amount: {
type: DataTypes.DECIMAL,
},
admin_rate: {
type: DataTypes.DECIMAL,
},
admin_amount: {
type: DataTypes.DECIMAL,
},
purpose: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
loans.associate = (db) => {
db.loans.belongsTo(db.users, {
as: 'createdBy',
});
db.loans.belongsTo(db.users, {
as: 'updatedBy',
});
};
return loans;
};

View File

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

View File

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

View File

@ -0,0 +1,73 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const payment_revenues = sequelize.define(
'payment_revenues',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
transaction_date: {
type: DataTypes.DATE,
},
admin_fee_amount: {
type: DataTypes.DECIMAL,
},
interest_amount: {
type: DataTypes.DECIMAL,
},
commission_amount: {
type: DataTypes.DECIMAL,
},
expense_amount: {
type: DataTypes.DECIMAL,
},
setlement_datetime: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
payment_revenues.associate = (db) => {
db.payment_revenues.belongsTo(db.users, {
as: 'createdBy',
});
db.payment_revenues.belongsTo(db.users, {
as: 'updatedBy',
});
};
return payment_revenues;
};

View File

@ -0,0 +1,61 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const payment_status = sequelize.define(
'payment_status',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
css: {
type: DataTypes.TEXT,
},
visible: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
payment_status.associate = (db) => {
db.payment_status.belongsTo(db.users, {
as: 'createdBy',
});
db.payment_status.belongsTo(db.users, {
as: 'updatedBy',
});
};
return payment_status;
};

View File

@ -0,0 +1,93 @@
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_transactions = sequelize.define(
'payment_transactions',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
transaction_datetime: {
type: DataTypes.DATE,
},
transaction_amount: {
type: DataTypes.DECIMAL,
},
deduct_amount: {
type: DataTypes.DECIMAL,
},
interest_amount: {
type: DataTypes.DECIMAL,
},
commission_amount: {
type: DataTypes.DECIMAL,
},
revenue_amount: {
type: DataTypes.DECIMAL,
},
setlement_datetime: {
type: DataTypes.DATE,
},
type: {
type: DataTypes.ENUM,
values: [
"interest",
"deduction",
"reverse"
],
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
payment_transactions.associate = (db) => {
db.payment_transactions.belongsTo(db.users, {
as: 'createdBy',
});
db.payment_transactions.belongsTo(db.users, {
as: 'updatedBy',
});
};
return payment_transactions;
};

View File

@ -0,0 +1,118 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const payments = sequelize.define(
'payments',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
start_payment_date: {
type: DataTypes.DATE,
},
payment_date: {
type: DataTypes.DATE,
},
last_payment_paid_date: {
type: DataTypes.DATE,
},
sort: {
type: DataTypes.INTEGER,
},
deduct_amount: {
type: DataTypes.DECIMAL,
},
deduct_paid_amount: {
type: DataTypes.DECIMAL,
},
interval: {
type: DataTypes.INTEGER,
},
interest_amount: {
type: DataTypes.DECIMAL,
},
commission_amount: {
type: DataTypes.DECIMAL,
},
total_amount: {
type: DataTypes.DECIMAL,
},
total_paid_amount: {
type: DataTypes.DECIMAL,
},
penalty_amount: {
type: DataTypes.DECIMAL,
},
pending_amount: {
type: DataTypes.DECIMAL,
},
cross_amount: {
type: DataTypes.DECIMAL,
},
remark: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
payments.associate = (db) => {
db.payments.belongsTo(db.users, {
as: 'createdBy',
});
db.payments.belongsTo(db.users, {
as: 'updatedBy',
});
};
return payments;
};

View File

@ -0,0 +1,61 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const provinces = sequelize.define(
'provinces',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name_kh: {
type: DataTypes.TEXT,
},
name_en: {
type: DataTypes.TEXT,
},
active: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
provinces.associate = (db) => {
db.provinces.belongsTo(db.users, {
as: 'createdBy',
});
db.provinces.belongsTo(db.users, {
as: 'updatedBy',
});
};
return provinces;
};

View File

@ -0,0 +1,48 @@
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 sexes = sequelize.define(
'sexes',
{
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,
},
);
sexes.associate = (db) => {
db.sexes.belongsTo(db.users, {
as: 'createdBy',
});
db.sexes.belongsTo(db.users, {
as: 'updatedBy',
});
};
return sexes;
};

View File

@ -0,0 +1,111 @@
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 shareholders = sequelize.define(
'shareholders',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name_en: {
type: DataTypes.TEXT,
},
name_kh: {
type: DataTypes.TEXT,
},
earn_rate: {
type: DataTypes.DECIMAL,
},
date_of_birth: {
type: DataTypes.DATE,
},
phone_number: {
type: DataTypes.TEXT,
},
start_work_date: {
type: DataTypes.DATE,
},
born_place: {
type: DataTypes.TEXT,
},
document_type: {
type: DataTypes.TEXT,
},
document_number: {
type: DataTypes.TEXT,
},
emergency_number: {
type: DataTypes.TEXT,
},
current_place: {
type: DataTypes.TEXT,
},
sex: {
type: DataTypes.ENUM,
values: [
"M",
"F"
],
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
shareholders.associate = (db) => {
db.shareholders.belongsTo(db.users, {
as: 'createdBy',
});
db.shareholders.belongsTo(db.users, {
as: 'updatedBy',
});
};
return shareholders;
};

View File

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

View File

@ -0,0 +1,106 @@
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 staffs = sequelize.define(
'staffs',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name_en: {
type: DataTypes.TEXT,
},
name_kh: {
type: DataTypes.TEXT,
},
date_of_birth: {
type: DataTypes.DATE,
},
phone_number: {
type: DataTypes.TEXT,
},
start_work_date: {
type: DataTypes.DATE,
},
born_place: {
type: DataTypes.TEXT,
},
document_type: {
type: DataTypes.TEXT,
},
document_number: {
type: DataTypes.TEXT,
},
emergency_number: {
type: DataTypes.TEXT,
},
current_place: {
type: DataTypes.TEXT,
},
sex: {
type: DataTypes.ENUM,
values: [
"M",
"F"
],
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
staffs.associate = (db) => {
db.staffs.belongsTo(db.users, {
as: 'createdBy',
});
db.staffs.belongsTo(db.users, {
as: 'updatedBy',
});
};
return staffs;
};

View File

@ -0,0 +1,86 @@
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 urls = sequelize.define(
'urls',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
method: {
type: DataTypes.ENUM,
values: [
"GET",
"POST",
"PATCH",
"DELETE"
],
},
uri: {
type: DataTypes.TEXT,
},
route_name: {
type: DataTypes.TEXT,
},
acitve: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
is_menu: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
urls.associate = (db) => {
db.urls.belongsTo(db.users, {
as: 'createdBy',
});
db.urls.belongsTo(db.users, {
as: 'updatedBy',
});
};
return urls;
};

View File

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

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