Initial version

This commit is contained in:
Flatlogic Bot 2026-05-06 18:59:03 +00:00
commit 65ab3be81a
481 changed files with 142720 additions and 0 deletions

305
.cursorrules Normal file
View File

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

3
.dockerignore Normal file
View File

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

3
.gitignore vendored Normal file
View File

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

187
502.html Normal file
View File

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

21
Dockerfile Normal file
View File

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

85
Dockerfile.dev Normal file
View File

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

1
LICENSE Normal file
View File

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

244
README.md Normal file
View File

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

1
backend/.env Normal file
View File

@ -0,0 +1 @@
PORT=8080

4
backend/.eslintignore Normal file
View File

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

15
backend/.eslintrc.cjs Normal file
View File

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

11
backend/.prettierrc Normal file
View File

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

7
backend/.sequelizerc Normal file
View File

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

23
backend/Dockerfile Normal file
View File

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

56
backend/README.md Normal file
View File

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

56
backend/package.json Normal file
View File

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

View File

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

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

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

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

@ -0,0 +1,79 @@
const os = require('os');
const config = {
gcloud: {
bucket: "fldemo-files",
hash: "afeefb9d49f5b7977577876b99532ac7"
},
bcrypt: {
saltRounds: 12
},
admin_pass: "a6643b6d",
user_pass: "10c056694666",
admin_email: "admin@flatlogic.com",
providers: {
LOCAL: 'local',
GOOGLE: 'google',
MICROSOFT: 'microsoft'
},
secret_key: process.env.SECRET_KEY || 'a6643b6d-92c1-4928-86aa-10c056694666',
remote: '',
port: process.env.NODE_ENV === "production" ? "" : "8080",
hostUI: process.env.NODE_ENV === "production" ? "" : "http://localhost",
portUI: process.env.NODE_ENV === "production" ? "" : "3000",
portUIProd: process.env.NODE_ENV === "production" ? "" : ":3000",
swaggerUI: process.env.NODE_ENV === "production" ? "" : "http://localhost",
swaggerPort: process.env.NODE_ENV === "production" ? "" : ":8080",
google: {
clientId: process.env.GOOGLE_CLIENT_ID || '',
clientSecret: process.env.GOOGLE_CLIENT_SECRET || '',
},
microsoft: {
clientId: process.env.MS_CLIENT_ID || '',
clientSecret: process.env.MS_CLIENT_SECRET || '',
},
uploadDir: os.tmpdir(),
email: {
from: 'ManiaSkills <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: 'PublicViewer',
},
project_uuid: 'a6643b6d-92c1-4928-86aa-10c056694666',
flHost: process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'dev_stage' ? 'https://flatlogic.com/projects' : 'http://localhost:3000/projects',
gpt_key: process.env.GPT_KEY || '',
};
config.pexelsKey = process.env.PEXELS_KEY || '';
config.pexelsQuery = 'Mountain summit with constellations';
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,642 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Analysis_jobsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const analysis_jobs = await db.analysis_jobs.create(
{
id: data.id || undefined,
job_type: data.job_type
||
null
,
status: data.status
||
null
,
started_at: data.started_at
||
null
,
finished_at: data.finished_at
||
null
,
attempt_number: data.attempt_number
||
null
,
error_message: data.error_message
||
null
,
duration_seconds: data.duration_seconds
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await analysis_jobs.setBeatmap( data.beatmap || null, {
transaction,
});
await analysis_jobs.setPlayer( data.player || null, {
transaction,
});
await analysis_jobs.setCountry( data.country || null, {
transaction,
});
return analysis_jobs;
}
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 analysis_jobsData = data.map((item, index) => ({
id: item.id || undefined,
job_type: item.job_type
||
null
,
status: item.status
||
null
,
started_at: item.started_at
||
null
,
finished_at: item.finished_at
||
null
,
attempt_number: item.attempt_number
||
null
,
error_message: item.error_message
||
null
,
duration_seconds: item.duration_seconds
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const analysis_jobs = await db.analysis_jobs.bulkCreate(analysis_jobsData, { transaction });
// For each item created, replace relation files
return analysis_jobs;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const analysis_jobs = await db.analysis_jobs.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.job_type !== undefined) updatePayload.job_type = data.job_type;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
if (data.finished_at !== undefined) updatePayload.finished_at = data.finished_at;
if (data.attempt_number !== undefined) updatePayload.attempt_number = data.attempt_number;
if (data.error_message !== undefined) updatePayload.error_message = data.error_message;
if (data.duration_seconds !== undefined) updatePayload.duration_seconds = data.duration_seconds;
updatePayload.updatedById = currentUser.id;
await analysis_jobs.update(updatePayload, {transaction});
if (data.beatmap !== undefined) {
await analysis_jobs.setBeatmap(
data.beatmap,
{ transaction }
);
}
if (data.player !== undefined) {
await analysis_jobs.setPlayer(
data.player,
{ transaction }
);
}
if (data.country !== undefined) {
await analysis_jobs.setCountry(
data.country,
{ transaction }
);
}
return analysis_jobs;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const analysis_jobs = await db.analysis_jobs.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of analysis_jobs) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of analysis_jobs) {
await record.destroy({transaction});
}
});
return analysis_jobs;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const analysis_jobs = await db.analysis_jobs.findByPk(id, options);
await analysis_jobs.update({
deletedBy: currentUser.id
}, {
transaction,
});
await analysis_jobs.destroy({
transaction
});
return analysis_jobs;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const analysis_jobs = await db.analysis_jobs.findOne(
{ where },
{ transaction },
);
if (!analysis_jobs) {
return analysis_jobs;
}
const output = analysis_jobs.get({plain: true});
output.beatmap = await analysis_jobs.getBeatmap({
transaction
});
output.player = await analysis_jobs.getPlayer({
transaction
});
output.country = await analysis_jobs.getCountry({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.beatmaps,
as: 'beatmap',
where: filter.beatmap ? {
[Op.or]: [
{ id: { [Op.in]: filter.beatmap.split('|').map(term => Utils.uuid(term)) } },
{
difficulty_name: {
[Op.or]: filter.beatmap.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.players,
as: 'player',
where: filter.player ? {
[Op.or]: [
{ id: { [Op.in]: filter.player.split('|').map(term => Utils.uuid(term)) } },
{
username: {
[Op.or]: filter.player.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.countries,
as: 'country',
where: filter.country ? {
[Op.or]: [
{ id: { [Op.in]: filter.country.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.country.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.error_message) {
where = {
...where,
[Op.and]: Utils.ilike(
'analysis_jobs',
'error_message',
filter.error_message,
),
};
}
if (filter.started_atRange) {
const [start, end] = filter.started_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
started_at: {
...where.started_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
started_at: {
...where.started_at,
[Op.lte]: end,
},
};
}
}
if (filter.finished_atRange) {
const [start, end] = filter.finished_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
finished_at: {
...where.finished_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
finished_at: {
...where.finished_at,
[Op.lte]: end,
},
};
}
}
if (filter.attempt_numberRange) {
const [start, end] = filter.attempt_numberRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
attempt_number: {
...where.attempt_number,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
attempt_number: {
...where.attempt_number,
[Op.lte]: end,
},
};
}
}
if (filter.duration_secondsRange) {
const [start, end] = filter.duration_secondsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
duration_seconds: {
...where.duration_seconds,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
duration_seconds: {
...where.duration_seconds,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.job_type) {
where = {
...where,
job_type: filter.job_type,
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.analysis_jobs.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(
'analysis_jobs',
'error_message',
query,
),
],
};
}
const records = await db.analysis_jobs.findAll({
attributes: [ 'id', 'error_message' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['error_message', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.error_message,
}));
}
};

View File

@ -0,0 +1,550 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Beatmap_setsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const beatmap_sets = await db.beatmap_sets.create(
{
id: data.id || undefined,
osu_set_number: data.osu_set_number
||
null
,
artist: data.artist
||
null
,
title: data.title
||
null
,
source: data.source
||
null
,
tags: data.tags
||
null
,
status: data.status
||
null
,
ranked_at: data.ranked_at
||
null
,
last_checked_at: data.last_checked_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return beatmap_sets;
}
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 beatmap_setsData = data.map((item, index) => ({
id: item.id || undefined,
osu_set_number: item.osu_set_number
||
null
,
artist: item.artist
||
null
,
title: item.title
||
null
,
source: item.source
||
null
,
tags: item.tags
||
null
,
status: item.status
||
null
,
ranked_at: item.ranked_at
||
null
,
last_checked_at: item.last_checked_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const beatmap_sets = await db.beatmap_sets.bulkCreate(beatmap_setsData, { transaction });
// For each item created, replace relation files
return beatmap_sets;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const beatmap_sets = await db.beatmap_sets.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.osu_set_number !== undefined) updatePayload.osu_set_number = data.osu_set_number;
if (data.artist !== undefined) updatePayload.artist = data.artist;
if (data.title !== undefined) updatePayload.title = data.title;
if (data.source !== undefined) updatePayload.source = data.source;
if (data.tags !== undefined) updatePayload.tags = data.tags;
if (data.status !== undefined) updatePayload.status = data.status;
if (data.ranked_at !== undefined) updatePayload.ranked_at = data.ranked_at;
if (data.last_checked_at !== undefined) updatePayload.last_checked_at = data.last_checked_at;
updatePayload.updatedById = currentUser.id;
await beatmap_sets.update(updatePayload, {transaction});
return beatmap_sets;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const beatmap_sets = await db.beatmap_sets.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of beatmap_sets) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of beatmap_sets) {
await record.destroy({transaction});
}
});
return beatmap_sets;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const beatmap_sets = await db.beatmap_sets.findByPk(id, options);
await beatmap_sets.update({
deletedBy: currentUser.id
}, {
transaction,
});
await beatmap_sets.destroy({
transaction
});
return beatmap_sets;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const beatmap_sets = await db.beatmap_sets.findOne(
{ where },
{ transaction },
);
if (!beatmap_sets) {
return beatmap_sets;
}
const output = beatmap_sets.get({plain: true});
output.beatmaps_beatmap_set = await beatmap_sets.getBeatmaps_beatmap_set({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.artist) {
where = {
...where,
[Op.and]: Utils.ilike(
'beatmap_sets',
'artist',
filter.artist,
),
};
}
if (filter.title) {
where = {
...where,
[Op.and]: Utils.ilike(
'beatmap_sets',
'title',
filter.title,
),
};
}
if (filter.source) {
where = {
...where,
[Op.and]: Utils.ilike(
'beatmap_sets',
'source',
filter.source,
),
};
}
if (filter.tags) {
where = {
...where,
[Op.and]: Utils.ilike(
'beatmap_sets',
'tags',
filter.tags,
),
};
}
if (filter.osu_set_numberRange) {
const [start, end] = filter.osu_set_numberRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
osu_set_number: {
...where.osu_set_number,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
osu_set_number: {
...where.osu_set_number,
[Op.lte]: end,
},
};
}
}
if (filter.ranked_atRange) {
const [start, end] = filter.ranked_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
ranked_at: {
...where.ranked_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
ranked_at: {
...where.ranked_at,
[Op.lte]: end,
},
};
}
}
if (filter.last_checked_atRange) {
const [start, end] = filter.last_checked_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
last_checked_at: {
...where.last_checked_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
last_checked_at: {
...where.last_checked_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.status) {
where = {
...where,
status: filter.status,
};
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.beatmap_sets.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(
'beatmap_sets',
'title',
query,
),
],
};
}
const records = await db.beatmap_sets.findAll({
attributes: [ 'id', 'title' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['title', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.title,
}));
}
};

View File

@ -0,0 +1,882 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class BeatmapsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const beatmaps = await db.beatmaps.create(
{
id: data.id || undefined,
osu_map_number: data.osu_map_number
||
null
,
difficulty_name: data.difficulty_name
||
null
,
mode: data.mode
||
null
,
circle_size: data.circle_size
||
null
,
bpm_min: data.bpm_min
||
null
,
bpm_max: data.bpm_max
||
null
,
total_length_ms: data.total_length_ms
||
null
,
drain_length_ms: data.drain_length_ms
||
null
,
total_objects: data.total_objects
||
null
,
total_notes: data.total_notes
||
null
,
total_holds: data.total_holds
||
null
,
star_rating: data.star_rating
||
null
,
submitted_at: data.submitted_at
||
null
,
last_analyzed_at: data.last_analyzed_at
||
null
,
analysis_ready: data.analysis_ready
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await beatmaps.setBeatmap_set( data.beatmap_set || null, {
transaction,
});
return beatmaps;
}
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 beatmapsData = data.map((item, index) => ({
id: item.id || undefined,
osu_map_number: item.osu_map_number
||
null
,
difficulty_name: item.difficulty_name
||
null
,
mode: item.mode
||
null
,
circle_size: item.circle_size
||
null
,
bpm_min: item.bpm_min
||
null
,
bpm_max: item.bpm_max
||
null
,
total_length_ms: item.total_length_ms
||
null
,
drain_length_ms: item.drain_length_ms
||
null
,
total_objects: item.total_objects
||
null
,
total_notes: item.total_notes
||
null
,
total_holds: item.total_holds
||
null
,
star_rating: item.star_rating
||
null
,
submitted_at: item.submitted_at
||
null
,
last_analyzed_at: item.last_analyzed_at
||
null
,
analysis_ready: item.analysis_ready
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const beatmaps = await db.beatmaps.bulkCreate(beatmapsData, { transaction });
// For each item created, replace relation files
return beatmaps;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const beatmaps = await db.beatmaps.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.osu_map_number !== undefined) updatePayload.osu_map_number = data.osu_map_number;
if (data.difficulty_name !== undefined) updatePayload.difficulty_name = data.difficulty_name;
if (data.mode !== undefined) updatePayload.mode = data.mode;
if (data.circle_size !== undefined) updatePayload.circle_size = data.circle_size;
if (data.bpm_min !== undefined) updatePayload.bpm_min = data.bpm_min;
if (data.bpm_max !== undefined) updatePayload.bpm_max = data.bpm_max;
if (data.total_length_ms !== undefined) updatePayload.total_length_ms = data.total_length_ms;
if (data.drain_length_ms !== undefined) updatePayload.drain_length_ms = data.drain_length_ms;
if (data.total_objects !== undefined) updatePayload.total_objects = data.total_objects;
if (data.total_notes !== undefined) updatePayload.total_notes = data.total_notes;
if (data.total_holds !== undefined) updatePayload.total_holds = data.total_holds;
if (data.star_rating !== undefined) updatePayload.star_rating = data.star_rating;
if (data.submitted_at !== undefined) updatePayload.submitted_at = data.submitted_at;
if (data.last_analyzed_at !== undefined) updatePayload.last_analyzed_at = data.last_analyzed_at;
if (data.analysis_ready !== undefined) updatePayload.analysis_ready = data.analysis_ready;
updatePayload.updatedById = currentUser.id;
await beatmaps.update(updatePayload, {transaction});
if (data.beatmap_set !== undefined) {
await beatmaps.setBeatmap_set(
data.beatmap_set,
{ transaction }
);
}
return beatmaps;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const beatmaps = await db.beatmaps.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of beatmaps) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of beatmaps) {
await record.destroy({transaction});
}
});
return beatmaps;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const beatmaps = await db.beatmaps.findByPk(id, options);
await beatmaps.update({
deletedBy: currentUser.id
}, {
transaction,
});
await beatmaps.destroy({
transaction
});
return beatmaps;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const beatmaps = await db.beatmaps.findOne(
{ where },
{ transaction },
);
if (!beatmaps) {
return beatmaps;
}
const output = beatmaps.get({plain: true});
output.map_files_beatmap = await beatmaps.getMap_files_beatmap({
transaction
});
output.map_skills_beatmap = await beatmaps.getMap_skills_beatmap({
transaction
});
output.analysis_jobs_beatmap = await beatmaps.getAnalysis_jobs_beatmap({
transaction
});
output.scores_beatmap = await beatmaps.getScores_beatmap({
transaction
});
output.beatmap_set = await beatmaps.getBeatmap_set({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.beatmap_sets,
as: 'beatmap_set',
where: filter.beatmap_set ? {
[Op.or]: [
{ id: { [Op.in]: filter.beatmap_set.split('|').map(term => Utils.uuid(term)) } },
{
title: {
[Op.or]: filter.beatmap_set.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.difficulty_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'beatmaps',
'difficulty_name',
filter.difficulty_name,
),
};
}
if (filter.osu_map_numberRange) {
const [start, end] = filter.osu_map_numberRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
osu_map_number: {
...where.osu_map_number,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
osu_map_number: {
...where.osu_map_number,
[Op.lte]: end,
},
};
}
}
if (filter.circle_sizeRange) {
const [start, end] = filter.circle_sizeRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
circle_size: {
...where.circle_size,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
circle_size: {
...where.circle_size,
[Op.lte]: end,
},
};
}
}
if (filter.bpm_minRange) {
const [start, end] = filter.bpm_minRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
bpm_min: {
...where.bpm_min,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
bpm_min: {
...where.bpm_min,
[Op.lte]: end,
},
};
}
}
if (filter.bpm_maxRange) {
const [start, end] = filter.bpm_maxRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
bpm_max: {
...where.bpm_max,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
bpm_max: {
...where.bpm_max,
[Op.lte]: end,
},
};
}
}
if (filter.total_length_msRange) {
const [start, end] = filter.total_length_msRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
total_length_ms: {
...where.total_length_ms,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
total_length_ms: {
...where.total_length_ms,
[Op.lte]: end,
},
};
}
}
if (filter.drain_length_msRange) {
const [start, end] = filter.drain_length_msRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
drain_length_ms: {
...where.drain_length_ms,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
drain_length_ms: {
...where.drain_length_ms,
[Op.lte]: end,
},
};
}
}
if (filter.total_objectsRange) {
const [start, end] = filter.total_objectsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
total_objects: {
...where.total_objects,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
total_objects: {
...where.total_objects,
[Op.lte]: end,
},
};
}
}
if (filter.total_notesRange) {
const [start, end] = filter.total_notesRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
total_notes: {
...where.total_notes,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
total_notes: {
...where.total_notes,
[Op.lte]: end,
},
};
}
}
if (filter.total_holdsRange) {
const [start, end] = filter.total_holdsRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
total_holds: {
...where.total_holds,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
total_holds: {
...where.total_holds,
[Op.lte]: end,
},
};
}
}
if (filter.star_ratingRange) {
const [start, end] = filter.star_ratingRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
star_rating: {
...where.star_rating,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
star_rating: {
...where.star_rating,
[Op.lte]: end,
},
};
}
}
if (filter.submitted_atRange) {
const [start, end] = filter.submitted_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
submitted_at: {
...where.submitted_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
submitted_at: {
...where.submitted_at,
[Op.lte]: end,
},
};
}
}
if (filter.last_analyzed_atRange) {
const [start, end] = filter.last_analyzed_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
last_analyzed_at: {
...where.last_analyzed_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
last_analyzed_at: {
...where.last_analyzed_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.mode) {
where = {
...where,
mode: filter.mode,
};
}
if (filter.analysis_ready) {
where = {
...where,
analysis_ready: filter.analysis_ready,
};
}
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.beatmaps.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(
'beatmaps',
'difficulty_name',
query,
),
],
};
}
const records = await db.beatmaps.findAll({
attributes: [ 'id', 'difficulty_name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['difficulty_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.difficulty_name,
}));
}
};

View File

@ -0,0 +1,577 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class CountriesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const countries = await db.countries.create(
{
id: data.id || undefined,
code: data.code
||
null
,
name: data.name
||
null
,
player_count: data.player_count
||
null
,
avg_overall_skill: data.avg_overall_skill
||
null
,
global_rank: data.global_rank
||
null
,
skills_computed_at: data.skills_computed_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.countries.getTableName(),
belongsToColumn: 'flag_image',
belongsToId: countries.id,
},
data.flag_image,
options,
);
return countries;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const countriesData = data.map((item, index) => ({
id: item.id || undefined,
code: item.code
||
null
,
name: item.name
||
null
,
player_count: item.player_count
||
null
,
avg_overall_skill: item.avg_overall_skill
||
null
,
global_rank: item.global_rank
||
null
,
skills_computed_at: item.skills_computed_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const countries = await db.countries.bulkCreate(countriesData, { transaction });
// For each item created, replace relation files
for (let i = 0; i < countries.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.countries.getTableName(),
belongsToColumn: 'flag_image',
belongsToId: countries[i].id,
},
data[i].flag_image,
options,
);
}
return countries;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const countries = await db.countries.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.code !== undefined) updatePayload.code = data.code;
if (data.name !== undefined) updatePayload.name = data.name;
if (data.player_count !== undefined) updatePayload.player_count = data.player_count;
if (data.avg_overall_skill !== undefined) updatePayload.avg_overall_skill = data.avg_overall_skill;
if (data.global_rank !== undefined) updatePayload.global_rank = data.global_rank;
if (data.skills_computed_at !== undefined) updatePayload.skills_computed_at = data.skills_computed_at;
updatePayload.updatedById = currentUser.id;
await countries.update(updatePayload, {transaction});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.countries.getTableName(),
belongsToColumn: 'flag_image',
belongsToId: countries.id,
},
data.flag_image,
options,
);
return countries;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const countries = await db.countries.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of countries) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of countries) {
await record.destroy({transaction});
}
});
return countries;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const countries = await db.countries.findByPk(id, options);
await countries.update({
deletedBy: currentUser.id
}, {
transaction,
});
await countries.destroy({
transaction
});
return countries;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const countries = await db.countries.findOne(
{ where },
{ transaction },
);
if (!countries) {
return countries;
}
const output = countries.get({plain: true});
output.players_country = await countries.getPlayers_country({
transaction
});
output.analysis_jobs_country = await countries.getAnalysis_jobs_country({
transaction
});
output.country_skill_snapshots_country = await countries.getCountry_skill_snapshots_country({
transaction
});
output.country_comparisons_left_country = await countries.getCountry_comparisons_left_country({
transaction
});
output.country_comparisons_right_country = await countries.getCountry_comparisons_right_country({
transaction
});
output.flag_image = await countries.getFlag_image({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.file,
as: 'flag_image',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.code) {
where = {
...where,
[Op.and]: Utils.ilike(
'countries',
'code',
filter.code,
),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'countries',
'name',
filter.name,
),
};
}
if (filter.player_countRange) {
const [start, end] = filter.player_countRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
player_count: {
...where.player_count,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
player_count: {
...where.player_count,
[Op.lte]: end,
},
};
}
}
if (filter.avg_overall_skillRange) {
const [start, end] = filter.avg_overall_skillRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
avg_overall_skill: {
...where.avg_overall_skill,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
avg_overall_skill: {
...where.avg_overall_skill,
[Op.lte]: end,
},
};
}
}
if (filter.global_rankRange) {
const [start, end] = filter.global_rankRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
global_rank: {
...where.global_rank,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
global_rank: {
...where.global_rank,
[Op.lte]: end,
},
};
}
}
if (filter.skills_computed_atRange) {
const [start, end] = filter.skills_computed_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
skills_computed_at: {
...where.skills_computed_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
skills_computed_at: {
...where.skills_computed_at,
[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.countries.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'countries',
'name',
query,
),
],
};
}
const records = await db.countries.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,948 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Country_comparisonsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const country_comparisons = await db.country_comparisons.create(
{
id: data.id || undefined,
computed_at: data.computed_at
||
null
,
left_overall_skill: data.left_overall_skill
||
null
,
right_overall_skill: data.right_overall_skill
||
null
,
left_ln_skill: data.left_ln_skill
||
null
,
right_ln_skill: data.right_ln_skill
||
null
,
left_chordjack_skill: data.left_chordjack_skill
||
null
,
right_chordjack_skill: data.right_chordjack_skill
||
null
,
left_stream_skill: data.left_stream_skill
||
null
,
right_stream_skill: data.right_stream_skill
||
null
,
left_accuracy_skill: data.left_accuracy_skill
||
null
,
right_accuracy_skill: data.right_accuracy_skill
||
null
,
left_sv_skill: data.left_sv_skill
||
null
,
right_sv_skill: data.right_sv_skill
||
null
,
left_wins_count: data.left_wins_count
||
null
,
right_wins_count: data.right_wins_count
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await country_comparisons.setLeft_country( data.left_country || null, {
transaction,
});
await country_comparisons.setRight_country( data.right_country || null, {
transaction,
});
return country_comparisons;
}
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 country_comparisonsData = data.map((item, index) => ({
id: item.id || undefined,
computed_at: item.computed_at
||
null
,
left_overall_skill: item.left_overall_skill
||
null
,
right_overall_skill: item.right_overall_skill
||
null
,
left_ln_skill: item.left_ln_skill
||
null
,
right_ln_skill: item.right_ln_skill
||
null
,
left_chordjack_skill: item.left_chordjack_skill
||
null
,
right_chordjack_skill: item.right_chordjack_skill
||
null
,
left_stream_skill: item.left_stream_skill
||
null
,
right_stream_skill: item.right_stream_skill
||
null
,
left_accuracy_skill: item.left_accuracy_skill
||
null
,
right_accuracy_skill: item.right_accuracy_skill
||
null
,
left_sv_skill: item.left_sv_skill
||
null
,
right_sv_skill: item.right_sv_skill
||
null
,
left_wins_count: item.left_wins_count
||
null
,
right_wins_count: item.right_wins_count
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const country_comparisons = await db.country_comparisons.bulkCreate(country_comparisonsData, { transaction });
// For each item created, replace relation files
return country_comparisons;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const country_comparisons = await db.country_comparisons.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.computed_at !== undefined) updatePayload.computed_at = data.computed_at;
if (data.left_overall_skill !== undefined) updatePayload.left_overall_skill = data.left_overall_skill;
if (data.right_overall_skill !== undefined) updatePayload.right_overall_skill = data.right_overall_skill;
if (data.left_ln_skill !== undefined) updatePayload.left_ln_skill = data.left_ln_skill;
if (data.right_ln_skill !== undefined) updatePayload.right_ln_skill = data.right_ln_skill;
if (data.left_chordjack_skill !== undefined) updatePayload.left_chordjack_skill = data.left_chordjack_skill;
if (data.right_chordjack_skill !== undefined) updatePayload.right_chordjack_skill = data.right_chordjack_skill;
if (data.left_stream_skill !== undefined) updatePayload.left_stream_skill = data.left_stream_skill;
if (data.right_stream_skill !== undefined) updatePayload.right_stream_skill = data.right_stream_skill;
if (data.left_accuracy_skill !== undefined) updatePayload.left_accuracy_skill = data.left_accuracy_skill;
if (data.right_accuracy_skill !== undefined) updatePayload.right_accuracy_skill = data.right_accuracy_skill;
if (data.left_sv_skill !== undefined) updatePayload.left_sv_skill = data.left_sv_skill;
if (data.right_sv_skill !== undefined) updatePayload.right_sv_skill = data.right_sv_skill;
if (data.left_wins_count !== undefined) updatePayload.left_wins_count = data.left_wins_count;
if (data.right_wins_count !== undefined) updatePayload.right_wins_count = data.right_wins_count;
updatePayload.updatedById = currentUser.id;
await country_comparisons.update(updatePayload, {transaction});
if (data.left_country !== undefined) {
await country_comparisons.setLeft_country(
data.left_country,
{ transaction }
);
}
if (data.right_country !== undefined) {
await country_comparisons.setRight_country(
data.right_country,
{ transaction }
);
}
return country_comparisons;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const country_comparisons = await db.country_comparisons.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of country_comparisons) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of country_comparisons) {
await record.destroy({transaction});
}
});
return country_comparisons;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const country_comparisons = await db.country_comparisons.findByPk(id, options);
await country_comparisons.update({
deletedBy: currentUser.id
}, {
transaction,
});
await country_comparisons.destroy({
transaction
});
return country_comparisons;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const country_comparisons = await db.country_comparisons.findOne(
{ where },
{ transaction },
);
if (!country_comparisons) {
return country_comparisons;
}
const output = country_comparisons.get({plain: true});
output.left_country = await country_comparisons.getLeft_country({
transaction
});
output.right_country = await country_comparisons.getRight_country({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.countries,
as: 'left_country',
where: filter.left_country ? {
[Op.or]: [
{ id: { [Op.in]: filter.left_country.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.left_country.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.countries,
as: 'right_country',
where: filter.right_country ? {
[Op.or]: [
{ id: { [Op.in]: filter.right_country.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.right_country.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.computed_atRange) {
const [start, end] = filter.computed_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
computed_at: {
...where.computed_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
computed_at: {
...where.computed_at,
[Op.lte]: end,
},
};
}
}
if (filter.left_overall_skillRange) {
const [start, end] = filter.left_overall_skillRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
left_overall_skill: {
...where.left_overall_skill,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
left_overall_skill: {
...where.left_overall_skill,
[Op.lte]: end,
},
};
}
}
if (filter.right_overall_skillRange) {
const [start, end] = filter.right_overall_skillRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
right_overall_skill: {
...where.right_overall_skill,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
right_overall_skill: {
...where.right_overall_skill,
[Op.lte]: end,
},
};
}
}
if (filter.left_ln_skillRange) {
const [start, end] = filter.left_ln_skillRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
left_ln_skill: {
...where.left_ln_skill,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
left_ln_skill: {
...where.left_ln_skill,
[Op.lte]: end,
},
};
}
}
if (filter.right_ln_skillRange) {
const [start, end] = filter.right_ln_skillRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
right_ln_skill: {
...where.right_ln_skill,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
right_ln_skill: {
...where.right_ln_skill,
[Op.lte]: end,
},
};
}
}
if (filter.left_chordjack_skillRange) {
const [start, end] = filter.left_chordjack_skillRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
left_chordjack_skill: {
...where.left_chordjack_skill,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
left_chordjack_skill: {
...where.left_chordjack_skill,
[Op.lte]: end,
},
};
}
}
if (filter.right_chordjack_skillRange) {
const [start, end] = filter.right_chordjack_skillRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
right_chordjack_skill: {
...where.right_chordjack_skill,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
right_chordjack_skill: {
...where.right_chordjack_skill,
[Op.lte]: end,
},
};
}
}
if (filter.left_stream_skillRange) {
const [start, end] = filter.left_stream_skillRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
left_stream_skill: {
...where.left_stream_skill,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
left_stream_skill: {
...where.left_stream_skill,
[Op.lte]: end,
},
};
}
}
if (filter.right_stream_skillRange) {
const [start, end] = filter.right_stream_skillRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
right_stream_skill: {
...where.right_stream_skill,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
right_stream_skill: {
...where.right_stream_skill,
[Op.lte]: end,
},
};
}
}
if (filter.left_accuracy_skillRange) {
const [start, end] = filter.left_accuracy_skillRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
left_accuracy_skill: {
...where.left_accuracy_skill,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
left_accuracy_skill: {
...where.left_accuracy_skill,
[Op.lte]: end,
},
};
}
}
if (filter.right_accuracy_skillRange) {
const [start, end] = filter.right_accuracy_skillRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
right_accuracy_skill: {
...where.right_accuracy_skill,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
right_accuracy_skill: {
...where.right_accuracy_skill,
[Op.lte]: end,
},
};
}
}
if (filter.left_sv_skillRange) {
const [start, end] = filter.left_sv_skillRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
left_sv_skill: {
...where.left_sv_skill,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
left_sv_skill: {
...where.left_sv_skill,
[Op.lte]: end,
},
};
}
}
if (filter.right_sv_skillRange) {
const [start, end] = filter.right_sv_skillRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
right_sv_skill: {
...where.right_sv_skill,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
right_sv_skill: {
...where.right_sv_skill,
[Op.lte]: end,
},
};
}
}
if (filter.left_wins_countRange) {
const [start, end] = filter.left_wins_countRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
left_wins_count: {
...where.left_wins_count,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
left_wins_count: {
...where.left_wins_count,
[Op.lte]: end,
},
};
}
}
if (filter.right_wins_countRange) {
const [start, end] = filter.right_wins_countRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
right_wins_count: {
...where.right_wins_count,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
right_wins_count: {
...where.right_wins_count,
[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.country_comparisons.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(
'country_comparisons',
'computed_at',
query,
),
],
};
}
const records = await db.country_comparisons.findAll({
attributes: [ 'id', 'computed_at' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['computed_at', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.computed_at,
}));
}
};

File diff suppressed because it is too large Load Diff

View File

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

View File

@ -0,0 +1,498 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Map_filesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const map_files = await db.map_files.create(
{
id: data.id || undefined,
file_kind: data.file_kind
||
null
,
storage_path: data.storage_path
||
null
,
file_hash: data.file_hash
||
null
,
file_size_bytes: data.file_size_bytes
||
null
,
ingested_at: data.ingested_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await map_files.setBeatmap( data.beatmap || null, {
transaction,
});
return map_files;
}
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 map_filesData = data.map((item, index) => ({
id: item.id || undefined,
file_kind: item.file_kind
||
null
,
storage_path: item.storage_path
||
null
,
file_hash: item.file_hash
||
null
,
file_size_bytes: item.file_size_bytes
||
null
,
ingested_at: item.ingested_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const map_files = await db.map_files.bulkCreate(map_filesData, { transaction });
// For each item created, replace relation files
return map_files;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const map_files = await db.map_files.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.file_kind !== undefined) updatePayload.file_kind = data.file_kind;
if (data.storage_path !== undefined) updatePayload.storage_path = data.storage_path;
if (data.file_hash !== undefined) updatePayload.file_hash = data.file_hash;
if (data.file_size_bytes !== undefined) updatePayload.file_size_bytes = data.file_size_bytes;
if (data.ingested_at !== undefined) updatePayload.ingested_at = data.ingested_at;
updatePayload.updatedById = currentUser.id;
await map_files.update(updatePayload, {transaction});
if (data.beatmap !== undefined) {
await map_files.setBeatmap(
data.beatmap,
{ transaction }
);
}
return map_files;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const map_files = await db.map_files.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of map_files) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of map_files) {
await record.destroy({transaction});
}
});
return map_files;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const map_files = await db.map_files.findByPk(id, options);
await map_files.update({
deletedBy: currentUser.id
}, {
transaction,
});
await map_files.destroy({
transaction
});
return map_files;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const map_files = await db.map_files.findOne(
{ where },
{ transaction },
);
if (!map_files) {
return map_files;
}
const output = map_files.get({plain: true});
output.beatmap = await map_files.getBeatmap({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.beatmaps,
as: 'beatmap',
where: filter.beatmap ? {
[Op.or]: [
{ id: { [Op.in]: filter.beatmap.split('|').map(term => Utils.uuid(term)) } },
{
difficulty_name: {
[Op.or]: filter.beatmap.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.storage_path) {
where = {
...where,
[Op.and]: Utils.ilike(
'map_files',
'storage_path',
filter.storage_path,
),
};
}
if (filter.file_hash) {
where = {
...where,
[Op.and]: Utils.ilike(
'map_files',
'file_hash',
filter.file_hash,
),
};
}
if (filter.file_size_bytesRange) {
const [start, end] = filter.file_size_bytesRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
file_size_bytes: {
...where.file_size_bytes,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
file_size_bytes: {
...where.file_size_bytes,
[Op.lte]: end,
},
};
}
}
if (filter.ingested_atRange) {
const [start, end] = filter.ingested_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
ingested_at: {
...where.ingested_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
ingested_at: {
...where.ingested_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.file_kind) {
where = {
...where,
file_kind: filter.file_kind,
};
}
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.map_files.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(
'map_files',
'storage_path',
query,
),
],
};
}
const records = await db.map_files.findAll({
attributes: [ 'id', 'storage_path' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['storage_path', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.storage_path,
}));
}
};

File diff suppressed because it is too large Load Diff

View File

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

View File

@ -0,0 +1,820 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Player_skill_snapshotsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const player_skill_snapshots = await db.player_skill_snapshots.create(
{
id: data.id || undefined,
overall_skill: data.overall_skill
||
null
,
stream_skill: data.stream_skill
||
null
,
chordjack_skill: data.chordjack_skill
||
null
,
jackspeed_skill: data.jackspeed_skill
||
null
,
stamina_skill: data.stamina_skill
||
null
,
ln_skill: data.ln_skill
||
null
,
sv_skill: data.sv_skill
||
null
,
vibro_skill: data.vibro_skill
||
null
,
accuracy_skill: data.accuracy_skill
||
null
,
tech_skill: data.tech_skill
||
null
,
archetype: data.archetype
||
null
,
overall_rank: data.overall_rank
||
null
,
snapshot_at: data.snapshot_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await player_skill_snapshots.setPlayer( data.player || null, {
transaction,
});
return player_skill_snapshots;
}
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 player_skill_snapshotsData = data.map((item, index) => ({
id: item.id || undefined,
overall_skill: item.overall_skill
||
null
,
stream_skill: item.stream_skill
||
null
,
chordjack_skill: item.chordjack_skill
||
null
,
jackspeed_skill: item.jackspeed_skill
||
null
,
stamina_skill: item.stamina_skill
||
null
,
ln_skill: item.ln_skill
||
null
,
sv_skill: item.sv_skill
||
null
,
vibro_skill: item.vibro_skill
||
null
,
accuracy_skill: item.accuracy_skill
||
null
,
tech_skill: item.tech_skill
||
null
,
archetype: item.archetype
||
null
,
overall_rank: item.overall_rank
||
null
,
snapshot_at: item.snapshot_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const player_skill_snapshots = await db.player_skill_snapshots.bulkCreate(player_skill_snapshotsData, { transaction });
// For each item created, replace relation files
return player_skill_snapshots;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const player_skill_snapshots = await db.player_skill_snapshots.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.overall_skill !== undefined) updatePayload.overall_skill = data.overall_skill;
if (data.stream_skill !== undefined) updatePayload.stream_skill = data.stream_skill;
if (data.chordjack_skill !== undefined) updatePayload.chordjack_skill = data.chordjack_skill;
if (data.jackspeed_skill !== undefined) updatePayload.jackspeed_skill = data.jackspeed_skill;
if (data.stamina_skill !== undefined) updatePayload.stamina_skill = data.stamina_skill;
if (data.ln_skill !== undefined) updatePayload.ln_skill = data.ln_skill;
if (data.sv_skill !== undefined) updatePayload.sv_skill = data.sv_skill;
if (data.vibro_skill !== undefined) updatePayload.vibro_skill = data.vibro_skill;
if (data.accuracy_skill !== undefined) updatePayload.accuracy_skill = data.accuracy_skill;
if (data.tech_skill !== undefined) updatePayload.tech_skill = data.tech_skill;
if (data.archetype !== undefined) updatePayload.archetype = data.archetype;
if (data.overall_rank !== undefined) updatePayload.overall_rank = data.overall_rank;
if (data.snapshot_at !== undefined) updatePayload.snapshot_at = data.snapshot_at;
updatePayload.updatedById = currentUser.id;
await player_skill_snapshots.update(updatePayload, {transaction});
if (data.player !== undefined) {
await player_skill_snapshots.setPlayer(
data.player,
{ transaction }
);
}
return player_skill_snapshots;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const player_skill_snapshots = await db.player_skill_snapshots.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of player_skill_snapshots) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of player_skill_snapshots) {
await record.destroy({transaction});
}
});
return player_skill_snapshots;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const player_skill_snapshots = await db.player_skill_snapshots.findByPk(id, options);
await player_skill_snapshots.update({
deletedBy: currentUser.id
}, {
transaction,
});
await player_skill_snapshots.destroy({
transaction
});
return player_skill_snapshots;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const player_skill_snapshots = await db.player_skill_snapshots.findOne(
{ where },
{ transaction },
);
if (!player_skill_snapshots) {
return player_skill_snapshots;
}
const output = player_skill_snapshots.get({plain: true});
output.player = await player_skill_snapshots.getPlayer({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.players,
as: 'player',
where: filter.player ? {
[Op.or]: [
{ id: { [Op.in]: filter.player.split('|').map(term => Utils.uuid(term)) } },
{
username: {
[Op.or]: filter.player.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.overall_skillRange) {
const [start, end] = filter.overall_skillRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
overall_skill: {
...where.overall_skill,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
overall_skill: {
...where.overall_skill,
[Op.lte]: end,
},
};
}
}
if (filter.stream_skillRange) {
const [start, end] = filter.stream_skillRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
stream_skill: {
...where.stream_skill,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
stream_skill: {
...where.stream_skill,
[Op.lte]: end,
},
};
}
}
if (filter.chordjack_skillRange) {
const [start, end] = filter.chordjack_skillRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
chordjack_skill: {
...where.chordjack_skill,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
chordjack_skill: {
...where.chordjack_skill,
[Op.lte]: end,
},
};
}
}
if (filter.jackspeed_skillRange) {
const [start, end] = filter.jackspeed_skillRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
jackspeed_skill: {
...where.jackspeed_skill,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
jackspeed_skill: {
...where.jackspeed_skill,
[Op.lte]: end,
},
};
}
}
if (filter.stamina_skillRange) {
const [start, end] = filter.stamina_skillRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
stamina_skill: {
...where.stamina_skill,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
stamina_skill: {
...where.stamina_skill,
[Op.lte]: end,
},
};
}
}
if (filter.ln_skillRange) {
const [start, end] = filter.ln_skillRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
ln_skill: {
...where.ln_skill,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
ln_skill: {
...where.ln_skill,
[Op.lte]: end,
},
};
}
}
if (filter.sv_skillRange) {
const [start, end] = filter.sv_skillRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sv_skill: {
...where.sv_skill,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sv_skill: {
...where.sv_skill,
[Op.lte]: end,
},
};
}
}
if (filter.vibro_skillRange) {
const [start, end] = filter.vibro_skillRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
vibro_skill: {
...where.vibro_skill,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
vibro_skill: {
...where.vibro_skill,
[Op.lte]: end,
},
};
}
}
if (filter.accuracy_skillRange) {
const [start, end] = filter.accuracy_skillRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
accuracy_skill: {
...where.accuracy_skill,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
accuracy_skill: {
...where.accuracy_skill,
[Op.lte]: end,
},
};
}
}
if (filter.tech_skillRange) {
const [start, end] = filter.tech_skillRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
tech_skill: {
...where.tech_skill,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
tech_skill: {
...where.tech_skill,
[Op.lte]: end,
},
};
}
}
if (filter.overall_rankRange) {
const [start, end] = filter.overall_rankRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
overall_rank: {
...where.overall_rank,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
overall_rank: {
...where.overall_rank,
[Op.lte]: end,
},
};
}
}
if (filter.snapshot_atRange) {
const [start, end] = filter.snapshot_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
snapshot_at: {
...where.snapshot_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
snapshot_at: {
...where.snapshot_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.archetype) {
where = {
...where,
archetype: filter.archetype,
};
}
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.player_skill_snapshots.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(
'player_skill_snapshots',
'snapshot_at',
query,
),
],
};
}
const records = await db.player_skill_snapshots.findAll({
attributes: [ 'id', 'snapshot_at' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['snapshot_at', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.snapshot_at,
}));
}
};

View File

@ -0,0 +1,524 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Player_top_playsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const player_top_plays = await db.player_top_plays.create(
{
id: data.id || undefined,
skill_type: data.skill_type
||
null
,
rank_in_skill: data.rank_in_skill
||
null
,
contribution_value: data.contribution_value
||
null
,
selected_at: data.selected_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await player_top_plays.setPlayer( data.player || null, {
transaction,
});
await player_top_plays.setScore( data.score || null, {
transaction,
});
return player_top_plays;
}
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 player_top_playsData = data.map((item, index) => ({
id: item.id || undefined,
skill_type: item.skill_type
||
null
,
rank_in_skill: item.rank_in_skill
||
null
,
contribution_value: item.contribution_value
||
null
,
selected_at: item.selected_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const player_top_plays = await db.player_top_plays.bulkCreate(player_top_playsData, { transaction });
// For each item created, replace relation files
return player_top_plays;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const player_top_plays = await db.player_top_plays.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.skill_type !== undefined) updatePayload.skill_type = data.skill_type;
if (data.rank_in_skill !== undefined) updatePayload.rank_in_skill = data.rank_in_skill;
if (data.contribution_value !== undefined) updatePayload.contribution_value = data.contribution_value;
if (data.selected_at !== undefined) updatePayload.selected_at = data.selected_at;
updatePayload.updatedById = currentUser.id;
await player_top_plays.update(updatePayload, {transaction});
if (data.player !== undefined) {
await player_top_plays.setPlayer(
data.player,
{ transaction }
);
}
if (data.score !== undefined) {
await player_top_plays.setScore(
data.score,
{ transaction }
);
}
return player_top_plays;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const player_top_plays = await db.player_top_plays.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of player_top_plays) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of player_top_plays) {
await record.destroy({transaction});
}
});
return player_top_plays;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const player_top_plays = await db.player_top_plays.findByPk(id, options);
await player_top_plays.update({
deletedBy: currentUser.id
}, {
transaction,
});
await player_top_plays.destroy({
transaction
});
return player_top_plays;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const player_top_plays = await db.player_top_plays.findOne(
{ where },
{ transaction },
);
if (!player_top_plays) {
return player_top_plays;
}
const output = player_top_plays.get({plain: true});
output.player = await player_top_plays.getPlayer({
transaction
});
output.score = await player_top_plays.getScore({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.players,
as: 'player',
where: filter.player ? {
[Op.or]: [
{ id: { [Op.in]: filter.player.split('|').map(term => Utils.uuid(term)) } },
{
username: {
[Op.or]: filter.player.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.scores,
as: 'score',
where: filter.score ? {
[Op.or]: [
{ id: { [Op.in]: filter.score.split('|').map(term => Utils.uuid(term)) } },
{
scoring_type: {
[Op.or]: filter.score.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.rank_in_skillRange) {
const [start, end] = filter.rank_in_skillRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
rank_in_skill: {
...where.rank_in_skill,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
rank_in_skill: {
...where.rank_in_skill,
[Op.lte]: end,
},
};
}
}
if (filter.contribution_valueRange) {
const [start, end] = filter.contribution_valueRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
contribution_value: {
...where.contribution_value,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
contribution_value: {
...where.contribution_value,
[Op.lte]: end,
},
};
}
}
if (filter.selected_atRange) {
const [start, end] = filter.selected_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
selected_at: {
...where.selected_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
selected_at: {
...where.selected_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.skill_type) {
where = {
...where,
skill_type: filter.skill_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.player_top_plays.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(
'player_top_plays',
'skill_type',
query,
),
],
};
}
const records = await db.player_top_plays.findAll({
attributes: [ 'id', 'skill_type' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['skill_type', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.skill_type,
}));
}
};

View File

@ -0,0 +1,956 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class PlayersDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const players = await db.players.create(
{
id: data.id || undefined,
osu_user_number: data.osu_user_number
||
null
,
username: data.username
||
null
,
archetype: data.archetype
||
null
,
overall_skill: data.overall_skill
||
null
,
stream_skill: data.stream_skill
||
null
,
chordjack_skill: data.chordjack_skill
||
null
,
jackspeed_skill: data.jackspeed_skill
||
null
,
stamina_skill: data.stamina_skill
||
null
,
ln_skill: data.ln_skill
||
null
,
sv_skill: data.sv_skill
||
null
,
vibro_skill: data.vibro_skill
||
null
,
accuracy_skill: data.accuracy_skill
||
null
,
overall_rank: data.overall_rank
||
null
,
country_rank: data.country_rank
||
null
,
profile_last_synced_at: data.profile_last_synced_at
||
null
,
skills_computed_at: data.skills_computed_at
||
null
,
is_tracked: data.is_tracked
||
false
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await players.setCountry( data.country || null, {
transaction,
});
return players;
}
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 playersData = data.map((item, index) => ({
id: item.id || undefined,
osu_user_number: item.osu_user_number
||
null
,
username: item.username
||
null
,
archetype: item.archetype
||
null
,
overall_skill: item.overall_skill
||
null
,
stream_skill: item.stream_skill
||
null
,
chordjack_skill: item.chordjack_skill
||
null
,
jackspeed_skill: item.jackspeed_skill
||
null
,
stamina_skill: item.stamina_skill
||
null
,
ln_skill: item.ln_skill
||
null
,
sv_skill: item.sv_skill
||
null
,
vibro_skill: item.vibro_skill
||
null
,
accuracy_skill: item.accuracy_skill
||
null
,
overall_rank: item.overall_rank
||
null
,
country_rank: item.country_rank
||
null
,
profile_last_synced_at: item.profile_last_synced_at
||
null
,
skills_computed_at: item.skills_computed_at
||
null
,
is_tracked: item.is_tracked
||
false
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const players = await db.players.bulkCreate(playersData, { transaction });
// For each item created, replace relation files
return players;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const players = await db.players.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.osu_user_number !== undefined) updatePayload.osu_user_number = data.osu_user_number;
if (data.username !== undefined) updatePayload.username = data.username;
if (data.archetype !== undefined) updatePayload.archetype = data.archetype;
if (data.overall_skill !== undefined) updatePayload.overall_skill = data.overall_skill;
if (data.stream_skill !== undefined) updatePayload.stream_skill = data.stream_skill;
if (data.chordjack_skill !== undefined) updatePayload.chordjack_skill = data.chordjack_skill;
if (data.jackspeed_skill !== undefined) updatePayload.jackspeed_skill = data.jackspeed_skill;
if (data.stamina_skill !== undefined) updatePayload.stamina_skill = data.stamina_skill;
if (data.ln_skill !== undefined) updatePayload.ln_skill = data.ln_skill;
if (data.sv_skill !== undefined) updatePayload.sv_skill = data.sv_skill;
if (data.vibro_skill !== undefined) updatePayload.vibro_skill = data.vibro_skill;
if (data.accuracy_skill !== undefined) updatePayload.accuracy_skill = data.accuracy_skill;
if (data.overall_rank !== undefined) updatePayload.overall_rank = data.overall_rank;
if (data.country_rank !== undefined) updatePayload.country_rank = data.country_rank;
if (data.profile_last_synced_at !== undefined) updatePayload.profile_last_synced_at = data.profile_last_synced_at;
if (data.skills_computed_at !== undefined) updatePayload.skills_computed_at = data.skills_computed_at;
if (data.is_tracked !== undefined) updatePayload.is_tracked = data.is_tracked;
updatePayload.updatedById = currentUser.id;
await players.update(updatePayload, {transaction});
if (data.country !== undefined) {
await players.setCountry(
data.country,
{ transaction }
);
}
return players;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const players = await db.players.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of players) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of players) {
await record.destroy({transaction});
}
});
return players;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const players = await db.players.findByPk(id, options);
await players.update({
deletedBy: currentUser.id
}, {
transaction,
});
await players.destroy({
transaction
});
return players;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const players = await db.players.findOne(
{ where },
{ transaction },
);
if (!players) {
return players;
}
const output = players.get({plain: true});
output.analysis_jobs_player = await players.getAnalysis_jobs_player({
transaction
});
output.scores_player = await players.getScores_player({
transaction
});
output.player_top_plays_player = await players.getPlayer_top_plays_player({
transaction
});
output.player_skill_snapshots_player = await players.getPlayer_skill_snapshots_player({
transaction
});
output.country = await players.getCountry({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.countries,
as: 'country',
where: filter.country ? {
[Op.or]: [
{ id: { [Op.in]: filter.country.split('|').map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: filter.country.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.username) {
where = {
...where,
[Op.and]: Utils.ilike(
'players',
'username',
filter.username,
),
};
}
if (filter.osu_user_numberRange) {
const [start, end] = filter.osu_user_numberRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
osu_user_number: {
...where.osu_user_number,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
osu_user_number: {
...where.osu_user_number,
[Op.lte]: end,
},
};
}
}
if (filter.overall_skillRange) {
const [start, end] = filter.overall_skillRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
overall_skill: {
...where.overall_skill,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
overall_skill: {
...where.overall_skill,
[Op.lte]: end,
},
};
}
}
if (filter.stream_skillRange) {
const [start, end] = filter.stream_skillRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
stream_skill: {
...where.stream_skill,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
stream_skill: {
...where.stream_skill,
[Op.lte]: end,
},
};
}
}
if (filter.chordjack_skillRange) {
const [start, end] = filter.chordjack_skillRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
chordjack_skill: {
...where.chordjack_skill,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
chordjack_skill: {
...where.chordjack_skill,
[Op.lte]: end,
},
};
}
}
if (filter.jackspeed_skillRange) {
const [start, end] = filter.jackspeed_skillRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
jackspeed_skill: {
...where.jackspeed_skill,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
jackspeed_skill: {
...where.jackspeed_skill,
[Op.lte]: end,
},
};
}
}
if (filter.stamina_skillRange) {
const [start, end] = filter.stamina_skillRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
stamina_skill: {
...where.stamina_skill,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
stamina_skill: {
...where.stamina_skill,
[Op.lte]: end,
},
};
}
}
if (filter.ln_skillRange) {
const [start, end] = filter.ln_skillRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
ln_skill: {
...where.ln_skill,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
ln_skill: {
...where.ln_skill,
[Op.lte]: end,
},
};
}
}
if (filter.sv_skillRange) {
const [start, end] = filter.sv_skillRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
sv_skill: {
...where.sv_skill,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
sv_skill: {
...where.sv_skill,
[Op.lte]: end,
},
};
}
}
if (filter.vibro_skillRange) {
const [start, end] = filter.vibro_skillRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
vibro_skill: {
...where.vibro_skill,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
vibro_skill: {
...where.vibro_skill,
[Op.lte]: end,
},
};
}
}
if (filter.accuracy_skillRange) {
const [start, end] = filter.accuracy_skillRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
accuracy_skill: {
...where.accuracy_skill,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
accuracy_skill: {
...where.accuracy_skill,
[Op.lte]: end,
},
};
}
}
if (filter.overall_rankRange) {
const [start, end] = filter.overall_rankRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
overall_rank: {
...where.overall_rank,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
overall_rank: {
...where.overall_rank,
[Op.lte]: end,
},
};
}
}
if (filter.country_rankRange) {
const [start, end] = filter.country_rankRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
country_rank: {
...where.country_rank,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
country_rank: {
...where.country_rank,
[Op.lte]: end,
},
};
}
}
if (filter.profile_last_synced_atRange) {
const [start, end] = filter.profile_last_synced_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
profile_last_synced_at: {
...where.profile_last_synced_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
profile_last_synced_at: {
...where.profile_last_synced_at,
[Op.lte]: end,
},
};
}
}
if (filter.skills_computed_atRange) {
const [start, end] = filter.skills_computed_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
skills_computed_at: {
...where.skills_computed_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
skills_computed_at: {
...where.skills_computed_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.archetype) {
where = {
...where,
archetype: filter.archetype,
};
}
if (filter.is_tracked) {
where = {
...where,
is_tracked: filter.is_tracked,
};
}
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.players.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(
'players',
'username',
query,
),
],
};
}
const records = await db.players.findAll({
attributes: [ 'id', 'username' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['username', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.username,
}));
}
};

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

@ -0,0 +1,413 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class RolesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const roles = await db.roles.create(
{
id: data.id || undefined,
name: data.name
||
null
,
role_customization: data.role_customization
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await roles.setPermissions(data.permissions || [], {
transaction,
});
return roles;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const rolesData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name
||
null
,
role_customization: item.role_customization
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const roles = await db.roles.bulkCreate(rolesData, { transaction });
// For each item created, replace relation files
return roles;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const roles = await db.roles.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.role_customization !== undefined) updatePayload.role_customization = data.role_customization;
updatePayload.updatedById = currentUser.id;
await roles.update(updatePayload, {transaction});
if (data.permissions !== undefined) {
await roles.setPermissions(data.permissions, { transaction });
}
return roles;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const roles = await db.roles.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of roles) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of roles) {
await record.destroy({transaction});
}
});
return roles;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const roles = await db.roles.findByPk(id, options);
await roles.update({
deletedBy: currentUser.id
}, {
transaction,
});
await roles.destroy({
transaction
});
return roles;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const roles = await db.roles.findOne(
{ where },
{ transaction },
);
if (!roles) {
return roles;
}
const output = roles.get({plain: true});
output.users_app_role = await roles.getUsers_app_role({
transaction
});
output.permissions = await roles.getPermissions({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.permissions,
as: 'permissions',
required: false,
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike(
'roles',
'name',
filter.name,
),
};
}
if (filter.role_customization) {
where = {
...where,
[Op.and]: Utils.ilike(
'roles',
'role_customization',
filter.role_customization,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.permissions) {
const searchTerms = filter.permissions.split('|');
include = [
{
model: db.permissions,
as: 'permissions_filter',
required: searchTerms.length > 0,
where: searchTerms.length > 0 ? {
[Op.or]: [
{ id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
{
name: {
[Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
}
}
]
} : undefined
},
...include,
]
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order: filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.roles.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset, ) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike(
'roles',
'name',
query,
),
],
};
}
const records = await db.roles.findAll({
attributes: [ 'id', 'name' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.name,
}));
}
};

View File

@ -0,0 +1,524 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Score_skill_contributionsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const score_skill_contributions = await db.score_skill_contributions.create(
{
id: data.id || undefined,
skill_type: data.skill_type
||
null
,
map_skill_value: data.map_skill_value
||
null
,
weighted_skill_value: data.weighted_skill_value
||
null
,
weight_used: data.weight_used
||
null
,
computed_at: data.computed_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await score_skill_contributions.setScore( data.score || null, {
transaction,
});
return score_skill_contributions;
}
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 score_skill_contributionsData = data.map((item, index) => ({
id: item.id || undefined,
skill_type: item.skill_type
||
null
,
map_skill_value: item.map_skill_value
||
null
,
weighted_skill_value: item.weighted_skill_value
||
null
,
weight_used: item.weight_used
||
null
,
computed_at: item.computed_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const score_skill_contributions = await db.score_skill_contributions.bulkCreate(score_skill_contributionsData, { transaction });
// For each item created, replace relation files
return score_skill_contributions;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const score_skill_contributions = await db.score_skill_contributions.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.skill_type !== undefined) updatePayload.skill_type = data.skill_type;
if (data.map_skill_value !== undefined) updatePayload.map_skill_value = data.map_skill_value;
if (data.weighted_skill_value !== undefined) updatePayload.weighted_skill_value = data.weighted_skill_value;
if (data.weight_used !== undefined) updatePayload.weight_used = data.weight_used;
if (data.computed_at !== undefined) updatePayload.computed_at = data.computed_at;
updatePayload.updatedById = currentUser.id;
await score_skill_contributions.update(updatePayload, {transaction});
if (data.score !== undefined) {
await score_skill_contributions.setScore(
data.score,
{ transaction }
);
}
return score_skill_contributions;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const score_skill_contributions = await db.score_skill_contributions.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of score_skill_contributions) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of score_skill_contributions) {
await record.destroy({transaction});
}
});
return score_skill_contributions;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const score_skill_contributions = await db.score_skill_contributions.findByPk(id, options);
await score_skill_contributions.update({
deletedBy: currentUser.id
}, {
transaction,
});
await score_skill_contributions.destroy({
transaction
});
return score_skill_contributions;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const score_skill_contributions = await db.score_skill_contributions.findOne(
{ where },
{ transaction },
);
if (!score_skill_contributions) {
return score_skill_contributions;
}
const output = score_skill_contributions.get({plain: true});
output.score = await score_skill_contributions.getScore({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.scores,
as: 'score',
where: filter.score ? {
[Op.or]: [
{ id: { [Op.in]: filter.score.split('|').map(term => Utils.uuid(term)) } },
{
scoring_type: {
[Op.or]: filter.score.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.map_skill_valueRange) {
const [start, end] = filter.map_skill_valueRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
map_skill_value: {
...where.map_skill_value,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
map_skill_value: {
...where.map_skill_value,
[Op.lte]: end,
},
};
}
}
if (filter.weighted_skill_valueRange) {
const [start, end] = filter.weighted_skill_valueRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
weighted_skill_value: {
...where.weighted_skill_value,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
weighted_skill_value: {
...where.weighted_skill_value,
[Op.lte]: end,
},
};
}
}
if (filter.weight_usedRange) {
const [start, end] = filter.weight_usedRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
weight_used: {
...where.weight_used,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
weight_used: {
...where.weight_used,
[Op.lte]: end,
},
};
}
}
if (filter.computed_atRange) {
const [start, end] = filter.computed_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
computed_at: {
...where.computed_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
computed_at: {
...where.computed_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.skill_type) {
where = {
...where,
skill_type: filter.skill_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.score_skill_contributions.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(
'score_skill_contributions',
'skill_type',
query,
),
],
};
}
const records = await db.score_skill_contributions.findAll({
attributes: [ 'id', 'skill_type' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['skill_type', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.skill_type,
}));
}
};

View File

@ -0,0 +1,870 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class ScoresDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const scores = await db.scores.create(
{
id: data.id || undefined,
osu_score_number: data.osu_score_number
||
null
,
scoring_type: data.scoring_type
||
null
,
accuracy: data.accuracy
||
null
,
max_combo: data.max_combo
||
null
,
grade: data.grade
||
null
,
count_300: data.count_300
||
null
,
count_200: data.count_200
||
null
,
count_100: data.count_100
||
null
,
count_50: data.count_50
||
null
,
count_miss: data.count_miss
||
null
,
is_full_combo: data.is_full_combo
||
false
,
score_weight: data.score_weight
||
null
,
played_at: data.played_at
||
null
,
ingested_at: data.ingested_at
||
null
,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await scores.setPlayer( data.player || null, {
transaction,
});
await scores.setBeatmap( data.beatmap || null, {
transaction,
});
return scores;
}
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 scoresData = data.map((item, index) => ({
id: item.id || undefined,
osu_score_number: item.osu_score_number
||
null
,
scoring_type: item.scoring_type
||
null
,
accuracy: item.accuracy
||
null
,
max_combo: item.max_combo
||
null
,
grade: item.grade
||
null
,
count_300: item.count_300
||
null
,
count_200: item.count_200
||
null
,
count_100: item.count_100
||
null
,
count_50: item.count_50
||
null
,
count_miss: item.count_miss
||
null
,
is_full_combo: item.is_full_combo
||
false
,
score_weight: item.score_weight
||
null
,
played_at: item.played_at
||
null
,
ingested_at: item.ingested_at
||
null
,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const scores = await db.scores.bulkCreate(scoresData, { transaction });
// For each item created, replace relation files
return scores;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const scores = await db.scores.findByPk(id, {}, {transaction});
const updatePayload = {};
if (data.osu_score_number !== undefined) updatePayload.osu_score_number = data.osu_score_number;
if (data.scoring_type !== undefined) updatePayload.scoring_type = data.scoring_type;
if (data.accuracy !== undefined) updatePayload.accuracy = data.accuracy;
if (data.max_combo !== undefined) updatePayload.max_combo = data.max_combo;
if (data.grade !== undefined) updatePayload.grade = data.grade;
if (data.count_300 !== undefined) updatePayload.count_300 = data.count_300;
if (data.count_200 !== undefined) updatePayload.count_200 = data.count_200;
if (data.count_100 !== undefined) updatePayload.count_100 = data.count_100;
if (data.count_50 !== undefined) updatePayload.count_50 = data.count_50;
if (data.count_miss !== undefined) updatePayload.count_miss = data.count_miss;
if (data.is_full_combo !== undefined) updatePayload.is_full_combo = data.is_full_combo;
if (data.score_weight !== undefined) updatePayload.score_weight = data.score_weight;
if (data.played_at !== undefined) updatePayload.played_at = data.played_at;
if (data.ingested_at !== undefined) updatePayload.ingested_at = data.ingested_at;
updatePayload.updatedById = currentUser.id;
await scores.update(updatePayload, {transaction});
if (data.player !== undefined) {
await scores.setPlayer(
data.player,
{ transaction }
);
}
if (data.beatmap !== undefined) {
await scores.setBeatmap(
data.beatmap,
{ transaction }
);
}
return scores;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const scores = await db.scores.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of scores) {
await record.update(
{deletedBy: currentUser.id},
{transaction}
);
}
for (const record of scores) {
await record.destroy({transaction});
}
});
return scores;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || {id: null};
const transaction = (options && options.transaction) || undefined;
const scores = await db.scores.findByPk(id, options);
await scores.update({
deletedBy: currentUser.id
}, {
transaction,
});
await scores.destroy({
transaction
});
return scores;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const scores = await db.scores.findOne(
{ where },
{ transaction },
);
if (!scores) {
return scores;
}
const output = scores.get({plain: true});
output.score_skill_contributions_score = await scores.getScore_skill_contributions_score({
transaction
});
output.player_top_plays_score = await scores.getPlayer_top_plays_score({
transaction
});
output.player = await scores.getPlayer({
transaction
});
output.beatmap = await scores.getBeatmap({
transaction
});
return output;
}
static async findAll(
filter,
options
) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.players,
as: 'player',
where: filter.player ? {
[Op.or]: [
{ id: { [Op.in]: filter.player.split('|').map(term => Utils.uuid(term)) } },
{
username: {
[Op.or]: filter.player.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
{
model: db.beatmaps,
as: 'beatmap',
where: filter.beatmap ? {
[Op.or]: [
{ id: { [Op.in]: filter.beatmap.split('|').map(term => Utils.uuid(term)) } },
{
difficulty_name: {
[Op.or]: filter.beatmap.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
}
},
]
} : {},
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.osu_score_numberRange) {
const [start, end] = filter.osu_score_numberRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
osu_score_number: {
...where.osu_score_number,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
osu_score_number: {
...where.osu_score_number,
[Op.lte]: end,
},
};
}
}
if (filter.accuracyRange) {
const [start, end] = filter.accuracyRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
accuracy: {
...where.accuracy,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
accuracy: {
...where.accuracy,
[Op.lte]: end,
},
};
}
}
if (filter.max_comboRange) {
const [start, end] = filter.max_comboRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
max_combo: {
...where.max_combo,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
max_combo: {
...where.max_combo,
[Op.lte]: end,
},
};
}
}
if (filter.count_300Range) {
const [start, end] = filter.count_300Range;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
count_300: {
...where.count_300,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
count_300: {
...where.count_300,
[Op.lte]: end,
},
};
}
}
if (filter.count_200Range) {
const [start, end] = filter.count_200Range;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
count_200: {
...where.count_200,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
count_200: {
...where.count_200,
[Op.lte]: end,
},
};
}
}
if (filter.count_100Range) {
const [start, end] = filter.count_100Range;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
count_100: {
...where.count_100,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
count_100: {
...where.count_100,
[Op.lte]: end,
},
};
}
}
if (filter.count_50Range) {
const [start, end] = filter.count_50Range;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
count_50: {
...where.count_50,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
count_50: {
...where.count_50,
[Op.lte]: end,
},
};
}
}
if (filter.count_missRange) {
const [start, end] = filter.count_missRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
count_miss: {
...where.count_miss,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
count_miss: {
...where.count_miss,
[Op.lte]: end,
},
};
}
}
if (filter.score_weightRange) {
const [start, end] = filter.score_weightRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
score_weight: {
...where.score_weight,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
score_weight: {
...where.score_weight,
[Op.lte]: end,
},
};
}
}
if (filter.played_atRange) {
const [start, end] = filter.played_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
played_at: {
...where.played_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
played_at: {
...where.played_at,
[Op.lte]: end,
},
};
}
}
if (filter.ingested_atRange) {
const [start, end] = filter.ingested_atRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
ingested_at: {
...where.ingested_at,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
ingested_at: {
...where.ingested_at,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true'
};
}
if (filter.scoring_type) {
where = {
...where,
scoring_type: filter.scoring_type,
};
}
if (filter.grade) {
where = {
...where,
grade: filter.grade,
};
}
if (filter.is_full_combo) {
where = {
...where,
is_full_combo: filter.is_full_combo,
};
}
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.scores.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(
'scores',
'scoring_type',
query,
),
],
};
}
const records = await db.scores.findAll({
attributes: [ 'id', 'scoring_type' ],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['scoring_type', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.scoring_type,
}));
}
};

View File

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

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

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

View File

@ -0,0 +1,33 @@
module.exports = {
production: {
dialect: 'postgres',
username: process.env.DB_USER,
password: process.env.DB_PASS,
database: process.env.DB_NAME,
host: process.env.DB_HOST,
port: process.env.DB_PORT,
logging: console.log,
seederStorage: 'sequelize',
},
development: {
username: 'postgres',
dialect: 'postgres',
password: '',
database: 'db_maniaskills',
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,124 @@
module.exports = {
async up(queryInterface, Sequelize) {
const transaction = await queryInterface.sequelize.transaction();
try {
const rows = await queryInterface.sequelize.query(
"SELECT to_regclass('public.files') AS regclass_name;",
{
transaction,
type: Sequelize.QueryTypes.SELECT,
},
);
const tableName = rows[0].regclass_name;
if (tableName) {
await transaction.commit();
return;
}
await queryInterface.createTable(
'files',
{
id: {
type: Sequelize.DataTypes.UUID,
defaultValue: Sequelize.DataTypes.UUIDV4,
primaryKey: true,
},
belongsTo: {
type: Sequelize.DataTypes.STRING(255),
allowNull: true,
},
belongsToId: {
type: Sequelize.DataTypes.UUID,
allowNull: true,
},
belongsToColumn: {
type: Sequelize.DataTypes.STRING(255),
allowNull: true,
},
name: {
type: Sequelize.DataTypes.STRING(2083),
allowNull: false,
},
sizeInBytes: {
type: Sequelize.DataTypes.INTEGER,
allowNull: true,
},
privateUrl: {
type: Sequelize.DataTypes.STRING(2083),
allowNull: true,
},
publicUrl: {
type: Sequelize.DataTypes.STRING(2083),
allowNull: false,
},
createdAt: {
type: Sequelize.DataTypes.DATE,
allowNull: false,
},
updatedAt: {
type: Sequelize.DataTypes.DATE,
allowNull: false,
},
deletedAt: {
type: Sequelize.DataTypes.DATE,
allowNull: true,
},
createdById: {
type: Sequelize.DataTypes.UUID,
allowNull: true,
references: {
key: 'id',
model: 'users',
},
onDelete: 'SET NULL',
onUpdate: 'CASCADE',
},
updatedById: {
type: Sequelize.DataTypes.UUID,
allowNull: true,
references: {
key: 'id',
model: 'users',
},
onDelete: 'SET NULL',
onUpdate: 'CASCADE',
},
},
{ transaction },
);
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
async down(queryInterface, Sequelize) {
const transaction = await queryInterface.sequelize.transaction();
try {
const rows = await queryInterface.sequelize.query(
"SELECT to_regclass('public.files') AS regclass_name;",
{
transaction,
type: Sequelize.QueryTypes.SELECT,
},
);
const tableName = rows[0].regclass_name;
if (!tableName) {
await transaction.commit();
return;
}
await queryInterface.dropTable('files', { transaction });
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
};

View File

@ -0,0 +1,77 @@
module.exports = {
async up(queryInterface, Sequelize) {
const transaction = await queryInterface.sequelize.transaction();
try {
const rows = await queryInterface.sequelize.query(
"SELECT to_regclass('public.\"usersCustom_permissionsPermissions\"') AS regclass_name;",
{
transaction,
type: Sequelize.QueryTypes.SELECT,
},
);
const tableName = rows[0].regclass_name;
if (tableName) {
await transaction.commit();
return;
}
await queryInterface.createTable(
'usersCustom_permissionsPermissions',
{
createdAt: {
type: Sequelize.DataTypes.DATE,
allowNull: false,
},
updatedAt: {
type: Sequelize.DataTypes.DATE,
allowNull: false,
},
users_custom_permissionsId: {
type: Sequelize.DataTypes.UUID,
allowNull: false,
primaryKey: true,
},
permissionId: {
type: Sequelize.DataTypes.UUID,
allowNull: false,
primaryKey: true,
},
},
{ transaction },
);
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
async down(queryInterface, Sequelize) {
const transaction = await queryInterface.sequelize.transaction();
try {
const rows = await queryInterface.sequelize.query(
"SELECT to_regclass('public.\"usersCustom_permissionsPermissions\"') AS regclass_name;",
{
transaction,
type: Sequelize.QueryTypes.SELECT,
},
);
const tableName = rows[0].regclass_name;
if (!tableName) {
await transaction.commit();
return;
}
await queryInterface.dropTable('usersCustom_permissionsPermissions', { transaction });
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
},
};

View File

@ -0,0 +1,196 @@
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 analysis_jobs = sequelize.define(
'analysis_jobs',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
job_type: {
type: DataTypes.ENUM,
values: [
"extract_osz",
"parse_osu",
"run_msd",
"custom_analyze",
"normalize",
"store_skills",
"sync_osu_api",
"aggregate_player_skills",
"aggregate_country_skills"
],
},
status: {
type: DataTypes.ENUM,
values: [
"queued",
"running",
"succeeded",
"failed",
"canceled"
],
},
started_at: {
type: DataTypes.DATE,
},
finished_at: {
type: DataTypes.DATE,
},
attempt_number: {
type: DataTypes.INTEGER,
},
error_message: {
type: DataTypes.TEXT,
},
duration_seconds: {
type: DataTypes.DECIMAL,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
analysis_jobs.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.analysis_jobs.belongsTo(db.beatmaps, {
as: 'beatmap',
foreignKey: {
name: 'beatmapId',
},
constraints: false,
});
db.analysis_jobs.belongsTo(db.players, {
as: 'player',
foreignKey: {
name: 'playerId',
},
constraints: false,
});
db.analysis_jobs.belongsTo(db.countries, {
as: 'country',
foreignKey: {
name: 'countryId',
},
constraints: false,
});
db.analysis_jobs.belongsTo(db.users, {
as: 'createdBy',
});
db.analysis_jobs.belongsTo(db.users, {
as: 'updatedBy',
});
};
return analysis_jobs;
};

View File

@ -0,0 +1,160 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const beatmap_sets = sequelize.define(
'beatmap_sets',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
osu_set_number: {
type: DataTypes.INTEGER,
},
artist: {
type: DataTypes.TEXT,
},
title: {
type: DataTypes.TEXT,
},
source: {
type: DataTypes.TEXT,
},
tags: {
type: DataTypes.TEXT,
},
status: {
type: DataTypes.ENUM,
values: [
"ranked",
"loved",
"qualified",
"approved",
"pending",
"graveyard"
],
},
ranked_at: {
type: DataTypes.DATE,
},
last_checked_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
beatmap_sets.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.beatmap_sets.hasMany(db.beatmaps, {
as: 'beatmaps_beatmap_set',
foreignKey: {
name: 'beatmap_setId',
},
constraints: false,
});
//end loop
db.beatmap_sets.belongsTo(db.users, {
as: 'createdBy',
});
db.beatmap_sets.belongsTo(db.users, {
as: 'updatedBy',
});
};
return beatmap_sets;
};

View File

@ -0,0 +1,229 @@
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 beatmaps = sequelize.define(
'beatmaps',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
osu_map_number: {
type: DataTypes.INTEGER,
},
difficulty_name: {
type: DataTypes.TEXT,
},
mode: {
type: DataTypes.ENUM,
values: [
"mania_4k"
],
},
circle_size: {
type: DataTypes.INTEGER,
},
bpm_min: {
type: DataTypes.DECIMAL,
},
bpm_max: {
type: DataTypes.DECIMAL,
},
total_length_ms: {
type: DataTypes.INTEGER,
},
drain_length_ms: {
type: DataTypes.INTEGER,
},
total_objects: {
type: DataTypes.INTEGER,
},
total_notes: {
type: DataTypes.INTEGER,
},
total_holds: {
type: DataTypes.INTEGER,
},
star_rating: {
type: DataTypes.DECIMAL,
},
submitted_at: {
type: DataTypes.DATE,
},
last_analyzed_at: {
type: DataTypes.DATE,
},
analysis_ready: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
beatmaps.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.beatmaps.hasMany(db.map_files, {
as: 'map_files_beatmap',
foreignKey: {
name: 'beatmapId',
},
constraints: false,
});
db.beatmaps.hasMany(db.map_skills, {
as: 'map_skills_beatmap',
foreignKey: {
name: 'beatmapId',
},
constraints: false,
});
db.beatmaps.hasMany(db.analysis_jobs, {
as: 'analysis_jobs_beatmap',
foreignKey: {
name: 'beatmapId',
},
constraints: false,
});
db.beatmaps.hasMany(db.scores, {
as: 'scores_beatmap',
foreignKey: {
name: 'beatmapId',
},
constraints: false,
});
//end loop
db.beatmaps.belongsTo(db.beatmap_sets, {
as: 'beatmap_set',
foreignKey: {
name: 'beatmap_setId',
},
constraints: false,
});
db.beatmaps.belongsTo(db.users, {
as: 'createdBy',
});
db.beatmaps.belongsTo(db.users, {
as: 'updatedBy',
});
};
return beatmaps;
};

View File

@ -0,0 +1,167 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const countries = sequelize.define(
'countries',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
code: {
type: DataTypes.TEXT,
},
name: {
type: DataTypes.TEXT,
},
player_count: {
type: DataTypes.INTEGER,
},
avg_overall_skill: {
type: DataTypes.DECIMAL,
},
global_rank: {
type: DataTypes.INTEGER,
},
skills_computed_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
countries.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.countries.hasMany(db.players, {
as: 'players_country',
foreignKey: {
name: 'countryId',
},
constraints: false,
});
db.countries.hasMany(db.analysis_jobs, {
as: 'analysis_jobs_country',
foreignKey: {
name: 'countryId',
},
constraints: false,
});
db.countries.hasMany(db.country_skill_snapshots, {
as: 'country_skill_snapshots_country',
foreignKey: {
name: 'countryId',
},
constraints: false,
});
db.countries.hasMany(db.country_comparisons, {
as: 'country_comparisons_left_country',
foreignKey: {
name: 'left_countryId',
},
constraints: false,
});
db.countries.hasMany(db.country_comparisons, {
as: 'country_comparisons_right_country',
foreignKey: {
name: 'right_countryId',
},
constraints: false,
});
//end loop
db.countries.hasMany(db.file, {
as: 'flag_image',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.countries.getTableName(),
belongsToColumn: 'flag_image',
},
});
db.countries.belongsTo(db.users, {
as: 'createdBy',
});
db.countries.belongsTo(db.users, {
as: 'updatedBy',
});
};
return countries;
};

View File

@ -0,0 +1,196 @@
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 country_comparisons = sequelize.define(
'country_comparisons',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
computed_at: {
type: DataTypes.DATE,
},
left_overall_skill: {
type: DataTypes.DECIMAL,
},
right_overall_skill: {
type: DataTypes.DECIMAL,
},
left_ln_skill: {
type: DataTypes.DECIMAL,
},
right_ln_skill: {
type: DataTypes.DECIMAL,
},
left_chordjack_skill: {
type: DataTypes.DECIMAL,
},
right_chordjack_skill: {
type: DataTypes.DECIMAL,
},
left_stream_skill: {
type: DataTypes.DECIMAL,
},
right_stream_skill: {
type: DataTypes.DECIMAL,
},
left_accuracy_skill: {
type: DataTypes.DECIMAL,
},
right_accuracy_skill: {
type: DataTypes.DECIMAL,
},
left_sv_skill: {
type: DataTypes.DECIMAL,
},
right_sv_skill: {
type: DataTypes.DECIMAL,
},
left_wins_count: {
type: DataTypes.INTEGER,
},
right_wins_count: {
type: DataTypes.INTEGER,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
country_comparisons.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.country_comparisons.belongsTo(db.countries, {
as: 'left_country',
foreignKey: {
name: 'left_countryId',
},
constraints: false,
});
db.country_comparisons.belongsTo(db.countries, {
as: 'right_country',
foreignKey: {
name: 'right_countryId',
},
constraints: false,
});
db.country_comparisons.belongsTo(db.users, {
as: 'createdBy',
});
db.country_comparisons.belongsTo(db.users, {
as: 'updatedBy',
});
};
return country_comparisons;
};

View File

@ -0,0 +1,209 @@
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 country_skill_snapshots = sequelize.define(
'country_skill_snapshots',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
top_players_count: {
type: DataTypes.INTEGER,
},
overall_skill: {
type: DataTypes.DECIMAL,
},
stream_skill: {
type: DataTypes.DECIMAL,
},
chordjack_skill: {
type: DataTypes.DECIMAL,
},
jackspeed_skill: {
type: DataTypes.DECIMAL,
},
stamina_skill: {
type: DataTypes.DECIMAL,
},
ln_skill: {
type: DataTypes.DECIMAL,
},
sv_skill: {
type: DataTypes.DECIMAL,
},
vibro_skill: {
type: DataTypes.DECIMAL,
},
accuracy_skill: {
type: DataTypes.DECIMAL,
},
tech_skill: {
type: DataTypes.DECIMAL,
},
overall_rank: {
type: DataTypes.INTEGER,
},
ln_rank: {
type: DataTypes.INTEGER,
},
chordjack_rank: {
type: DataTypes.INTEGER,
},
stream_rank: {
type: DataTypes.INTEGER,
},
accuracy_rank: {
type: DataTypes.INTEGER,
},
sv_rank: {
type: DataTypes.INTEGER,
},
snapshot_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
country_skill_snapshots.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.country_skill_snapshots.belongsTo(db.countries, {
as: 'country',
foreignKey: {
name: 'countryId',
},
constraints: false,
});
db.country_skill_snapshots.belongsTo(db.users, {
as: 'createdBy',
});
db.country_skill_snapshots.belongsTo(db.users, {
as: 'updatedBy',
});
};
return country_skill_snapshots;
};

View File

@ -0,0 +1,53 @@
module.exports = function(sequelize, DataTypes) {
const file = sequelize.define(
'file',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
belongsTo: DataTypes.STRING(255),
belongsToId: DataTypes.UUID,
belongsToColumn: DataTypes.STRING(255),
name: {
type: DataTypes.STRING(2083),
allowNull: false,
validate: {
notEmpty: true,
},
},
sizeInBytes: {
type: DataTypes.INTEGER,
allowNull: true,
},
privateUrl: {
type: DataTypes.STRING(2083),
allowNull: true,
},
publicUrl: {
type: DataTypes.STRING(2083),
allowNull: false,
validate: {
notEmpty: true,
},
},
},
{
timestamps: true,
paranoid: true,
},
);
file.associate = (db) => {
db.file.belongsTo(db.users, {
as: 'createdBy',
});
db.file.belongsTo(db.users, {
as: 'updatedBy',
});
};
return file;
};

View File

@ -0,0 +1,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,133 @@
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 map_files = sequelize.define(
'map_files',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
file_kind: {
type: DataTypes.ENUM,
values: [
"osz",
"osu",
"msd_output",
"analysis_json"
],
},
storage_path: {
type: DataTypes.TEXT,
},
file_hash: {
type: DataTypes.TEXT,
},
file_size_bytes: {
type: DataTypes.INTEGER,
},
ingested_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
map_files.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.map_files.belongsTo(db.beatmaps, {
as: 'beatmap',
foreignKey: {
name: 'beatmapId',
},
constraints: false,
});
db.map_files.belongsTo(db.users, {
as: 'createdBy',
});
db.map_files.belongsTo(db.users, {
as: 'updatedBy',
});
};
return map_files;
};

View File

@ -0,0 +1,232 @@
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 map_skills = sequelize.define(
'map_skills',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
msd_overall: {
type: DataTypes.DECIMAL,
},
msd_stream: {
type: DataTypes.DECIMAL,
},
msd_chordjack: {
type: DataTypes.DECIMAL,
},
msd_jackspeed: {
type: DataTypes.DECIMAL,
},
msd_stamina: {
type: DataTypes.DECIMAL,
},
ln_skill: {
type: DataTypes.DECIMAL,
},
ln_density: {
type: DataTypes.DECIMAL,
},
ln_overlap_complexity: {
type: DataTypes.DECIMAL,
},
ln_release_difficulty: {
type: DataTypes.DECIMAL,
},
sv_skill: {
type: DataTypes.DECIMAL,
},
sv_changes_count: {
type: DataTypes.INTEGER,
},
sv_intensity: {
type: DataTypes.DECIMAL,
},
sv_density: {
type: DataTypes.DECIMAL,
},
vibro_skill: {
type: DataTypes.DECIMAL,
},
vibro_ratio: {
type: DataTypes.DECIMAL,
},
accuracy_skill: {
type: DataTypes.DECIMAL,
},
tech_skill: {
type: DataTypes.DECIMAL,
},
computed_at: {
type: DataTypes.DATE,
},
normalization_version: {
type: DataTypes.ENUM,
values: [
"v1"
],
},
is_stale: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
map_skills.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.map_skills.belongsTo(db.beatmaps, {
as: 'beatmap',
foreignKey: {
name: 'beatmapId',
},
constraints: false,
});
db.map_skills.belongsTo(db.users, {
as: 'createdBy',
});
db.map_skills.belongsTo(db.users, {
as: 'updatedBy',
});
};
return map_skills;
};

View File

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

View File

@ -0,0 +1,198 @@
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 player_skill_snapshots = sequelize.define(
'player_skill_snapshots',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
overall_skill: {
type: DataTypes.DECIMAL,
},
stream_skill: {
type: DataTypes.DECIMAL,
},
chordjack_skill: {
type: DataTypes.DECIMAL,
},
jackspeed_skill: {
type: DataTypes.DECIMAL,
},
stamina_skill: {
type: DataTypes.DECIMAL,
},
ln_skill: {
type: DataTypes.DECIMAL,
},
sv_skill: {
type: DataTypes.DECIMAL,
},
vibro_skill: {
type: DataTypes.DECIMAL,
},
accuracy_skill: {
type: DataTypes.DECIMAL,
},
tech_skill: {
type: DataTypes.DECIMAL,
},
archetype: {
type: DataTypes.ENUM,
values: [
"ln_specialist",
"chordjack_god",
"jack_specialist",
"tech_wizard",
"stream_player",
"acc_perfectionist",
"all_rounder"
],
},
overall_rank: {
type: DataTypes.INTEGER,
},
snapshot_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
player_skill_snapshots.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.player_skill_snapshots.belongsTo(db.players, {
as: 'player',
foreignKey: {
name: 'playerId',
},
constraints: false,
});
db.player_skill_snapshots.belongsTo(db.users, {
as: 'createdBy',
});
db.player_skill_snapshots.belongsTo(db.users, {
as: 'updatedBy',
});
};
return player_skill_snapshots;
};

View File

@ -0,0 +1,149 @@
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 player_top_plays = sequelize.define(
'player_top_plays',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
skill_type: {
type: DataTypes.ENUM,
values: [
"stream",
"chordjack",
"jackspeed",
"stamina",
"ln",
"sv",
"vibro",
"accuracy",
"tech"
],
},
rank_in_skill: {
type: DataTypes.INTEGER,
},
contribution_value: {
type: DataTypes.DECIMAL,
},
selected_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
player_top_plays.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.player_top_plays.belongsTo(db.players, {
as: 'player',
foreignKey: {
name: 'playerId',
},
constraints: false,
});
db.player_top_plays.belongsTo(db.scores, {
as: 'score',
foreignKey: {
name: 'scoreId',
},
constraints: false,
});
db.player_top_plays.belongsTo(db.users, {
as: 'createdBy',
});
db.player_top_plays.belongsTo(db.users, {
as: 'updatedBy',
});
};
return player_top_plays;
};

View File

@ -0,0 +1,261 @@
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 players = sequelize.define(
'players',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
osu_user_number: {
type: DataTypes.INTEGER,
},
username: {
type: DataTypes.TEXT,
},
archetype: {
type: DataTypes.ENUM,
values: [
"ln_specialist",
"chordjack_god",
"jack_specialist",
"tech_wizard",
"stream_player",
"acc_perfectionist",
"all_rounder"
],
},
overall_skill: {
type: DataTypes.DECIMAL,
},
stream_skill: {
type: DataTypes.DECIMAL,
},
chordjack_skill: {
type: DataTypes.DECIMAL,
},
jackspeed_skill: {
type: DataTypes.DECIMAL,
},
stamina_skill: {
type: DataTypes.DECIMAL,
},
ln_skill: {
type: DataTypes.DECIMAL,
},
sv_skill: {
type: DataTypes.DECIMAL,
},
vibro_skill: {
type: DataTypes.DECIMAL,
},
accuracy_skill: {
type: DataTypes.DECIMAL,
},
overall_rank: {
type: DataTypes.INTEGER,
},
country_rank: {
type: DataTypes.INTEGER,
},
profile_last_synced_at: {
type: DataTypes.DATE,
},
skills_computed_at: {
type: DataTypes.DATE,
},
is_tracked: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
players.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.players.hasMany(db.analysis_jobs, {
as: 'analysis_jobs_player',
foreignKey: {
name: 'playerId',
},
constraints: false,
});
db.players.hasMany(db.scores, {
as: 'scores_player',
foreignKey: {
name: 'playerId',
},
constraints: false,
});
db.players.hasMany(db.player_top_plays, {
as: 'player_top_plays_player',
foreignKey: {
name: 'playerId',
},
constraints: false,
});
db.players.hasMany(db.player_skill_snapshots, {
as: 'player_skill_snapshots_player',
foreignKey: {
name: 'playerId',
},
constraints: false,
});
//end loop
db.players.belongsTo(db.countries, {
as: 'country',
foreignKey: {
name: 'countryId',
},
constraints: false,
});
db.players.belongsTo(db.users, {
as: 'createdBy',
});
db.players.belongsTo(db.users, {
as: 'updatedBy',
});
};
return players;
};

View File

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

View File

@ -0,0 +1,151 @@
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 score_skill_contributions = sequelize.define(
'score_skill_contributions',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
skill_type: {
type: DataTypes.ENUM,
values: [
"overall",
"stream",
"chordjack",
"jackspeed",
"stamina",
"ln",
"sv",
"vibro",
"accuracy",
"tech"
],
},
map_skill_value: {
type: DataTypes.DECIMAL,
},
weighted_skill_value: {
type: DataTypes.DECIMAL,
},
weight_used: {
type: DataTypes.DECIMAL,
},
computed_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
score_skill_contributions.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.score_skill_contributions.belongsTo(db.scores, {
as: 'score',
foreignKey: {
name: 'scoreId',
},
constraints: false,
});
db.score_skill_contributions.belongsTo(db.users, {
as: 'createdBy',
});
db.score_skill_contributions.belongsTo(db.users, {
as: 'updatedBy',
});
};
return score_skill_contributions;
};

View File

@ -0,0 +1,247 @@
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 scores = sequelize.define(
'scores',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
osu_score_number: {
type: DataTypes.INTEGER,
},
scoring_type: {
type: DataTypes.ENUM,
values: [
"stable",
"lazer"
],
},
accuracy: {
type: DataTypes.DECIMAL,
},
max_combo: {
type: DataTypes.INTEGER,
},
grade: {
type: DataTypes.ENUM,
values: [
"xh",
"x",
"sh",
"s",
"a",
"b",
"c",
"d",
"f"
],
},
count_300: {
type: DataTypes.INTEGER,
},
count_200: {
type: DataTypes.INTEGER,
},
count_100: {
type: DataTypes.INTEGER,
},
count_50: {
type: DataTypes.INTEGER,
},
count_miss: {
type: DataTypes.INTEGER,
},
is_full_combo: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
score_weight: {
type: DataTypes.DECIMAL,
},
played_at: {
type: DataTypes.DATE,
},
ingested_at: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
scores.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.scores.hasMany(db.score_skill_contributions, {
as: 'score_skill_contributions_score',
foreignKey: {
name: 'scoreId',
},
constraints: false,
});
db.scores.hasMany(db.player_top_plays, {
as: 'player_top_plays_score',
foreignKey: {
name: 'scoreId',
},
constraints: false,
});
//end loop
db.scores.belongsTo(db.players, {
as: 'player',
foreignKey: {
name: 'playerId',
},
constraints: false,
});
db.scores.belongsTo(db.beatmaps, {
as: 'beatmap',
foreignKey: {
name: 'beatmapId',
},
constraints: false,
});
db.scores.belongsTo(db.users, {
as: 'createdBy',
});
db.scores.belongsTo(db.users, {
as: 'updatedBy',
});
};
return scores;
};

View File

@ -0,0 +1,131 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const system_settings = sequelize.define(
'system_settings',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
setting_key: {
type: DataTypes.TEXT,
},
setting_value: {
type: DataTypes.TEXT,
},
value_type: {
type: DataTypes.ENUM,
values: [
"string",
"int",
"decimal",
"boolean",
"json"
],
},
effective_from: {
type: DataTypes.DATE,
},
is_secret: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
system_settings.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.system_settings.belongsTo(db.users, {
as: 'createdBy',
});
db.system_settings.belongsTo(db.users, {
as: 'updatedBy',
});
};
return system_settings;
};

View File

@ -0,0 +1,240 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function(sequelize, DataTypes) {
const users = sequelize.define(
'users',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
firstName: {
type: DataTypes.TEXT,
},
lastName: {
type: DataTypes.TEXT,
},
phoneNumber: {
type: DataTypes.TEXT,
},
email: {
type: DataTypes.TEXT,
},
disabled: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
password: {
type: DataTypes.TEXT,
},
emailVerified: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
emailVerificationToken: {
type: DataTypes.TEXT,
},
emailVerificationTokenExpiresAt: {
type: DataTypes.DATE,
},
passwordResetToken: {
type: DataTypes.TEXT,
},
passwordResetTokenExpiresAt: {
type: DataTypes.DATE,
},
provider: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
users.associate = (db) => {
db.users.belongsToMany(db.permissions, {
as: 'custom_permissions',
foreignKey: {
name: 'users_custom_permissionsId',
},
constraints: false,
through: 'usersCustom_permissionsPermissions',
});
db.users.belongsToMany(db.permissions, {
as: 'custom_permissions_filter',
foreignKey: {
name: 'users_custom_permissionsId',
},
constraints: false,
through: 'usersCustom_permissionsPermissions',
});
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
//end loop
db.users.belongsTo(db.roles, {
as: 'app_role',
foreignKey: {
name: 'app_roleId',
},
constraints: false,
});
db.users.hasMany(db.file, {
as: 'avatar',
foreignKey: 'belongsToId',
constraints: false,
scope: {
belongsTo: db.users.getTableName(),
belongsToColumn: 'avatar',
},
});
db.users.belongsTo(db.users, {
as: 'createdBy',
});
db.users.belongsTo(db.users, {
as: 'updatedBy',
});
};
users.beforeCreate((users, options) => {
users = trimStringFields(users);
if (users.provider !== providers.LOCAL && Object.values(providers).indexOf(users.provider) > -1) {
users.emailVerified = true;
if (!users.password) {
const password = crypto
.randomBytes(20)
.toString('hex');
const hashedPassword = bcrypt.hashSync(
password,
config.bcrypt.saltRounds,
);
users.password = hashedPassword
}
}
});
users.beforeUpdate((users, options) => {
users = trimStringFields(users);
});
return users;
};
function trimStringFields(users) {
users.email = users.email.trim();
users.firstName = users.firstName
? users.firstName.trim()
: null;
users.lastName = users.lastName
? users.lastName.trim()
: null;
return users;
}

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

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

View File

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

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

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

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

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

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

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

@ -0,0 +1,192 @@
const express = require('express');
const cors = require('cors');
const app = express();
const passport = require('passport');
const path = require('path');
const fs = require('fs');
const bodyParser = require('body-parser');
const db = require('./db/models');
const config = require('./config');
const swaggerUI = require('swagger-ui-express');
const swaggerJsDoc = require('swagger-jsdoc');
const authRoutes = require('./routes/auth');
const fileRoutes = require('./routes/file');
const searchRoutes = require('./routes/search');
const sqlRoutes = require('./routes/sql');
const pexelsRoutes = require('./routes/pexels');
const openaiRoutes = require('./routes/openai');
const usersRoutes = require('./routes/users');
const rolesRoutes = require('./routes/roles');
const permissionsRoutes = require('./routes/permissions');
const countriesRoutes = require('./routes/countries');
const playersRoutes = require('./routes/players');
const beatmap_setsRoutes = require('./routes/beatmap_sets');
const beatmapsRoutes = require('./routes/beatmaps');
const map_filesRoutes = require('./routes/map_files');
const map_skillsRoutes = require('./routes/map_skills');
const analysis_jobsRoutes = require('./routes/analysis_jobs');
const scoresRoutes = require('./routes/scores');
const score_skill_contributionsRoutes = require('./routes/score_skill_contributions');
const player_top_playsRoutes = require('./routes/player_top_plays');
const country_skill_snapshotsRoutes = require('./routes/country_skill_snapshots');
const player_skill_snapshotsRoutes = require('./routes/player_skill_snapshots');
const country_comparisonsRoutes = require('./routes/country_comparisons');
const system_settingsRoutes = require('./routes/system_settings');
const getBaseUrl = (url) => {
if (!url) return '';
return url.endsWith('/api') ? url.slice(0, -4) : url;
};
const options = {
definition: {
openapi: "3.0.0",
info: {
version: "1.0.0",
title: "ManiaSkills",
description: "ManiaSkills Online REST API for Testing and Prototyping application. You can perform all major operations with your entities - create, delete and etc.",
},
servers: [
{
url: getBaseUrl(process.env.NEXT_PUBLIC_BACK_API) || config.swaggerUrl,
description: "Development server",
}
],
components: {
securitySchemes: {
bearerAuth: {
type: 'http',
scheme: 'bearer',
bearerFormat: 'JWT',
}
},
responses: {
UnauthorizedError: {
description: "Access token is missing or invalid"
}
}
},
security: [{
bearerAuth: []
}]
},
apis: ["./src/routes/*.js"],
};
const specs = swaggerJsDoc(options);
app.use('/api-docs', function (req, res, next) {
swaggerUI.host = getBaseUrl(process.env.NEXT_PUBLIC_BACK_API) || req.get('host');
next()
}, swaggerUI.serve, swaggerUI.setup(specs))
app.use(cors({origin: true}));
require('./auth/auth');
app.use(bodyParser.json());
app.use('/api/auth', authRoutes);
app.use('/api/file', fileRoutes);
app.use('/api/pexels', pexelsRoutes);
app.enable('trust proxy');
app.use('/api/users', passport.authenticate('jwt', {session: false}), usersRoutes);
app.use('/api/roles', passport.authenticate('jwt', {session: false}), rolesRoutes);
app.use('/api/permissions', passport.authenticate('jwt', {session: false}), permissionsRoutes);
app.use('/api/countries', passport.authenticate('jwt', {session: false}), countriesRoutes);
app.use('/api/players', passport.authenticate('jwt', {session: false}), playersRoutes);
app.use('/api/beatmap_sets', passport.authenticate('jwt', {session: false}), beatmap_setsRoutes);
app.use('/api/beatmaps', passport.authenticate('jwt', {session: false}), beatmapsRoutes);
app.use('/api/map_files', passport.authenticate('jwt', {session: false}), map_filesRoutes);
app.use('/api/map_skills', passport.authenticate('jwt', {session: false}), map_skillsRoutes);
app.use('/api/analysis_jobs', passport.authenticate('jwt', {session: false}), analysis_jobsRoutes);
app.use('/api/scores', passport.authenticate('jwt', {session: false}), scoresRoutes);
app.use('/api/score_skill_contributions', passport.authenticate('jwt', {session: false}), score_skill_contributionsRoutes);
app.use('/api/player_top_plays', passport.authenticate('jwt', {session: false}), player_top_playsRoutes);
app.use('/api/country_skill_snapshots', passport.authenticate('jwt', {session: false}), country_skill_snapshotsRoutes);
app.use('/api/player_skill_snapshots', passport.authenticate('jwt', {session: false}), player_skill_snapshotsRoutes);
app.use('/api/country_comparisons', passport.authenticate('jwt', {session: false}), country_comparisonsRoutes);
app.use('/api/system_settings', passport.authenticate('jwt', {session: false}), system_settingsRoutes);
app.use(
'/api/openai',
passport.authenticate('jwt', { session: false }),
openaiRoutes,
);
app.use(
'/api/ai',
passport.authenticate('jwt', { session: false }),
openaiRoutes,
);
app.use(
'/api/search',
passport.authenticate('jwt', { session: false }),
searchRoutes);
app.use(
'/api/sql',
passport.authenticate('jwt', { session: false }),
sqlRoutes);
const publicDir = path.join(
__dirname,
'../public',
);
if (fs.existsSync(publicDir)) {
app.use('/', express.static(publicDir));
app.get('*', function(request, response) {
response.sendFile(
path.resolve(publicDir, 'index.html'),
);
});
}
const PORT = process.env.NODE_ENV === 'dev_stage' ? 3000 : 8080;
app.listen(PORT, () => {
console.log(`Listening on port ${PORT}`);
});
module.exports = app;

View File

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

View File

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

View File

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

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

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

View File

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

View File

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

View File

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,2 @@

View File

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

View File

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

View File

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

View File

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

View File

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

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

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

View File

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

View File

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

View File

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

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

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

View File

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

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

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

View File

@ -0,0 +1,138 @@
const db = require('../db/models');
const Analysis_jobsDBApi = require('../db/api/analysis_jobs');
const processFile = require("../middlewares/upload");
const ValidationError = require('./notifications/errors/validation');
const csv = require('csv-parser');
const axios = require('axios');
const config = require('../config');
const stream = require('stream');
module.exports = class Analysis_jobsService {
static async create(data, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await Analysis_jobsDBApi.create(
data,
{
currentUser,
transaction,
},
);
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
};
static async bulkImport(req, res, sendInvitationEmails = true, host) {
const transaction = await db.sequelize.transaction();
try {
await processFile(req, res);
const bufferStream = new stream.PassThrough();
const results = [];
await bufferStream.end(Buffer.from(req.file.buffer, "utf-8")); // convert Buffer to Stream
await new Promise((resolve, reject) => {
bufferStream
.pipe(csv())
.on('data', (data) => results.push(data))
.on('end', async () => {
console.log('CSV results', results);
resolve();
})
.on('error', (error) => reject(error));
})
await Analysis_jobsDBApi.bulkImport(results, {
transaction,
ignoreDuplicates: true,
validate: true,
currentUser: req.currentUser
});
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
static async update(data, id, currentUser) {
const transaction = await db.sequelize.transaction();
try {
let analysis_jobs = await Analysis_jobsDBApi.findBy(
{id},
{transaction},
);
if (!analysis_jobs) {
throw new ValidationError(
'analysis_jobsNotFound',
);
}
const updatedAnalysis_jobs = await Analysis_jobsDBApi.update(
id,
data,
{
currentUser,
transaction,
},
);
await transaction.commit();
return updatedAnalysis_jobs;
} catch (error) {
await transaction.rollback();
throw error;
}
};
static async deleteByIds(ids, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await Analysis_jobsDBApi.deleteByIds(ids, {
currentUser,
transaction,
});
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
static async remove(id, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await Analysis_jobsDBApi.remove(
id,
{
currentUser,
transaction,
},
);
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
};

View File

@ -0,0 +1,312 @@
const UsersDBApi = require('../db/api/users');
const ValidationError = require('./notifications/errors/validation');
const ForbiddenError = require('./notifications/errors/forbidden');
const bcrypt = require('bcrypt');
const EmailAddressVerificationEmail = require('./email/list/addressVerification');
const InvitationEmail = require("./email/list/invitation");
const PasswordResetEmail = require('./email/list/passwordReset');
const EmailSender = require('./email');
const config = require('../config');
const helpers = require('../helpers');
class Auth {
static async signup(email, password, options = {}, host) {
const user = await UsersDBApi.findBy({email});
const hashedPassword = await bcrypt.hash(
password,
config.bcrypt.saltRounds,
);
if (user) {
if (user.authenticationUid) {
throw new ValidationError(
'auth.emailAlreadyInUse',
);
}
if (user.disabled) {
throw new ValidationError(
'auth.userDisabled',
);
}
await UsersDBApi.updatePassword(
user.id,
hashedPassword,
options,
);
if (EmailSender.isConfigured) {
await this.sendEmailAddressVerificationEmail(
user.email,
host,
);
}
const data = {
user: {
id: user.id,
email: user.email
}
};
return helpers.jwtSign(data);
}
const newUser = await UsersDBApi.createFromAuth(
{
firstName: email.split('@')[0],
password: hashedPassword,
email: email,
},
options,
);
if (EmailSender.isConfigured) {
await this.sendEmailAddressVerificationEmail(
newUser.email,
host,
);
}
const data = {
user: {
id: newUser.id,
email: newUser.email
}
};
return helpers.jwtSign(data);
}
static async signin(email, password, options = {}) {
const user = await UsersDBApi.findBy({email});
if (!user) {
throw new ValidationError(
'auth.userNotFound',
);
}
if (user.disabled) {
throw new ValidationError(
'auth.userDisabled',
);
}
if (!user.password) {
throw new ValidationError(
'auth.wrongPassword',
);
}
if (!EmailSender.isConfigured) {
user.emailVerified = true;
}
if (!user.emailVerified) {
throw new ValidationError(
'auth.userNotVerified',
);
}
const passwordsMatch = await bcrypt.compare(
password,
user.password,
);
if (!passwordsMatch) {
throw new ValidationError(
'auth.wrongPassword',
);
}
const data = {
user: {
id: user.id,
email: user.email
}
};
return helpers.jwtSign(data);
}
static async sendEmailAddressVerificationEmail(
email,
host,
) {
let link;
try {
const token = await UsersDBApi.generateEmailVerificationToken(
email,
);
link = `${host}/verify-email?token=${token}`;
} catch (error) {
console.error(error);
throw new ValidationError(
'auth.emailAddressVerificationEmail.error',
);
}
const emailAddressVerificationEmail = new EmailAddressVerificationEmail(
email,
link,
);
return new EmailSender(
emailAddressVerificationEmail,
).send();
}
static async sendPasswordResetEmail(email, type = 'register', host) {
let link;
try {
const token = await UsersDBApi.generatePasswordResetToken(
email,
);
link = `${host}/password-reset?token=${token}`;
} catch (error) {
console.error(error);
throw new ValidationError(
'auth.passwordReset.error',
);
}
let passwordResetEmail;
if (type === 'register') {
passwordResetEmail = new PasswordResetEmail(
email,
link,
);
}
if (type === 'invitation') {
passwordResetEmail = new InvitationEmail(
email,
link,
);
}
return new EmailSender(passwordResetEmail).send();
}
static async verifyEmail(token, options = {}) {
const user = await UsersDBApi.findByEmailVerificationToken(
token,
options,
);
if (!user) {
throw new ValidationError(
'auth.emailAddressVerificationEmail.invalidToken',
);
}
return UsersDBApi.markEmailVerified(
user.id,
options,
);
}
static async passwordUpdate(currentPassword, newPassword, options) {
const currentUser = options.currentUser || null;
if (!currentUser) {
throw new ForbiddenError();
}
const currentPasswordMatch = await bcrypt.compare(
currentPassword,
currentUser.password,
);
if (!currentPasswordMatch) {
throw new ValidationError(
'auth.wrongPassword'
)
}
const newPasswordMatch = await bcrypt.compare(
newPassword,
currentUser.password,
);
if (newPasswordMatch) {
throw new ValidationError(
'auth.passwordUpdate.samePassword'
)
}
const hashedPassword = await bcrypt.hash(
newPassword,
config.bcrypt.saltRounds,
);
return UsersDBApi.updatePassword(
currentUser.id,
hashedPassword,
options,
);
}
static async passwordReset(
token,
password,
options = {},
) {
const user = await UsersDBApi.findByPasswordResetToken(
token,
options,
);
if (!user) {
throw new ValidationError(
'auth.passwordReset.invalidToken',
);
}
const hashedPassword = await bcrypt.hash(
password,
config.bcrypt.saltRounds,
);
return UsersDBApi.updatePassword(
user.id,
hashedPassword,
options,
);
}
static async updateProfile(data, currentUser) {
let transaction = await db.sequelize.transaction();
try {
await UsersDBApi.findBy(
{id: currentUser.id},
{transaction},
);
await UsersDBApi.update(
currentUser.id,
data,
{
currentUser,
transaction
},
);
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
}
module.exports = Auth;

View File

@ -0,0 +1,138 @@
const db = require('../db/models');
const Beatmap_setsDBApi = require('../db/api/beatmap_sets');
const processFile = require("../middlewares/upload");
const ValidationError = require('./notifications/errors/validation');
const csv = require('csv-parser');
const axios = require('axios');
const config = require('../config');
const stream = require('stream');
module.exports = class Beatmap_setsService {
static async create(data, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await Beatmap_setsDBApi.create(
data,
{
currentUser,
transaction,
},
);
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
};
static async bulkImport(req, res, sendInvitationEmails = true, host) {
const transaction = await db.sequelize.transaction();
try {
await processFile(req, res);
const bufferStream = new stream.PassThrough();
const results = [];
await bufferStream.end(Buffer.from(req.file.buffer, "utf-8")); // convert Buffer to Stream
await new Promise((resolve, reject) => {
bufferStream
.pipe(csv())
.on('data', (data) => results.push(data))
.on('end', async () => {
console.log('CSV results', results);
resolve();
})
.on('error', (error) => reject(error));
})
await Beatmap_setsDBApi.bulkImport(results, {
transaction,
ignoreDuplicates: true,
validate: true,
currentUser: req.currentUser
});
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
static async update(data, id, currentUser) {
const transaction = await db.sequelize.transaction();
try {
let beatmap_sets = await Beatmap_setsDBApi.findBy(
{id},
{transaction},
);
if (!beatmap_sets) {
throw new ValidationError(
'beatmap_setsNotFound',
);
}
const updatedBeatmap_sets = await Beatmap_setsDBApi.update(
id,
data,
{
currentUser,
transaction,
},
);
await transaction.commit();
return updatedBeatmap_sets;
} catch (error) {
await transaction.rollback();
throw error;
}
};
static async deleteByIds(ids, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await Beatmap_setsDBApi.deleteByIds(ids, {
currentUser,
transaction,
});
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
static async remove(id, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await Beatmap_setsDBApi.remove(
id,
{
currentUser,
transaction,
},
);
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
};

View File

@ -0,0 +1,138 @@
const db = require('../db/models');
const BeatmapsDBApi = require('../db/api/beatmaps');
const processFile = require("../middlewares/upload");
const ValidationError = require('./notifications/errors/validation');
const csv = require('csv-parser');
const axios = require('axios');
const config = require('../config');
const stream = require('stream');
module.exports = class BeatmapsService {
static async create(data, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await BeatmapsDBApi.create(
data,
{
currentUser,
transaction,
},
);
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
};
static async bulkImport(req, res, sendInvitationEmails = true, host) {
const transaction = await db.sequelize.transaction();
try {
await processFile(req, res);
const bufferStream = new stream.PassThrough();
const results = [];
await bufferStream.end(Buffer.from(req.file.buffer, "utf-8")); // convert Buffer to Stream
await new Promise((resolve, reject) => {
bufferStream
.pipe(csv())
.on('data', (data) => results.push(data))
.on('end', async () => {
console.log('CSV results', results);
resolve();
})
.on('error', (error) => reject(error));
})
await BeatmapsDBApi.bulkImport(results, {
transaction,
ignoreDuplicates: true,
validate: true,
currentUser: req.currentUser
});
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
static async update(data, id, currentUser) {
const transaction = await db.sequelize.transaction();
try {
let beatmaps = await BeatmapsDBApi.findBy(
{id},
{transaction},
);
if (!beatmaps) {
throw new ValidationError(
'beatmapsNotFound',
);
}
const updatedBeatmaps = await BeatmapsDBApi.update(
id,
data,
{
currentUser,
transaction,
},
);
await transaction.commit();
return updatedBeatmaps;
} catch (error) {
await transaction.rollback();
throw error;
}
};
static async deleteByIds(ids, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await BeatmapsDBApi.deleteByIds(ids, {
currentUser,
transaction,
});
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
static async remove(id, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await BeatmapsDBApi.remove(
id,
{
currentUser,
transaction,
},
);
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
};

View File

@ -0,0 +1,138 @@
const db = require('../db/models');
const CountriesDBApi = require('../db/api/countries');
const processFile = require("../middlewares/upload");
const ValidationError = require('./notifications/errors/validation');
const csv = require('csv-parser');
const axios = require('axios');
const config = require('../config');
const stream = require('stream');
module.exports = class CountriesService {
static async create(data, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await CountriesDBApi.create(
data,
{
currentUser,
transaction,
},
);
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
};
static async bulkImport(req, res, sendInvitationEmails = true, host) {
const transaction = await db.sequelize.transaction();
try {
await processFile(req, res);
const bufferStream = new stream.PassThrough();
const results = [];
await bufferStream.end(Buffer.from(req.file.buffer, "utf-8")); // convert Buffer to Stream
await new Promise((resolve, reject) => {
bufferStream
.pipe(csv())
.on('data', (data) => results.push(data))
.on('end', async () => {
console.log('CSV results', results);
resolve();
})
.on('error', (error) => reject(error));
})
await CountriesDBApi.bulkImport(results, {
transaction,
ignoreDuplicates: true,
validate: true,
currentUser: req.currentUser
});
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
static async update(data, id, currentUser) {
const transaction = await db.sequelize.transaction();
try {
let countries = await CountriesDBApi.findBy(
{id},
{transaction},
);
if (!countries) {
throw new ValidationError(
'countriesNotFound',
);
}
const updatedCountries = await CountriesDBApi.update(
id,
data,
{
currentUser,
transaction,
},
);
await transaction.commit();
return updatedCountries;
} catch (error) {
await transaction.rollback();
throw error;
}
};
static async deleteByIds(ids, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await CountriesDBApi.deleteByIds(ids, {
currentUser,
transaction,
});
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
static async remove(id, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await CountriesDBApi.remove(
id,
{
currentUser,
transaction,
},
);
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
};

View File

@ -0,0 +1,138 @@
const db = require('../db/models');
const Country_comparisonsDBApi = require('../db/api/country_comparisons');
const processFile = require("../middlewares/upload");
const ValidationError = require('./notifications/errors/validation');
const csv = require('csv-parser');
const axios = require('axios');
const config = require('../config');
const stream = require('stream');
module.exports = class Country_comparisonsService {
static async create(data, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await Country_comparisonsDBApi.create(
data,
{
currentUser,
transaction,
},
);
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
};
static async bulkImport(req, res, sendInvitationEmails = true, host) {
const transaction = await db.sequelize.transaction();
try {
await processFile(req, res);
const bufferStream = new stream.PassThrough();
const results = [];
await bufferStream.end(Buffer.from(req.file.buffer, "utf-8")); // convert Buffer to Stream
await new Promise((resolve, reject) => {
bufferStream
.pipe(csv())
.on('data', (data) => results.push(data))
.on('end', async () => {
console.log('CSV results', results);
resolve();
})
.on('error', (error) => reject(error));
})
await Country_comparisonsDBApi.bulkImport(results, {
transaction,
ignoreDuplicates: true,
validate: true,
currentUser: req.currentUser
});
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
static async update(data, id, currentUser) {
const transaction = await db.sequelize.transaction();
try {
let country_comparisons = await Country_comparisonsDBApi.findBy(
{id},
{transaction},
);
if (!country_comparisons) {
throw new ValidationError(
'country_comparisonsNotFound',
);
}
const updatedCountry_comparisons = await Country_comparisonsDBApi.update(
id,
data,
{
currentUser,
transaction,
},
);
await transaction.commit();
return updatedCountry_comparisons;
} catch (error) {
await transaction.rollback();
throw error;
}
};
static async deleteByIds(ids, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await Country_comparisonsDBApi.deleteByIds(ids, {
currentUser,
transaction,
});
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
static async remove(id, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await Country_comparisonsDBApi.remove(
id,
{
currentUser,
transaction,
},
);
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
};

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