Initial version

This commit is contained in:
Flatlogic Bot 2025-03-09 18:51:05 +00:00
commit afc80ac93c
408 changed files with 66791 additions and 0 deletions

4
.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
node_modules/
*/node_modules/
app-shell/
*/build/

11
backend/.prettierrc Normal file
View File

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

7
backend/.sequelizerc Normal file
View File

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

23
backend/Dockerfile Normal file
View File

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

67
backend/README.md Normal file
View File

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

51
backend/package.json Normal file
View File

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

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

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

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

@ -0,0 +1,73 @@
const os = require('os');
const config = {
gcloud: {
bucket: 'fldemo-files',
hash: '1932be095be643db391a2668c6e48896',
},
bcrypt: {
saltRounds: 12,
},
admin_pass: 'password',
admin_email: 'admin@flatlogic.com',
providers: {
LOCAL: 'local',
GOOGLE: 'google',
MICROSOFT: 'microsoft',
},
secret_key: 'HUEyqESqgQ1yTwzVlO6wprC9Kf1J1xuA',
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:
'671001533244-kf1k1gmp6mnl0r030qmvdu6v36ghmim6.apps.googleusercontent.com',
clientSecret: 'Yo4qbKZniqvojzUQ60iKlxqR',
},
microsoft: {
clientId: '4696f457-31af-40de-897c-e00d7d4cff73',
clientSecret: 'm8jzZ.5UpHF3=-dXzyxiZ4e[F8OF54@p',
},
uploadDir: os.tmpdir(),
email: {
from: 'GMW ERP <app@flatlogic.app>',
host: 'email-smtp.us-east-1.amazonaws.com',
port: 587,
auth: {
user: 'AKIAVEW7G4PQUBGM52OF',
pass: process.env.EMAIL_PASS,
},
tls: {
rejectUnauthorized: false,
},
},
roles: {
super_admin: 'Super Administrator',
admin: 'Administrator',
user: 'User',
},
project_uuid: '0dab9f2e-689a-4669-83cf-1eb9f79773dc',
flHost:
process.env.NODE_ENV === 'production' ||
process.env.NODE_ENV === 'dev_stage'
? 'https://flatlogic.com/projects'
: 'http://localhost:3000/projects',
};
config.pexelsKey = 'Vc99rnmOhHhJAbgGQoKLZtsaIVfkeownoQNbTj78VemUjKh08ZYRbf18';
config.pexelsQuery = 'abstract technology network';
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,73 @@
const db = require('../models');
const assert = require('assert');
const services = require('../../services/file');
module.exports = class FileDBApi {
static async replaceRelationFiles(relation, rawFiles, options) {
assert(relation.belongsTo, 'belongsTo is required');
assert(relation.belongsToColumn, 'belongsToColumn is required');
assert(relation.belongsToId, 'belongsToId is required');
let files = [];
if (Array.isArray(rawFiles)) {
files = rawFiles;
} else {
files = rawFiles ? [rawFiles] : [];
}
await this._removeLegacyFiles(relation, files, options);
await this._addFiles(relation, files, options);
}
static async _addFiles(relation, files, options) {
const transaction = (options && options.transaction) || undefined;
const currentUser = (options && options.currentUser) || { id: null };
const inexistentFiles = files.filter((file) => !!file.new);
for (const file of inexistentFiles) {
await db.file.create(
{
belongsTo: relation.belongsTo,
belongsToColumn: relation.belongsToColumn,
belongsToId: relation.belongsToId,
name: file.name,
sizeInBytes: file.sizeInBytes,
privateUrl: file.privateUrl,
publicUrl: file.publicUrl,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{
transaction,
},
);
}
}
static async _removeLegacyFiles(relation, files, options) {
const transaction = (options && options.transaction) || undefined;
const filesToDelete = await db.file.findAll({
where: {
belongsTo: relation.belongsTo,
belongsToId: relation.belongsToId,
belongsToColumn: relation.belongsToColumn,
id: {
[db.Sequelize.Op.notIn]: files
.filter((file) => !file.new)
.map((file) => file.id),
},
},
transaction,
});
for (let file of filesToDelete) {
await services.deleteGCloud(file.privateUrl);
await file.destroy({
transaction,
});
}
}
};

View File

@ -0,0 +1,369 @@
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 Human_resourcesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const human_resources = await db.human_resources.create(
{
id: data.id || undefined,
employee_name: data.employee_name || null,
role: data.role || null,
shift: data.shift || null,
payroll: data.payroll || null,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await human_resources.setSubsidiary(data.subsidiary || null, {
transaction,
});
return human_resources;
}
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 human_resourcesData = data.map((item, index) => ({
id: item.id || undefined,
employee_name: item.employee_name || null,
role: item.role || null,
shift: item.shift || null,
payroll: item.payroll || null,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const human_resources = await db.human_resources.bulkCreate(
human_resourcesData,
{ transaction },
);
// For each item created, replace relation files
return human_resources;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const human_resources = await db.human_resources.findByPk(
id,
{},
{ transaction },
);
const updatePayload = {};
if (data.employee_name !== undefined)
updatePayload.employee_name = data.employee_name;
if (data.role !== undefined) updatePayload.role = data.role;
if (data.shift !== undefined) updatePayload.shift = data.shift;
if (data.payroll !== undefined) updatePayload.payroll = data.payroll;
updatePayload.updatedById = currentUser.id;
await human_resources.update(updatePayload, { transaction });
if (data.subsidiary !== undefined) {
await human_resources.setSubsidiary(
data.subsidiary,
{ transaction },
);
}
return human_resources;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const human_resources = await db.human_resources.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of human_resources) {
await record.update({ deletedBy: currentUser.id }, { transaction });
}
for (const record of human_resources) {
await record.destroy({ transaction });
}
});
return human_resources;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const human_resources = await db.human_resources.findByPk(id, options);
await human_resources.update(
{
deletedBy: currentUser.id,
},
{
transaction,
},
);
await human_resources.destroy({
transaction,
});
return human_resources;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const human_resources = await db.human_resources.findOne(
{ where },
{ transaction },
);
if (!human_resources) {
return human_resources;
}
const output = human_resources.get({ plain: true });
output.subsidiary = await human_resources.getSubsidiary({
transaction,
});
return output;
}
static async findAll(filter, globalAccess, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userSubsidiary = (user && user.subsidiary?.id) || null;
if (userSubsidiary) {
if (options?.currentUser?.subsidiaryId) {
where.subsidiaryId = options.currentUser.subsidiaryId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.subsidiary,
as: 'subsidiary',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.employee_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'human_resources',
'employee_name',
filter.employee_name,
),
};
}
if (filter.shift) {
where = {
...where,
[Op.and]: Utils.ilike('human_resources', 'shift', filter.shift),
};
}
if (filter.payrollRange) {
const [start, end] = filter.payrollRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
payroll: {
...where.payroll,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
payroll: {
...where.payroll,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true',
};
}
if (filter.role) {
where = {
...where,
role: filter.role,
};
}
if (filter.subsidiary) {
const listItems = filter.subsidiary.split('|').map((item) => {
return Utils.uuid(item);
});
where = {
...where,
subsidiaryId: { [Op.or]: listItems },
};
}
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,
},
};
}
}
}
if (globalAccess) {
delete where.subsidiaryId;
}
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.human_resources.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,
globalAccess,
organizationId,
) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike('human_resources', 'employee_name', query),
],
};
}
const records = await db.human_resources.findAll({
attributes: ['id', 'employee_name'],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['employee_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.employee_name,
}));
}
};

View File

@ -0,0 +1,396 @@
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 InventoryDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const inventory = await db.inventory.create(
{
id: data.id || undefined,
product_name: data.product_name || null,
available_quantity: data.available_quantity || null,
reserved_quantity: data.reserved_quantity || null,
returned_quantity: data.returned_quantity || null,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await inventory.setSubsidiary(data.subsidiary || null, {
transaction,
});
return inventory;
}
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 inventoryData = data.map((item, index) => ({
id: item.id || undefined,
product_name: item.product_name || null,
available_quantity: item.available_quantity || null,
reserved_quantity: item.reserved_quantity || null,
returned_quantity: item.returned_quantity || null,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const inventory = await db.inventory.bulkCreate(inventoryData, {
transaction,
});
// For each item created, replace relation files
return inventory;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const inventory = await db.inventory.findByPk(id, {}, { transaction });
const updatePayload = {};
if (data.product_name !== undefined)
updatePayload.product_name = data.product_name;
if (data.available_quantity !== undefined)
updatePayload.available_quantity = data.available_quantity;
if (data.reserved_quantity !== undefined)
updatePayload.reserved_quantity = data.reserved_quantity;
if (data.returned_quantity !== undefined)
updatePayload.returned_quantity = data.returned_quantity;
updatePayload.updatedById = currentUser.id;
await inventory.update(updatePayload, { transaction });
if (data.subsidiary !== undefined) {
await inventory.setSubsidiary(
data.subsidiary,
{ transaction },
);
}
return inventory;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const inventory = await db.inventory.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of inventory) {
await record.update({ deletedBy: currentUser.id }, { transaction });
}
for (const record of inventory) {
await record.destroy({ transaction });
}
});
return inventory;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const inventory = await db.inventory.findByPk(id, options);
await inventory.update(
{
deletedBy: currentUser.id,
},
{
transaction,
},
);
await inventory.destroy({
transaction,
});
return inventory;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const inventory = await db.inventory.findOne({ where }, { transaction });
if (!inventory) {
return inventory;
}
const output = inventory.get({ plain: true });
output.subsidiary = await inventory.getSubsidiary({
transaction,
});
return output;
}
static async findAll(filter, globalAccess, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userSubsidiary = (user && user.subsidiary?.id) || null;
if (userSubsidiary) {
if (options?.currentUser?.subsidiaryId) {
where.subsidiaryId = options.currentUser.subsidiaryId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.subsidiary,
as: 'subsidiary',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.product_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'inventory',
'product_name',
filter.product_name,
),
};
}
if (filter.available_quantityRange) {
const [start, end] = filter.available_quantityRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
available_quantity: {
...where.available_quantity,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
available_quantity: {
...where.available_quantity,
[Op.lte]: end,
},
};
}
}
if (filter.reserved_quantityRange) {
const [start, end] = filter.reserved_quantityRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
reserved_quantity: {
...where.reserved_quantity,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
reserved_quantity: {
...where.reserved_quantity,
[Op.lte]: end,
},
};
}
}
if (filter.returned_quantityRange) {
const [start, end] = filter.returned_quantityRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
returned_quantity: {
...where.returned_quantity,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
returned_quantity: {
...where.returned_quantity,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true',
};
}
if (filter.subsidiary) {
const listItems = filter.subsidiary.split('|').map((item) => {
return Utils.uuid(item);
});
where = {
...where,
subsidiaryId: { [Op.or]: listItems },
};
}
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,
},
};
}
}
}
if (globalAccess) {
delete where.subsidiaryId;
}
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.inventory.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,
globalAccess,
organizationId,
) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike('inventory', 'product_name', query),
],
};
}
const records = await db.inventory.findAll({
attributes: ['id', 'product_name'],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['product_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.product_name,
}));
}
};

View File

@ -0,0 +1,367 @@
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 MachineryDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const machinery = await db.machinery.create(
{
id: data.id || undefined,
machine_name: data.machine_name || null,
maintenance_schedule: data.maintenance_schedule || null,
downtime_hours: data.downtime_hours || null,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await machinery.setSubsidiary(data.subsidiary || null, {
transaction,
});
return machinery;
}
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 machineryData = data.map((item, index) => ({
id: item.id || undefined,
machine_name: item.machine_name || null,
maintenance_schedule: item.maintenance_schedule || null,
downtime_hours: item.downtime_hours || null,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const machinery = await db.machinery.bulkCreate(machineryData, {
transaction,
});
// For each item created, replace relation files
return machinery;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const machinery = await db.machinery.findByPk(id, {}, { transaction });
const updatePayload = {};
if (data.machine_name !== undefined)
updatePayload.machine_name = data.machine_name;
if (data.maintenance_schedule !== undefined)
updatePayload.maintenance_schedule = data.maintenance_schedule;
if (data.downtime_hours !== undefined)
updatePayload.downtime_hours = data.downtime_hours;
updatePayload.updatedById = currentUser.id;
await machinery.update(updatePayload, { transaction });
if (data.subsidiary !== undefined) {
await machinery.setSubsidiary(
data.subsidiary,
{ transaction },
);
}
return machinery;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const machinery = await db.machinery.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of machinery) {
await record.update({ deletedBy: currentUser.id }, { transaction });
}
for (const record of machinery) {
await record.destroy({ transaction });
}
});
return machinery;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const machinery = await db.machinery.findByPk(id, options);
await machinery.update(
{
deletedBy: currentUser.id,
},
{
transaction,
},
);
await machinery.destroy({
transaction,
});
return machinery;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const machinery = await db.machinery.findOne({ where }, { transaction });
if (!machinery) {
return machinery;
}
const output = machinery.get({ plain: true });
output.subsidiary = await machinery.getSubsidiary({
transaction,
});
return output;
}
static async findAll(filter, globalAccess, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userSubsidiary = (user && user.subsidiary?.id) || null;
if (userSubsidiary) {
if (options?.currentUser?.subsidiaryId) {
where.subsidiaryId = options.currentUser.subsidiaryId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.subsidiary,
as: 'subsidiary',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.machine_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'machinery',
'machine_name',
filter.machine_name,
),
};
}
if (filter.maintenance_scheduleRange) {
const [start, end] = filter.maintenance_scheduleRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
maintenance_schedule: {
...where.maintenance_schedule,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
maintenance_schedule: {
...where.maintenance_schedule,
[Op.lte]: end,
},
};
}
}
if (filter.downtime_hoursRange) {
const [start, end] = filter.downtime_hoursRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
downtime_hours: {
...where.downtime_hours,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
downtime_hours: {
...where.downtime_hours,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true',
};
}
if (filter.subsidiary) {
const listItems = filter.subsidiary.split('|').map((item) => {
return Utils.uuid(item);
});
where = {
...where,
subsidiaryId: { [Op.or]: listItems },
};
}
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,
},
};
}
}
}
if (globalAccess) {
delete where.subsidiaryId;
}
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.machinery.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,
globalAccess,
organizationId,
) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike('machinery', 'machine_name', query),
],
};
}
const records = await db.machinery.findAll({
attributes: ['id', 'machine_name'],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['machine_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.machine_name,
}));
}
};

View File

@ -0,0 +1,257 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class 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 globalAccess = currentUser.app_role?.globalAccess;
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;
const user = (options && options.currentUser) || null;
const userSubsidiary = (user && user.subsidiary?.id) || null;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike('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,375 @@
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 Quality_controlDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const quality_control = await db.quality_control.create(
{
id: data.id || undefined,
check_name: data.check_name || null,
compliance: data.compliance || false,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await quality_control.setWork_order(data.work_order || null, {
transaction,
});
await quality_control.setSubsidiary(data.subsidiary || null, {
transaction,
});
return quality_control;
}
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 quality_controlData = data.map((item, index) => ({
id: item.id || undefined,
check_name: item.check_name || null,
compliance: item.compliance || false,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const quality_control = await db.quality_control.bulkCreate(
quality_controlData,
{ transaction },
);
// For each item created, replace relation files
return quality_control;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const quality_control = await db.quality_control.findByPk(
id,
{},
{ transaction },
);
const updatePayload = {};
if (data.check_name !== undefined)
updatePayload.check_name = data.check_name;
if (data.compliance !== undefined)
updatePayload.compliance = data.compliance;
updatePayload.updatedById = currentUser.id;
await quality_control.update(updatePayload, { transaction });
if (data.work_order !== undefined) {
await quality_control.setWork_order(
data.work_order,
{ transaction },
);
}
if (data.subsidiary !== undefined) {
await quality_control.setSubsidiary(
data.subsidiary,
{ transaction },
);
}
return quality_control;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const quality_control = await db.quality_control.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of quality_control) {
await record.update({ deletedBy: currentUser.id }, { transaction });
}
for (const record of quality_control) {
await record.destroy({ transaction });
}
});
return quality_control;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const quality_control = await db.quality_control.findByPk(id, options);
await quality_control.update(
{
deletedBy: currentUser.id,
},
{
transaction,
},
);
await quality_control.destroy({
transaction,
});
return quality_control;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const quality_control = await db.quality_control.findOne(
{ where },
{ transaction },
);
if (!quality_control) {
return quality_control;
}
const output = quality_control.get({ plain: true });
output.work_order = await quality_control.getWork_order({
transaction,
});
output.subsidiary = await quality_control.getSubsidiary({
transaction,
});
return output;
}
static async findAll(filter, globalAccess, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userSubsidiary = (user && user.subsidiary?.id) || null;
if (userSubsidiary) {
if (options?.currentUser?.subsidiaryId) {
where.subsidiaryId = options.currentUser.subsidiaryId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.work_orders,
as: 'work_order',
where: filter.work_order
? {
[Op.or]: [
{
id: {
[Op.in]: filter.work_order
.split('|')
.map((term) => Utils.uuid(term)),
},
},
{
order_number: {
[Op.or]: filter.work_order
.split('|')
.map((term) => ({ [Op.iLike]: `%${term}%` })),
},
},
],
}
: {},
},
{
model: db.subsidiary,
as: 'subsidiary',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.check_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'quality_control',
'check_name',
filter.check_name,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true',
};
}
if (filter.compliance) {
where = {
...where,
compliance: filter.compliance,
};
}
if (filter.subsidiary) {
const listItems = filter.subsidiary.split('|').map((item) => {
return Utils.uuid(item);
});
where = {
...where,
subsidiaryId: { [Op.or]: listItems },
};
}
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,
},
};
}
}
}
if (globalAccess) {
delete where.subsidiaryId;
}
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.quality_control.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,
globalAccess,
organizationId,
) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike('quality_control', 'check_name', query),
],
};
}
const records = await db.quality_control.findAll({
attributes: ['id', 'check_name'],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['check_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.check_name,
}));
}
};

View File

@ -0,0 +1,375 @@
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 Raw_materialsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const raw_materials = await db.raw_materials.create(
{
id: data.id || undefined,
material_name: data.material_name || null,
quantity: data.quantity || null,
reorder_level: data.reorder_level || null,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await raw_materials.setSubsidiary(data.subsidiary || null, {
transaction,
});
return raw_materials;
}
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 raw_materialsData = data.map((item, index) => ({
id: item.id || undefined,
material_name: item.material_name || null,
quantity: item.quantity || null,
reorder_level: item.reorder_level || null,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const raw_materials = await db.raw_materials.bulkCreate(raw_materialsData, {
transaction,
});
// For each item created, replace relation files
return raw_materials;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const raw_materials = await db.raw_materials.findByPk(
id,
{},
{ transaction },
);
const updatePayload = {};
if (data.material_name !== undefined)
updatePayload.material_name = data.material_name;
if (data.quantity !== undefined) updatePayload.quantity = data.quantity;
if (data.reorder_level !== undefined)
updatePayload.reorder_level = data.reorder_level;
updatePayload.updatedById = currentUser.id;
await raw_materials.update(updatePayload, { transaction });
if (data.subsidiary !== undefined) {
await raw_materials.setSubsidiary(
data.subsidiary,
{ transaction },
);
}
return raw_materials;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const raw_materials = await db.raw_materials.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of raw_materials) {
await record.update({ deletedBy: currentUser.id }, { transaction });
}
for (const record of raw_materials) {
await record.destroy({ transaction });
}
});
return raw_materials;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const raw_materials = await db.raw_materials.findByPk(id, options);
await raw_materials.update(
{
deletedBy: currentUser.id,
},
{
transaction,
},
);
await raw_materials.destroy({
transaction,
});
return raw_materials;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const raw_materials = await db.raw_materials.findOne(
{ where },
{ transaction },
);
if (!raw_materials) {
return raw_materials;
}
const output = raw_materials.get({ plain: true });
output.subsidiary = await raw_materials.getSubsidiary({
transaction,
});
return output;
}
static async findAll(filter, globalAccess, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userSubsidiary = (user && user.subsidiary?.id) || null;
if (userSubsidiary) {
if (options?.currentUser?.subsidiaryId) {
where.subsidiaryId = options.currentUser.subsidiaryId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.subsidiary,
as: 'subsidiary',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.material_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'raw_materials',
'material_name',
filter.material_name,
),
};
}
if (filter.quantityRange) {
const [start, end] = filter.quantityRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
quantity: {
...where.quantity,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
quantity: {
...where.quantity,
[Op.lte]: end,
},
};
}
}
if (filter.reorder_levelRange) {
const [start, end] = filter.reorder_levelRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
reorder_level: {
...where.reorder_level,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
reorder_level: {
...where.reorder_level,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true',
};
}
if (filter.subsidiary) {
const listItems = filter.subsidiary.split('|').map((item) => {
return Utils.uuid(item);
});
where = {
...where,
subsidiaryId: { [Op.or]: listItems },
};
}
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,
},
};
}
}
}
if (globalAccess) {
delete where.subsidiaryId;
}
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.raw_materials.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,
globalAccess,
organizationId,
) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike('raw_materials', 'material_name', query),
],
};
}
const records = await db.raw_materials.findAll({
attributes: ['id', 'material_name'],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['material_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.material_name,
}));
}
};

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

@ -0,0 +1,343 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const config = require('../../config');
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,
globalAccess: data.globalAccess || false,
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,
globalAccess: item.globalAccess || false,
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 globalAccess = currentUser.app_role?.globalAccess;
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;
if (data.globalAccess !== undefined)
updatePayload.globalAccess = data.globalAccess;
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, globalAccess, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userSubsidiary = (user && user.subsidiary?.id) || null;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.permissions,
as: 'permissions',
},
];
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.globalAccess) {
where = {
...where,
globalAccess: filter.globalAccess,
};
}
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,
},
};
}
}
}
if (!globalAccess) {
where = { name: { [Op.ne]: config.roles.super_admin } };
}
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, globalAccess) {
let where = {};
if (!globalAccess) {
where = { name: { [Op.ne]: config.roles.super_admin } };
}
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,340 @@
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 SubsidiariesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const subsidiaries = await db.subsidiaries.create(
{
id: data.id || undefined,
name: data.name || null,
address: data.address || null,
contact_number: data.contact_number || null,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await subsidiaries.setSubsidiary(data.subsidiary || null, {
transaction,
});
return subsidiaries;
}
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 subsidiariesData = data.map((item, index) => ({
id: item.id || undefined,
name: item.name || null,
address: item.address || null,
contact_number: item.contact_number || null,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const subsidiaries = await db.subsidiaries.bulkCreate(subsidiariesData, {
transaction,
});
// For each item created, replace relation files
return subsidiaries;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const subsidiaries = await db.subsidiaries.findByPk(
id,
{},
{ transaction },
);
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
if (data.address !== undefined) updatePayload.address = data.address;
if (data.contact_number !== undefined)
updatePayload.contact_number = data.contact_number;
updatePayload.updatedById = currentUser.id;
await subsidiaries.update(updatePayload, { transaction });
if (data.subsidiary !== undefined) {
await subsidiaries.setSubsidiary(
data.subsidiary,
{ transaction },
);
}
return subsidiaries;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const subsidiaries = await db.subsidiaries.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of subsidiaries) {
await record.update({ deletedBy: currentUser.id }, { transaction });
}
for (const record of subsidiaries) {
await record.destroy({ transaction });
}
});
return subsidiaries;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const subsidiaries = await db.subsidiaries.findByPk(id, options);
await subsidiaries.update(
{
deletedBy: currentUser.id,
},
{
transaction,
},
);
await subsidiaries.destroy({
transaction,
});
return subsidiaries;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const subsidiaries = await db.subsidiaries.findOne(
{ where },
{ transaction },
);
if (!subsidiaries) {
return subsidiaries;
}
const output = subsidiaries.get({ plain: true });
output.subsidiary = await subsidiaries.getSubsidiary({
transaction,
});
return output;
}
static async findAll(filter, globalAccess, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userSubsidiary = (user && user.subsidiary?.id) || null;
if (userSubsidiary) {
if (options?.currentUser?.subsidiaryId) {
where.subsidiaryId = options.currentUser.subsidiaryId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.subsidiary,
as: 'subsidiary',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.name) {
where = {
...where,
[Op.and]: Utils.ilike('subsidiaries', 'name', filter.name),
};
}
if (filter.address) {
where = {
...where,
[Op.and]: Utils.ilike('subsidiaries', 'address', filter.address),
};
}
if (filter.contact_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'subsidiaries',
'contact_number',
filter.contact_number,
),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true',
};
}
if (filter.subsidiary) {
const listItems = filter.subsidiary.split('|').map((item) => {
return Utils.uuid(item);
});
where = {
...where,
subsidiaryId: { [Op.or]: listItems },
};
}
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,
},
};
}
}
}
if (globalAccess) {
delete where.subsidiaryId;
}
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.subsidiaries.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,
globalAccess,
organizationId,
) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike('subsidiaries', 'name', query),
],
};
}
const records = await db.subsidiaries.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,312 @@
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 SubsidiaryDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const subsidiary = await db.subsidiary.create(
{
id: data.id || undefined,
name: data.name || null,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return subsidiary;
}
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 subsidiaryData = 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 subsidiary = await db.subsidiary.bulkCreate(subsidiaryData, {
transaction,
});
// For each item created, replace relation files
return subsidiary;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const subsidiary = await db.subsidiary.findByPk(id, {}, { transaction });
const updatePayload = {};
if (data.name !== undefined) updatePayload.name = data.name;
updatePayload.updatedById = currentUser.id;
await subsidiary.update(updatePayload, { transaction });
return subsidiary;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const subsidiary = await db.subsidiary.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of subsidiary) {
await record.update({ deletedBy: currentUser.id }, { transaction });
}
for (const record of subsidiary) {
await record.destroy({ transaction });
}
});
return subsidiary;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const subsidiary = await db.subsidiary.findByPk(id, options);
await subsidiary.update(
{
deletedBy: currentUser.id,
},
{
transaction,
},
);
await subsidiary.destroy({
transaction,
});
return subsidiary;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const subsidiary = await db.subsidiary.findOne({ where }, { transaction });
if (!subsidiary) {
return subsidiary;
}
const output = subsidiary.get({ plain: true });
output.users_subsidiary = await subsidiary.getUsers_subsidiary({
transaction,
});
output.human_resources_subsidiary =
await subsidiary.getHuman_resources_subsidiary({
transaction,
});
output.inventory_subsidiary = await subsidiary.getInventory_subsidiary({
transaction,
});
output.machinery_subsidiary = await subsidiary.getMachinery_subsidiary({
transaction,
});
output.quality_control_subsidiary =
await subsidiary.getQuality_control_subsidiary({
transaction,
});
output.raw_materials_subsidiary =
await subsidiary.getRaw_materials_subsidiary({
transaction,
});
output.subsidiaries_subsidiary =
await subsidiary.getSubsidiaries_subsidiary({
transaction,
});
output.suppliers_subsidiary = await subsidiary.getSuppliers_subsidiary({
transaction,
});
output.work_orders_subsidiary = await subsidiary.getWork_orders_subsidiary({
transaction,
});
return output;
}
static async findAll(filter, globalAccess, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userSubsidiary = (user && user.subsidiary?.id) || null;
if (userSubsidiary) {
if (options?.currentUser?.subsidiaryId) {
where.subsidiaryId = options.currentUser.subsidiaryId;
}
}
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('subsidiary', '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,
},
};
}
}
}
if (globalAccess) {
delete where.subsidiaryId;
}
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.subsidiary.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,
globalAccess,
organizationId,
) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike('subsidiary', 'name', query),
],
};
}
const records = await db.subsidiary.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,405 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class SuppliersDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const suppliers = await db.suppliers.create(
{
id: data.id || undefined,
supplier_name: data.supplier_name || null,
contract_terms: data.contract_terms || null,
delivery_schedule: data.delivery_schedule || null,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await suppliers.setSubsidiary(data.subsidiary || null, {
transaction,
});
await suppliers.setMaterials_supplied(data.materials_supplied || [], {
transaction,
});
return suppliers;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const suppliersData = data.map((item, index) => ({
id: item.id || undefined,
supplier_name: item.supplier_name || null,
contract_terms: item.contract_terms || null,
delivery_schedule: item.delivery_schedule || null,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const suppliers = await db.suppliers.bulkCreate(suppliersData, {
transaction,
});
// For each item created, replace relation files
return suppliers;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const suppliers = await db.suppliers.findByPk(id, {}, { transaction });
const updatePayload = {};
if (data.supplier_name !== undefined)
updatePayload.supplier_name = data.supplier_name;
if (data.contract_terms !== undefined)
updatePayload.contract_terms = data.contract_terms;
if (data.delivery_schedule !== undefined)
updatePayload.delivery_schedule = data.delivery_schedule;
updatePayload.updatedById = currentUser.id;
await suppliers.update(updatePayload, { transaction });
if (data.subsidiary !== undefined) {
await suppliers.setSubsidiary(
data.subsidiary,
{ transaction },
);
}
if (data.materials_supplied !== undefined) {
await suppliers.setMaterials_supplied(data.materials_supplied, {
transaction,
});
}
return suppliers;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const suppliers = await db.suppliers.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of suppliers) {
await record.update({ deletedBy: currentUser.id }, { transaction });
}
for (const record of suppliers) {
await record.destroy({ transaction });
}
});
return suppliers;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const suppliers = await db.suppliers.findByPk(id, options);
await suppliers.update(
{
deletedBy: currentUser.id,
},
{
transaction,
},
);
await suppliers.destroy({
transaction,
});
return suppliers;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const suppliers = await db.suppliers.findOne({ where }, { transaction });
if (!suppliers) {
return suppliers;
}
const output = suppliers.get({ plain: true });
output.materials_supplied = await suppliers.getMaterials_supplied({
transaction,
});
output.subsidiary = await suppliers.getSubsidiary({
transaction,
});
return output;
}
static async findAll(filter, globalAccess, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userSubsidiary = (user && user.subsidiary?.id) || null;
if (userSubsidiary) {
if (options?.currentUser?.subsidiaryId) {
where.subsidiaryId = options.currentUser.subsidiaryId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.subsidiary,
as: 'subsidiary',
},
{
model: db.raw_materials,
as: 'materials_supplied',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.supplier_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'suppliers',
'supplier_name',
filter.supplier_name,
),
};
}
if (filter.contract_terms) {
where = {
...where,
[Op.and]: Utils.ilike(
'suppliers',
'contract_terms',
filter.contract_terms,
),
};
}
if (filter.delivery_scheduleRange) {
const [start, end] = filter.delivery_scheduleRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
delivery_schedule: {
...where.delivery_schedule,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
delivery_schedule: {
...where.delivery_schedule,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true',
};
}
if (filter.subsidiary) {
const listItems = filter.subsidiary.split('|').map((item) => {
return Utils.uuid(item);
});
where = {
...where,
subsidiaryId: { [Op.or]: listItems },
};
}
if (filter.materials_supplied) {
const searchTerms = filter.materials_supplied.split('|');
include = [
{
model: db.raw_materials,
as: 'materials_supplied_filter',
required: searchTerms.length > 0,
where:
searchTerms.length > 0
? {
[Op.or]: [
{
id: {
[Op.in]: searchTerms.map((term) => Utils.uuid(term)),
},
},
{
material_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,
},
};
}
}
}
if (globalAccess) {
delete where.subsidiaryId;
}
const queryOptions = {
where,
include,
distinct: true,
order:
filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log,
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.suppliers.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count,
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(
query,
limit,
offset,
globalAccess,
organizationId,
) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike('suppliers', 'supplier_name', query),
],
};
}
const records = await db.suppliers.findAll({
attributes: ['id', 'supplier_name'],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['supplier_name', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.supplier_name,
}));
}
};

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

@ -0,0 +1,803 @@
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, globalAccess, 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.setSubsidiary(data.data.subsidiary || 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, globalAccess, 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.subsidiary !== undefined) {
await users.setSubsidiary(
data.subsidiary,
{ 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.work_orders_assigned_to = await users.getWork_orders_assigned_to({
transaction,
});
output.avatar = await users.getAvatar({
transaction,
});
output.app_role = await users.getApp_role({
transaction,
});
if (output.app_role) {
output.app_role_permissions = await output.app_role.getPermissions({
transaction,
});
}
output.custom_permissions = await users.getCustom_permissions({
transaction,
});
output.subsidiary = await users.getSubsidiary({
transaction,
});
return output;
}
static async findAll(filter, globalAccess, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userSubsidiary = (user && user.subsidiary?.id) || null;
if (userSubsidiary) {
if (options?.currentUser?.subsidiaryId) {
where.subsidiaryId = options.currentUser.subsidiaryId;
}
}
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.subsidiary,
as: 'subsidiary',
},
{
model: db.permissions,
as: 'custom_permissions',
},
{
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.subsidiary) {
const listItems = filter.subsidiary.split('|').map((item) => {
return Utils.uuid(item);
});
where = {
...where,
subsidiaryId: { [Op.or]: listItems },
};
}
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,
},
};
}
}
}
if (globalAccess) {
delete where.subsidiaryId;
}
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,
globalAccess,
organizationId,
) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
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,
organizationId: data.organizationId,
},
{ transaction },
);
const app_role = await db.roles.findOne({
where: { name: '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,485 @@
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class Work_ordersDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const work_orders = await db.work_orders.create(
{
id: data.id || undefined,
order_number: data.order_number || null,
start_date: data.start_date || null,
end_date: data.end_date || null,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await work_orders.setAssigned_to(data.assigned_to || null, {
transaction,
});
await work_orders.setSubsidiary(data.subsidiary || null, {
transaction,
});
await work_orders.setMaterials(data.materials || [], {
transaction,
});
return work_orders;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const work_ordersData = data.map((item, index) => ({
id: item.id || undefined,
order_number: item.order_number || null,
start_date: item.start_date || null,
end_date: item.end_date || null,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const work_orders = await db.work_orders.bulkCreate(work_ordersData, {
transaction,
});
// For each item created, replace relation files
return work_orders;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const globalAccess = currentUser.app_role?.globalAccess;
const work_orders = await db.work_orders.findByPk(id, {}, { transaction });
const updatePayload = {};
if (data.order_number !== undefined)
updatePayload.order_number = data.order_number;
if (data.start_date !== undefined)
updatePayload.start_date = data.start_date;
if (data.end_date !== undefined) updatePayload.end_date = data.end_date;
updatePayload.updatedById = currentUser.id;
await work_orders.update(updatePayload, { transaction });
if (data.assigned_to !== undefined) {
await work_orders.setAssigned_to(
data.assigned_to,
{ transaction },
);
}
if (data.subsidiary !== undefined) {
await work_orders.setSubsidiary(
data.subsidiary,
{ transaction },
);
}
if (data.materials !== undefined) {
await work_orders.setMaterials(data.materials, { transaction });
}
return work_orders;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const work_orders = await db.work_orders.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of work_orders) {
await record.update({ deletedBy: currentUser.id }, { transaction });
}
for (const record of work_orders) {
await record.destroy({ transaction });
}
});
return work_orders;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const work_orders = await db.work_orders.findByPk(id, options);
await work_orders.update(
{
deletedBy: currentUser.id,
},
{
transaction,
},
);
await work_orders.destroy({
transaction,
});
return work_orders;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const work_orders = await db.work_orders.findOne(
{ where },
{ transaction },
);
if (!work_orders) {
return work_orders;
}
const output = work_orders.get({ plain: true });
output.quality_control_work_order =
await work_orders.getQuality_control_work_order({
transaction,
});
output.materials = await work_orders.getMaterials({
transaction,
});
output.assigned_to = await work_orders.getAssigned_to({
transaction,
});
output.subsidiary = await work_orders.getSubsidiary({
transaction,
});
return output;
}
static async findAll(filter, globalAccess, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
const user = (options && options.currentUser) || null;
const userSubsidiary = (user && user.subsidiary?.id) || null;
if (userSubsidiary) {
if (options?.currentUser?.subsidiaryId) {
where.subsidiaryId = options.currentUser.subsidiaryId;
}
}
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.users,
as: 'assigned_to',
where: filter.assigned_to
? {
[Op.or]: [
{
id: {
[Op.in]: filter.assigned_to
.split('|')
.map((term) => Utils.uuid(term)),
},
},
{
firstName: {
[Op.or]: filter.assigned_to
.split('|')
.map((term) => ({ [Op.iLike]: `%${term}%` })),
},
},
],
}
: {},
},
{
model: db.subsidiary,
as: 'subsidiary',
},
{
model: db.raw_materials,
as: 'materials',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.order_number) {
where = {
...where,
[Op.and]: Utils.ilike(
'work_orders',
'order_number',
filter.order_number,
),
};
}
if (filter.calendarStart && filter.calendarEnd) {
where = {
...where,
[Op.or]: [
{
start_date: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
{
end_date: {
[Op.between]: [filter.calendarStart, filter.calendarEnd],
},
},
],
};
}
if (filter.start_dateRange) {
const [start, end] = filter.start_dateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
start_date: {
...where.start_date,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
start_date: {
...where.start_date,
[Op.lte]: end,
},
};
}
}
if (filter.end_dateRange) {
const [start, end] = filter.end_dateRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
end_date: {
...where.end_date,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
end_date: {
...where.end_date,
[Op.lte]: end,
},
};
}
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true',
};
}
if (filter.subsidiary) {
const listItems = filter.subsidiary.split('|').map((item) => {
return Utils.uuid(item);
});
where = {
...where,
subsidiaryId: { [Op.or]: listItems },
};
}
if (filter.materials) {
const searchTerms = filter.materials.split('|');
include = [
{
model: db.raw_materials,
as: 'materials_filter',
required: searchTerms.length > 0,
where:
searchTerms.length > 0
? {
[Op.or]: [
{
id: {
[Op.in]: searchTerms.map((term) => Utils.uuid(term)),
},
},
{
material_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,
},
};
}
}
}
if (globalAccess) {
delete where.subsidiaryId;
}
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.work_orders.findAndCountAll(
queryOptions,
);
return {
rows: options?.countOnly ? [] : rows,
count: count,
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(
query,
limit,
offset,
globalAccess,
organizationId,
) {
let where = {};
if (!globalAccess && organizationId) {
where.organizationId = organizationId;
}
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike('work_orders', 'order_number', query),
],
};
}
const records = await db.work_orders.findAll({
attributes: ['id', 'order_number'],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['order_number', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.order_number,
}));
}
};

View File

@ -0,0 +1,31 @@
module.exports = {
production: {
dialect: 'postgres',
username: process.env.DB_USER,
password: process.env.DB_PASS,
database: process.env.DB_NAME,
host: process.env.DB_HOST,
port: process.env.DB_PORT,
logging: console.log,
seederStorage: 'sequelize',
},
development: {
username: 'postgres',
dialect: 'postgres',
password: '',
database: 'db_gmw_erp',
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,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,71 @@
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 human_resources = sequelize.define(
'human_resources',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
employee_name: {
type: DataTypes.TEXT,
},
role: {
type: DataTypes.ENUM,
values: ['skilled_labor', 'managerial_staff'],
},
shift: {
type: DataTypes.TEXT,
},
payroll: {
type: DataTypes.DECIMAL,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
human_resources.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.human_resources.belongsTo(db.subsidiary, {
as: 'subsidiary',
foreignKey: {
name: 'subsidiaryId',
},
constraints: false,
});
db.human_resources.belongsTo(db.users, {
as: 'createdBy',
});
db.human_resources.belongsTo(db.users, {
as: 'updatedBy',
});
};
return human_resources;
};

View File

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

View File

@ -0,0 +1,69 @@
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 inventory = sequelize.define(
'inventory',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
product_name: {
type: DataTypes.TEXT,
},
available_quantity: {
type: DataTypes.INTEGER,
},
reserved_quantity: {
type: DataTypes.INTEGER,
},
returned_quantity: {
type: DataTypes.INTEGER,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
inventory.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.inventory.belongsTo(db.subsidiary, {
as: 'subsidiary',
foreignKey: {
name: 'subsidiaryId',
},
constraints: false,
});
db.inventory.belongsTo(db.users, {
as: 'createdBy',
});
db.inventory.belongsTo(db.users, {
as: 'updatedBy',
});
};
return inventory;
};

View File

@ -0,0 +1,65 @@
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 machinery = sequelize.define(
'machinery',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
machine_name: {
type: DataTypes.TEXT,
},
maintenance_schedule: {
type: DataTypes.DATE,
},
downtime_hours: {
type: DataTypes.INTEGER,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
machinery.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.machinery.belongsTo(db.subsidiary, {
as: 'subsidiary',
foreignKey: {
name: 'subsidiaryId',
},
constraints: false,
});
db.machinery.belongsTo(db.users, {
as: 'createdBy',
});
db.machinery.belongsTo(db.users, {
as: 'updatedBy',
});
};
return machinery;
};

View File

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

View File

@ -0,0 +1,72 @@
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 quality_control = sequelize.define(
'quality_control',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
check_name: {
type: DataTypes.TEXT,
},
compliance: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
quality_control.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.quality_control.belongsTo(db.work_orders, {
as: 'work_order',
foreignKey: {
name: 'work_orderId',
},
constraints: false,
});
db.quality_control.belongsTo(db.subsidiary, {
as: 'subsidiary',
foreignKey: {
name: 'subsidiaryId',
},
constraints: false,
});
db.quality_control.belongsTo(db.users, {
as: 'createdBy',
});
db.quality_control.belongsTo(db.users, {
as: 'updatedBy',
});
};
return quality_control;
};

View File

@ -0,0 +1,65 @@
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 raw_materials = sequelize.define(
'raw_materials',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
material_name: {
type: DataTypes.TEXT,
},
quantity: {
type: DataTypes.INTEGER,
},
reorder_level: {
type: DataTypes.INTEGER,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
raw_materials.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.raw_materials.belongsTo(db.subsidiary, {
as: 'subsidiary',
foreignKey: {
name: 'subsidiaryId',
},
constraints: false,
});
db.raw_materials.belongsTo(db.users, {
as: 'createdBy',
});
db.raw_materials.belongsTo(db.users, {
as: 'updatedBy',
});
};
return raw_materials;
};

View File

@ -0,0 +1,86 @@
const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');
module.exports = function (sequelize, DataTypes) {
const roles = sequelize.define(
'roles',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
role_customization: {
type: DataTypes.TEXT,
},
globalAccess: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false,
},
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,65 @@
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 subsidiaries = sequelize.define(
'subsidiaries',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.TEXT,
},
address: {
type: DataTypes.TEXT,
},
contact_number: {
type: DataTypes.TEXT,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
subsidiaries.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.subsidiaries.belongsTo(db.subsidiary, {
as: 'subsidiary',
foreignKey: {
name: 'subsidiaryId',
},
constraints: false,
});
db.subsidiaries.belongsTo(db.users, {
as: 'createdBy',
});
db.subsidiaries.belongsTo(db.users, {
as: 'updatedBy',
});
};
return subsidiaries;
};

View File

@ -0,0 +1,121 @@
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 subsidiary = sequelize.define(
'subsidiary',
{
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,
},
);
subsidiary.associate = (db) => {
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.subsidiary.hasMany(db.users, {
as: 'users_subsidiary',
foreignKey: {
name: 'subsidiaryId',
},
constraints: false,
});
db.subsidiary.hasMany(db.human_resources, {
as: 'human_resources_subsidiary',
foreignKey: {
name: 'subsidiaryId',
},
constraints: false,
});
db.subsidiary.hasMany(db.inventory, {
as: 'inventory_subsidiary',
foreignKey: {
name: 'subsidiaryId',
},
constraints: false,
});
db.subsidiary.hasMany(db.machinery, {
as: 'machinery_subsidiary',
foreignKey: {
name: 'subsidiaryId',
},
constraints: false,
});
db.subsidiary.hasMany(db.quality_control, {
as: 'quality_control_subsidiary',
foreignKey: {
name: 'subsidiaryId',
},
constraints: false,
});
db.subsidiary.hasMany(db.raw_materials, {
as: 'raw_materials_subsidiary',
foreignKey: {
name: 'subsidiaryId',
},
constraints: false,
});
db.subsidiary.hasMany(db.subsidiaries, {
as: 'subsidiaries_subsidiary',
foreignKey: {
name: 'subsidiaryId',
},
constraints: false,
});
db.subsidiary.hasMany(db.suppliers, {
as: 'suppliers_subsidiary',
foreignKey: {
name: 'subsidiaryId',
},
constraints: false,
});
db.subsidiary.hasMany(db.work_orders, {
as: 'work_orders_subsidiary',
foreignKey: {
name: 'subsidiaryId',
},
constraints: false,
});
//end loop
db.subsidiary.belongsTo(db.users, {
as: 'createdBy',
});
db.subsidiary.belongsTo(db.users, {
as: 'updatedBy',
});
};
return subsidiary;
};

View File

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

View File

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

View File

@ -0,0 +1,99 @@
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 work_orders = sequelize.define(
'work_orders',
{
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
order_number: {
type: DataTypes.TEXT,
},
start_date: {
type: DataTypes.DATE,
},
end_date: {
type: DataTypes.DATE,
},
importHash: {
type: DataTypes.STRING(255),
allowNull: true,
unique: true,
},
},
{
timestamps: true,
paranoid: true,
freezeTableName: true,
},
);
work_orders.associate = (db) => {
db.work_orders.belongsToMany(db.raw_materials, {
as: 'materials',
foreignKey: {
name: 'work_orders_materialsId',
},
constraints: false,
through: 'work_ordersMaterialsRaw_materials',
});
db.work_orders.belongsToMany(db.raw_materials, {
as: 'materials_filter',
foreignKey: {
name: 'work_orders_materialsId',
},
constraints: false,
through: 'work_ordersMaterialsRaw_materials',
});
/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity
db.work_orders.hasMany(db.quality_control, {
as: 'quality_control_work_order',
foreignKey: {
name: 'work_orderId',
},
constraints: false,
});
//end loop
db.work_orders.belongsTo(db.users, {
as: 'assigned_to',
foreignKey: {
name: 'assigned_toId',
},
constraints: false,
});
db.work_orders.belongsTo(db.subsidiary, {
as: 'subsidiary',
foreignKey: {
name: 'subsidiaryId',
},
constraints: false,
});
db.work_orders.belongsTo(db.users, {
as: 'createdBy',
});
db.work_orders.belongsTo(db.users, {
as: 'updatedBy',
});
};
return work_orders;
};

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,80 @@
'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',
'ab4cf9bf-4eef-4107-b73d-9d0274cf69bc',
];
module.exports = {
up: async (queryInterface, Sequelize) => {
let hash = bcrypt.hashSync(config.admin_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: hash,
createdAt: new Date(),
updatedAt: new Date(),
},
{
id: ids[1],
firstName: 'John',
email: 'john@doe.com',
emailVerified: true,
provider: config.providers.LOCAL,
password: hash,
createdAt: new Date(),
updatedAt: new Date(),
},
{
id: ids[2],
firstName: 'Client',
email: 'client@hello.com',
emailVerified: true,
provider: config.providers.LOCAL,
password: hash,
createdAt: new Date(),
updatedAt: new Date(),
},
{
id: ids[3],
firstName: 'Super Admin',
email: 'super_admin@flatlogic.com',
emailVerified: true,
provider: config.providers.LOCAL,
password: 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

View File

@ -0,0 +1,783 @@
const db = require('../models');
const Users = db.users;
const HumanResources = db.human_resources;
const Inventory = db.inventory;
const Machinery = db.machinery;
const QualityControl = db.quality_control;
const RawMaterials = db.raw_materials;
const Subsidiaries = db.subsidiaries;
const Suppliers = db.suppliers;
const WorkOrders = db.work_orders;
const Subsidiary = db.subsidiary;
const HumanResourcesData = [
{
employee_name: 'John Doe',
role: 'skilled_labor',
shift: 'Day',
payroll: 50000,
// type code here for "relation_one" field
},
{
employee_name: 'Jane Smith',
role: 'managerial_staff',
shift: 'Night',
payroll: 75000,
// type code here for "relation_one" field
},
{
employee_name: 'Alice Johnson',
role: 'managerial_staff',
shift: 'Day',
payroll: 52000,
// type code here for "relation_one" field
},
];
const InventoryData = [
{
product_name: 'Widget A',
available_quantity: 200,
reserved_quantity: 50,
returned_quantity: 10,
// type code here for "relation_one" field
},
{
product_name: 'Gadget B',
available_quantity: 150,
reserved_quantity: 30,
returned_quantity: 5,
// type code here for "relation_one" field
},
{
product_name: 'Device C',
available_quantity: 300,
reserved_quantity: 70,
returned_quantity: 20,
// type code here for "relation_one" field
},
];
const MachineryData = [
{
machine_name: 'CNC Lathe',
maintenance_schedule: new Date('2023-12-01T10:00:00Z'),
downtime_hours: 5,
// type code here for "relation_one" field
},
{
machine_name: 'Injection Molder',
maintenance_schedule: new Date('2023-12-05T10:00:00Z'),
downtime_hours: 3,
// type code here for "relation_one" field
},
{
machine_name: 'Laser Cutter',
maintenance_schedule: new Date('2023-12-10T10:00:00Z'),
downtime_hours: 2,
// type code here for "relation_one" field
},
];
const QualityControlData = [
{
check_name: 'Initial Inspection',
// type code here for "relation_one" field
compliance: true,
// type code here for "relation_one" field
},
{
check_name: 'Mid-Process Check',
// type code here for "relation_one" field
compliance: false,
// type code here for "relation_one" field
},
{
check_name: 'Final Inspection',
// type code here for "relation_one" field
compliance: true,
// type code here for "relation_one" field
},
];
const RawMaterialsData = [
{
material_name: 'Steel Rods',
quantity: 500,
reorder_level: 100,
// type code here for "relation_one" field
},
{
material_name: 'Copper Wires',
quantity: 300,
reorder_level: 50,
// type code here for "relation_one" field
},
{
material_name: 'Plastic Sheets',
quantity: 1000,
reorder_level: 200,
// type code here for "relation_one" field
},
];
const SubsidiariesData = [
{
name: 'Edwin Hubble',
address: 'Euclid',
contact_number: 'Frederick Sanger',
// type code here for "relation_one" field
},
{
name: 'Euclid',
address: 'Andreas Vesalius',
contact_number: 'Ernst Haeckel',
// type code here for "relation_one" field
},
{
name: 'Lucretius',
address: 'Neils Bohr',
contact_number: 'Edward O. Wilson',
// type code here for "relation_one" field
},
];
const SuppliersData = [
{
supplier_name: 'Global Metals Inc.',
contract_terms: 'Annual',
delivery_schedule: new Date('2023-11-30T09:00:00Z'),
// type code here for "relation_many" field
// type code here for "relation_one" field
},
{
supplier_name: 'Plastics Plus',
contract_terms: 'Bi-Annual',
delivery_schedule: new Date('2023-12-15T09:00:00Z'),
// type code here for "relation_many" field
// type code here for "relation_one" field
},
{
supplier_name: 'Copper Connections',
contract_terms: 'Quarterly',
delivery_schedule: new Date('2023-12-01T09:00:00Z'),
// type code here for "relation_many" field
// type code here for "relation_one" field
},
];
const WorkOrdersData = [
{
order_number: 'WO-001',
// type code here for "relation_many" field
// type code here for "relation_one" field
start_date: new Date('2023-11-01T08:00:00Z'),
end_date: new Date('2023-11-05T17:00:00Z'),
// type code here for "relation_one" field
},
{
order_number: 'WO-002',
// type code here for "relation_many" field
// type code here for "relation_one" field
start_date: new Date('2023-11-06T08:00:00Z'),
end_date: new Date('2023-11-10T17:00:00Z'),
// type code here for "relation_one" field
},
{
order_number: 'WO-003',
// type code here for "relation_many" field
// type code here for "relation_one" field
start_date: new Date('2023-11-11T08:00:00Z'),
end_date: new Date('2023-11-15T17:00:00Z'),
// type code here for "relation_one" field
},
];
const SubsidiaryData = [
{
name: 'Ernst Mayr',
},
{
name: 'Edward O. Wilson',
},
{
name: 'Alfred Wegener',
},
];
// Similar logic for "relation_many"
async function associateUserWithSubsidiary() {
const relatedSubsidiary0 = await Subsidiary.findOne({
offset: Math.floor(Math.random() * (await Subsidiary.count())),
});
const User0 = await Users.findOne({
order: [['id', 'ASC']],
offset: 0,
});
if (User0?.setSubsidiary) {
await User0.setSubsidiary(relatedSubsidiary0);
}
const relatedSubsidiary1 = await Subsidiary.findOne({
offset: Math.floor(Math.random() * (await Subsidiary.count())),
});
const User1 = await Users.findOne({
order: [['id', 'ASC']],
offset: 1,
});
if (User1?.setSubsidiary) {
await User1.setSubsidiary(relatedSubsidiary1);
}
const relatedSubsidiary2 = await Subsidiary.findOne({
offset: Math.floor(Math.random() * (await Subsidiary.count())),
});
const User2 = await Users.findOne({
order: [['id', 'ASC']],
offset: 2,
});
if (User2?.setSubsidiary) {
await User2.setSubsidiary(relatedSubsidiary2);
}
}
async function associateHumanResourceWithSubsidiary() {
const relatedSubsidiary0 = await Subsidiary.findOne({
offset: Math.floor(Math.random() * (await Subsidiary.count())),
});
const HumanResource0 = await HumanResources.findOne({
order: [['id', 'ASC']],
offset: 0,
});
if (HumanResource0?.setSubsidiary) {
await HumanResource0.setSubsidiary(relatedSubsidiary0);
}
const relatedSubsidiary1 = await Subsidiary.findOne({
offset: Math.floor(Math.random() * (await Subsidiary.count())),
});
const HumanResource1 = await HumanResources.findOne({
order: [['id', 'ASC']],
offset: 1,
});
if (HumanResource1?.setSubsidiary) {
await HumanResource1.setSubsidiary(relatedSubsidiary1);
}
const relatedSubsidiary2 = await Subsidiary.findOne({
offset: Math.floor(Math.random() * (await Subsidiary.count())),
});
const HumanResource2 = await HumanResources.findOne({
order: [['id', 'ASC']],
offset: 2,
});
if (HumanResource2?.setSubsidiary) {
await HumanResource2.setSubsidiary(relatedSubsidiary2);
}
}
async function associateInventoryWithSubsidiary() {
const relatedSubsidiary0 = await Subsidiary.findOne({
offset: Math.floor(Math.random() * (await Subsidiary.count())),
});
const Inventory0 = await Inventory.findOne({
order: [['id', 'ASC']],
offset: 0,
});
if (Inventory0?.setSubsidiary) {
await Inventory0.setSubsidiary(relatedSubsidiary0);
}
const relatedSubsidiary1 = await Subsidiary.findOne({
offset: Math.floor(Math.random() * (await Subsidiary.count())),
});
const Inventory1 = await Inventory.findOne({
order: [['id', 'ASC']],
offset: 1,
});
if (Inventory1?.setSubsidiary) {
await Inventory1.setSubsidiary(relatedSubsidiary1);
}
const relatedSubsidiary2 = await Subsidiary.findOne({
offset: Math.floor(Math.random() * (await Subsidiary.count())),
});
const Inventory2 = await Inventory.findOne({
order: [['id', 'ASC']],
offset: 2,
});
if (Inventory2?.setSubsidiary) {
await Inventory2.setSubsidiary(relatedSubsidiary2);
}
}
async function associateMachineryWithSubsidiary() {
const relatedSubsidiary0 = await Subsidiary.findOne({
offset: Math.floor(Math.random() * (await Subsidiary.count())),
});
const Machinery0 = await Machinery.findOne({
order: [['id', 'ASC']],
offset: 0,
});
if (Machinery0?.setSubsidiary) {
await Machinery0.setSubsidiary(relatedSubsidiary0);
}
const relatedSubsidiary1 = await Subsidiary.findOne({
offset: Math.floor(Math.random() * (await Subsidiary.count())),
});
const Machinery1 = await Machinery.findOne({
order: [['id', 'ASC']],
offset: 1,
});
if (Machinery1?.setSubsidiary) {
await Machinery1.setSubsidiary(relatedSubsidiary1);
}
const relatedSubsidiary2 = await Subsidiary.findOne({
offset: Math.floor(Math.random() * (await Subsidiary.count())),
});
const Machinery2 = await Machinery.findOne({
order: [['id', 'ASC']],
offset: 2,
});
if (Machinery2?.setSubsidiary) {
await Machinery2.setSubsidiary(relatedSubsidiary2);
}
}
async function associateQualityControlWithWork_order() {
const relatedWork_order0 = await WorkOrders.findOne({
offset: Math.floor(Math.random() * (await WorkOrders.count())),
});
const QualityControl0 = await QualityControl.findOne({
order: [['id', 'ASC']],
offset: 0,
});
if (QualityControl0?.setWork_order) {
await QualityControl0.setWork_order(relatedWork_order0);
}
const relatedWork_order1 = await WorkOrders.findOne({
offset: Math.floor(Math.random() * (await WorkOrders.count())),
});
const QualityControl1 = await QualityControl.findOne({
order: [['id', 'ASC']],
offset: 1,
});
if (QualityControl1?.setWork_order) {
await QualityControl1.setWork_order(relatedWork_order1);
}
const relatedWork_order2 = await WorkOrders.findOne({
offset: Math.floor(Math.random() * (await WorkOrders.count())),
});
const QualityControl2 = await QualityControl.findOne({
order: [['id', 'ASC']],
offset: 2,
});
if (QualityControl2?.setWork_order) {
await QualityControl2.setWork_order(relatedWork_order2);
}
}
async function associateQualityControlWithSubsidiary() {
const relatedSubsidiary0 = await Subsidiary.findOne({
offset: Math.floor(Math.random() * (await Subsidiary.count())),
});
const QualityControl0 = await QualityControl.findOne({
order: [['id', 'ASC']],
offset: 0,
});
if (QualityControl0?.setSubsidiary) {
await QualityControl0.setSubsidiary(relatedSubsidiary0);
}
const relatedSubsidiary1 = await Subsidiary.findOne({
offset: Math.floor(Math.random() * (await Subsidiary.count())),
});
const QualityControl1 = await QualityControl.findOne({
order: [['id', 'ASC']],
offset: 1,
});
if (QualityControl1?.setSubsidiary) {
await QualityControl1.setSubsidiary(relatedSubsidiary1);
}
const relatedSubsidiary2 = await Subsidiary.findOne({
offset: Math.floor(Math.random() * (await Subsidiary.count())),
});
const QualityControl2 = await QualityControl.findOne({
order: [['id', 'ASC']],
offset: 2,
});
if (QualityControl2?.setSubsidiary) {
await QualityControl2.setSubsidiary(relatedSubsidiary2);
}
}
async function associateRawMaterialWithSubsidiary() {
const relatedSubsidiary0 = await Subsidiary.findOne({
offset: Math.floor(Math.random() * (await Subsidiary.count())),
});
const RawMaterial0 = await RawMaterials.findOne({
order: [['id', 'ASC']],
offset: 0,
});
if (RawMaterial0?.setSubsidiary) {
await RawMaterial0.setSubsidiary(relatedSubsidiary0);
}
const relatedSubsidiary1 = await Subsidiary.findOne({
offset: Math.floor(Math.random() * (await Subsidiary.count())),
});
const RawMaterial1 = await RawMaterials.findOne({
order: [['id', 'ASC']],
offset: 1,
});
if (RawMaterial1?.setSubsidiary) {
await RawMaterial1.setSubsidiary(relatedSubsidiary1);
}
const relatedSubsidiary2 = await Subsidiary.findOne({
offset: Math.floor(Math.random() * (await Subsidiary.count())),
});
const RawMaterial2 = await RawMaterials.findOne({
order: [['id', 'ASC']],
offset: 2,
});
if (RawMaterial2?.setSubsidiary) {
await RawMaterial2.setSubsidiary(relatedSubsidiary2);
}
}
async function associateSubsidiaryWithSubsidiary() {
const relatedSubsidiary0 = await Subsidiary.findOne({
offset: Math.floor(Math.random() * (await Subsidiary.count())),
});
const Subsidiary0 = await Subsidiaries.findOne({
order: [['id', 'ASC']],
offset: 0,
});
if (Subsidiary0?.setSubsidiary) {
await Subsidiary0.setSubsidiary(relatedSubsidiary0);
}
const relatedSubsidiary1 = await Subsidiary.findOne({
offset: Math.floor(Math.random() * (await Subsidiary.count())),
});
const Subsidiary1 = await Subsidiaries.findOne({
order: [['id', 'ASC']],
offset: 1,
});
if (Subsidiary1?.setSubsidiary) {
await Subsidiary1.setSubsidiary(relatedSubsidiary1);
}
const relatedSubsidiary2 = await Subsidiary.findOne({
offset: Math.floor(Math.random() * (await Subsidiary.count())),
});
const Subsidiary2 = await Subsidiaries.findOne({
order: [['id', 'ASC']],
offset: 2,
});
if (Subsidiary2?.setSubsidiary) {
await Subsidiary2.setSubsidiary(relatedSubsidiary2);
}
}
// Similar logic for "relation_many"
async function associateSupplierWithSubsidiary() {
const relatedSubsidiary0 = await Subsidiary.findOne({
offset: Math.floor(Math.random() * (await Subsidiary.count())),
});
const Supplier0 = await Suppliers.findOne({
order: [['id', 'ASC']],
offset: 0,
});
if (Supplier0?.setSubsidiary) {
await Supplier0.setSubsidiary(relatedSubsidiary0);
}
const relatedSubsidiary1 = await Subsidiary.findOne({
offset: Math.floor(Math.random() * (await Subsidiary.count())),
});
const Supplier1 = await Suppliers.findOne({
order: [['id', 'ASC']],
offset: 1,
});
if (Supplier1?.setSubsidiary) {
await Supplier1.setSubsidiary(relatedSubsidiary1);
}
const relatedSubsidiary2 = await Subsidiary.findOne({
offset: Math.floor(Math.random() * (await Subsidiary.count())),
});
const Supplier2 = await Suppliers.findOne({
order: [['id', 'ASC']],
offset: 2,
});
if (Supplier2?.setSubsidiary) {
await Supplier2.setSubsidiary(relatedSubsidiary2);
}
}
// Similar logic for "relation_many"
async function associateWorkOrderWithAssigned_to() {
const relatedAssigned_to0 = await Users.findOne({
offset: Math.floor(Math.random() * (await Users.count())),
});
const WorkOrder0 = await WorkOrders.findOne({
order: [['id', 'ASC']],
offset: 0,
});
if (WorkOrder0?.setAssigned_to) {
await WorkOrder0.setAssigned_to(relatedAssigned_to0);
}
const relatedAssigned_to1 = await Users.findOne({
offset: Math.floor(Math.random() * (await Users.count())),
});
const WorkOrder1 = await WorkOrders.findOne({
order: [['id', 'ASC']],
offset: 1,
});
if (WorkOrder1?.setAssigned_to) {
await WorkOrder1.setAssigned_to(relatedAssigned_to1);
}
const relatedAssigned_to2 = await Users.findOne({
offset: Math.floor(Math.random() * (await Users.count())),
});
const WorkOrder2 = await WorkOrders.findOne({
order: [['id', 'ASC']],
offset: 2,
});
if (WorkOrder2?.setAssigned_to) {
await WorkOrder2.setAssigned_to(relatedAssigned_to2);
}
}
async function associateWorkOrderWithSubsidiary() {
const relatedSubsidiary0 = await Subsidiary.findOne({
offset: Math.floor(Math.random() * (await Subsidiary.count())),
});
const WorkOrder0 = await WorkOrders.findOne({
order: [['id', 'ASC']],
offset: 0,
});
if (WorkOrder0?.setSubsidiary) {
await WorkOrder0.setSubsidiary(relatedSubsidiary0);
}
const relatedSubsidiary1 = await Subsidiary.findOne({
offset: Math.floor(Math.random() * (await Subsidiary.count())),
});
const WorkOrder1 = await WorkOrders.findOne({
order: [['id', 'ASC']],
offset: 1,
});
if (WorkOrder1?.setSubsidiary) {
await WorkOrder1.setSubsidiary(relatedSubsidiary1);
}
const relatedSubsidiary2 = await Subsidiary.findOne({
offset: Math.floor(Math.random() * (await Subsidiary.count())),
});
const WorkOrder2 = await WorkOrders.findOne({
order: [['id', 'ASC']],
offset: 2,
});
if (WorkOrder2?.setSubsidiary) {
await WorkOrder2.setSubsidiary(relatedSubsidiary2);
}
}
module.exports = {
up: async (queryInterface, Sequelize) => {
await HumanResources.bulkCreate(HumanResourcesData);
await Inventory.bulkCreate(InventoryData);
await Machinery.bulkCreate(MachineryData);
await QualityControl.bulkCreate(QualityControlData);
await RawMaterials.bulkCreate(RawMaterialsData);
await Subsidiaries.bulkCreate(SubsidiariesData);
await Suppliers.bulkCreate(SuppliersData);
await WorkOrders.bulkCreate(WorkOrdersData);
await Subsidiary.bulkCreate(SubsidiaryData);
await Promise.all([
// Similar logic for "relation_many"
await associateUserWithSubsidiary(),
await associateHumanResourceWithSubsidiary(),
await associateInventoryWithSubsidiary(),
await associateMachineryWithSubsidiary(),
await associateQualityControlWithWork_order(),
await associateQualityControlWithSubsidiary(),
await associateRawMaterialWithSubsidiary(),
await associateSubsidiaryWithSubsidiary(),
// Similar logic for "relation_many"
await associateSupplierWithSubsidiary(),
// Similar logic for "relation_many"
await associateWorkOrderWithAssigned_to(),
await associateWorkOrderWithSubsidiary(),
]);
},
down: async (queryInterface, Sequelize) => {
await queryInterface.bulkDelete('human_resources', null, {});
await queryInterface.bulkDelete('inventory', null, {});
await queryInterface.bulkDelete('machinery', null, {});
await queryInterface.bulkDelete('quality_control', null, {});
await queryInterface.bulkDelete('raw_materials', null, {});
await queryInterface.bulkDelete('subsidiaries', null, {});
await queryInterface.bulkDelete('suppliers', null, {});
await queryInterface.bulkDelete('work_orders', null, {});
await queryInterface.bulkDelete('subsidiary', null, {});
},
};

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

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

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

@ -0,0 +1,213 @@
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 pexelsRoutes = require('./routes/pexels');
const organizationForAuthRoutes = require('./routes/organizationLogin');
const openaiRoutes = require('./routes/openai');
const contactFormRoutes = require('./routes/contactForm');
const usersRoutes = require('./routes/users');
const human_resourcesRoutes = require('./routes/human_resources');
const inventoryRoutes = require('./routes/inventory');
const machineryRoutes = require('./routes/machinery');
const quality_controlRoutes = require('./routes/quality_control');
const raw_materialsRoutes = require('./routes/raw_materials');
const subsidiariesRoutes = require('./routes/subsidiaries');
const suppliersRoutes = require('./routes/suppliers');
const work_ordersRoutes = require('./routes/work_orders');
const rolesRoutes = require('./routes/roles');
const permissionsRoutes = require('./routes/permissions');
const subsidiaryRoutes = require('./routes/subsidiary');
const options = {
definition: {
openapi: '3.0.0',
info: {
version: '1.0.0',
title: 'GMW ERP',
description:
'GMW ERP Online REST API for Testing and Prototyping application. You can perform all major operations with your entities - create, delete and etc.',
},
servers: [
{
url: 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 = 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/human_resources',
passport.authenticate('jwt', { session: false }),
human_resourcesRoutes,
);
app.use(
'/api/inventory',
passport.authenticate('jwt', { session: false }),
inventoryRoutes,
);
app.use(
'/api/machinery',
passport.authenticate('jwt', { session: false }),
machineryRoutes,
);
app.use(
'/api/quality_control',
passport.authenticate('jwt', { session: false }),
quality_controlRoutes,
);
app.use(
'/api/raw_materials',
passport.authenticate('jwt', { session: false }),
raw_materialsRoutes,
);
app.use(
'/api/subsidiaries',
passport.authenticate('jwt', { session: false }),
subsidiariesRoutes,
);
app.use(
'/api/suppliers',
passport.authenticate('jwt', { session: false }),
suppliersRoutes,
);
app.use(
'/api/work_orders',
passport.authenticate('jwt', { session: false }),
work_ordersRoutes,
);
app.use(
'/api/roles',
passport.authenticate('jwt', { session: false }),
rolesRoutes,
);
app.use(
'/api/permissions',
passport.authenticate('jwt', { session: false }),
permissionsRoutes,
);
app.use(
'/api/subsidiary',
passport.authenticate('jwt', { session: false }),
subsidiaryRoutes,
);
app.use(
'/api/openai',
passport.authenticate('jwt', { session: false }),
openaiRoutes,
);
app.use('/api/contact-form', contactFormRoutes);
app.use(
'/api/search',
passport.authenticate('jwt', { session: false }),
searchRoutes,
);
app.use('/api/org-for-auth', organizationForAuthRoutes);
const publicDir = path.join(__dirname, '../public');
if (fs.existsSync(publicDir)) {
app.use('/', express.static(publicDir));
app.get('*', function (request, response) {
response.sendFile(path.resolve(publicDir, 'index.html'));
});
}
const PORT = process.env.NODE_ENV === 'dev_stage' ? 3000 : 8080;
db.sequelize.sync().then(function () {
app.listen(PORT, () => {
console.log(`Listening on port ${PORT}`);
});
});
module.exports = app;

View File

@ -0,0 +1,64 @@
const ValidationError = require('../services/notifications/errors/validation');
/**
* @param {string} permission
* @return {import("express").RequestHandler}
*/
function checkPermissions(permission) {
return (req, res, next) => {
const { currentUser } = req;
if (currentUser) {
if (currentUser.id === req.params.id || currentUser.id === req.body.id) {
next();
return;
}
const userPermission = currentUser.custom_permissions.find(
(cp) => cp.name === permission,
);
if (userPermission) {
next();
} else {
if (!currentUser.app_role) {
return next(new ValidationError('auth.forbidden'));
}
currentUser.app_role
.getPermissions()
.then((permissions) => {
if (permissions.find((p) => p.name === permission)) {
next();
} else {
next(new ValidationError('auth.forbidden'));
}
})
.catch((e) => next(e));
}
} else {
next(new ValidationError('auth.unauthorized'));
}
};
}
const METHOD_MAP = {
POST: 'CREATE',
GET: 'READ',
PUT: 'UPDATE',
PATCH: 'UPDATE',
DELETE: 'DELETE',
};
/**
* @param {string} name
* @return {import("express").RequestHandler}
*/
function checkCrudPermissions(name) {
return (req, res, next) => {
const permissionName = `${METHOD_MAP[req.method]}_${name.toUpperCase()}`;
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;

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

@ -0,0 +1,270 @@
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.body.organizationId,
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,33 @@
const express = require('express');
const router = express.Router();
const EmailSender = require('../services/email');
router.post('/send', async (req, res) => {
try {
const { email, subject, message } = req.body;
if (!email || !subject || !message) {
return res.status(400).json({ error: 'All fields are required' });
}
const emailSender = new EmailSender({
to: 'manuhspice10@gmail.com',
subject: subject,
html: () => `
<p><strong>From:</strong> ${email}</p>
<p><strong>Subject:</strong> ${subject}</p>
<p><strong>Message:</strong></p>
<p>${message}</p>
`,
text: () => `From: ${email}\nSubject: ${subject}\nMessage:\n${message}`,
});
await emailSender.send();
res.status(200).json({ message: 'Email sent successfully' });
} catch (error) {
console.error('Error sending email:', error);
res.status(500).json({ error: 'Error sending email' });
}
});
module.exports = router;

View File

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

View File

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

View File

@ -0,0 +1,180 @@
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 } = require('../services/openai');
const RolesService = require('../services/roles');
const RolesDBApi = require('../db/api/roles');
/**
* @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 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 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 { 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);
}
}),
);
module.exports = router;

View File

@ -0,0 +1,46 @@
const express = require('express');
const SubsidiaryDBApi = require('../db/api/subsidiary');
const wrapAsync = require('../helpers').wrapAsync;
const router = express.Router();
/**
* @swagger
* /api/organizations:
* get:
* security:
* - bearerAuth: []
* tags: [Organizations]
* summary: Get all organizations
* description: Get all organizations
* responses:
* 200:
* description: Organizations list successfully received
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: "#/components/schemas/Organizations"
* 401:
* $ref: "#/components/responses/UnauthorizedError"
* 404:
* description: Data not found
* 500:
* description: Some server error
*/
router.get(
'/',
wrapAsync(async (req, res) => {
const payload = await SubsidiaryDBApi.findAll(req.query);
const simplifiedPayload = payload.rows.map((org) => ({
id: org.id,
name: org.name,
}));
res.status(200).send(simplifiedPayload);
}),
);
module.exports = router;

View File

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

View File

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

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

@ -0,0 +1,444 @@
const express = require('express');
const RolesService = require('../services/roles');
const RolesDBApi = require('../db/api/roles');
const wrapAsync = require('../helpers').wrapAsync;
const config = require('../config');
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 globalAccess = req.currentUser.app_role.globalAccess;
const currentUser = req.currentUser;
const payload = await RolesDBApi.findAll(req.query, globalAccess, {
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 globalAccess = req.currentUser.app_role.globalAccess;
const currentUser = req.currentUser;
const payload = await RolesDBApi.findAll(req.query, globalAccess, {
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 globalAccess = req.currentUser.app_role.globalAccess;
const payload = await RolesDBApi.findAllAutocomplete(
req.query.query,
req.query.limit,
req.query.offset,
globalAccess,
);
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,60 @@
const express = require('express');
const SearchService = require('../services/search');
const config = require('../config');
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, organizationId } = req.body;
const globalAccess = req.currentUser.app_role.globalAccess;
if (!searchQuery) {
return res.status(400).json({ error: 'Please enter a search query' });
}
try {
const foundMatches = await SearchService.search(
searchQuery,
req.currentUser,
organizationId,
globalAccess,
);
res.json(foundMatches);
} catch (error) {
console.error('Internal Server Error', error);
res.status(500).json({ error: 'Internal Server Error' });
}
});
module.exports = router;

View File

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

View File

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

View File

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

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

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

View File

@ -0,0 +1,228 @@
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, organizationId, 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,
organizationId: organizationId,
},
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,52 @@
<!DOCTYPE html>
<html>
<head>
<style>
.email-container {
max-width: 600px;
margin: auto;
background-color: #ffffff;
border: 1px solid #e2e8f0;
border-radius: 4px;
overflow: hidden;
}
.email-header {
background-color: #3498db;
color: #fff;
padding: 16px;
text-align: center;
}
.email-body {
padding: 16px;
}
.email-footer {
padding: 16px;
background-color: #f7fafc;
text-align: center;
color: #4a5568;
font-size: 14px;
}
.link-primary {
color: #3498db;
text-decoration: none;
}
</style>
</head>
<body>
<div class="email-container">
<div class="email-header">Verify your email for {appTitle}!</div>
<div class="email-body">
<p>Hello,</p>
<p>Follow this link to verify your email address.</p>
<p>
If you didn't ask to verify this address, you can ignore this email.
</p>
<p><a href="{signupUrl}" class="link-primary">{signupUrl}</a></p>
</div>
<div class="email-footer">
Thanks,<br />
The {appTitle} Team
</div>
</div>
</body>
</html>

View File

@ -0,0 +1,56 @@
<!DOCTYPE html>
<html>
<head>
<style>
.email-container {
max-width: 600px;
margin: auto;
background-color: #ffffff;
border: 1px solid #e2e8f0;
border-radius: 4px;
overflow: hidden;
}
.email-header {
background-color: #3498db;
color: #fff;
padding: 16px;
text-align: center;
}
.email-body {
padding: 16px;
}
.email-footer {
padding: 16px;
background-color: #f7fafc;
text-align: center;
color: #4a5568;
font-size: 14px;
}
.btn-primary {
background-color: #3498db;
color: #fff !important;
padding: 8px 16px;
border-radius: 4px;
text-decoration: none;
display: inline-block;
}
</style>
</head>
<body>
<div class="email-container">
<div class="email-header">Welcome to {appTitle}!</div>
<div class="email-body">
<p>Hello,</p>
<p>
You've been invited to join {appTitle}. Please click the button below
to set up your account.
</p>
<a href="{signupUrl}" class="btn-primary">Set up account</a>
</div>
<div class="email-footer">
Thanks,<br />
The {appTitle} Team
</div>
</div>
</body>
</html>

View File

@ -0,0 +1,55 @@
<!DOCTYPE html>
<html>
<head>
<style>
.email-container {
max-width: 600px;
margin: auto;
background-color: #ffffff;
border: 1px solid #e2e8f0;
border-radius: 4px;
overflow: hidden;
}
.email-header {
background-color: #3498db;
color: #fff;
padding: 16px;
text-align: center;
}
.email-body {
padding: 16px;
}
.email-footer {
padding: 16px;
background-color: #f7fafc;
text-align: center;
color: #4a5568;
font-size: 14px;
}
.link-primary {
color: #3498db;
text-decoration: none;
}
</style>
</head>
<body>
<div class="email-container">
<div class="email-header">Reset your password for {appTitle}</div>
<div class="email-body">
<p>Hello,</p>
<p>
Follow this link to reset your {appTitle} password for your
{accountName} account.
</p>
<p><a href="{resetUrl}" class="link-primary">{resetUrl}</a></p>
<p>
If you didn't ask to reset your password, you can ignore this email.
</p>
</div>
<div class="email-footer">
Thanks,<br />
The {appTitle} Team
</div>
</div>
</body>
</html>

View File

@ -0,0 +1,41 @@
const config = require('../../config');
const assert = require('assert');
const nodemailer = require('nodemailer');
module.exports = class EmailSender {
constructor(email) {
this.email = email;
}
async send() {
assert(this.email, 'email is required');
assert(this.email.to, 'email.to is required');
assert(this.email.subject, 'email.subject is required');
assert(this.email.html, 'email.html is required');
const htmlContent = await this.email.html();
const transporter = nodemailer.createTransport(this.transportConfig);
const mailOptions = {
from: this.from,
to: this.email.to,
subject: this.email.subject,
html: htmlContent,
};
return transporter.sendMail(mailOptions);
}
static get isConfigured() {
return !!config.email?.auth?.pass && !!config.email?.auth?.user;
}
get transportConfig() {
return config.email;
}
get from() {
return config.email.from;
}
};

View File

@ -0,0 +1,41 @@
const { getNotification } = require('../../notifications/helpers');
const fs = require('fs').promises;
const path = require('path');
module.exports = class EmailAddressVerificationEmail {
constructor(to, link) {
this.to = to;
this.link = link;
}
get subject() {
return getNotification(
'emails.emailAddressVerification.subject',
getNotification('app.title'),
);
}
async html() {
try {
const templatePath = path.join(
__dirname,
'../../email/htmlTemplates/addressVerification/emailAddressVerification.html',
);
const template = await fs.readFile(templatePath, 'utf8');
const appTitle = getNotification('app.title');
const signupUrl = this.link;
let html = template
.replace(/{appTitle}/g, appTitle)
.replace(/{signupUrl}/g, signupUrl)
.replace(/{to}/g, this.to);
return html;
} catch (error) {
console.error('Error generating invitation email HTML:', error);
throw error;
}
}
};

View File

@ -0,0 +1,41 @@
const fs = require('fs').promises;
const path = require('path');
const { getNotification } = require('../../notifications/helpers');
module.exports = class InvitationEmail {
constructor(to, host) {
this.to = to;
this.host = host;
}
get subject() {
return getNotification(
'emails.invitation.subject',
getNotification('app.title'),
);
}
async html() {
try {
const templatePath = path.join(
__dirname,
'../../email/htmlTemplates/invitation/invitationTemplate.html',
);
const template = await fs.readFile(templatePath, 'utf8');
const appTitle = getNotification('app.title');
const signupUrl = `${this.host}&invitation=true`;
let html = template
.replace(/{appTitle}/g, appTitle)
.replace(/{signupUrl}/g, signupUrl)
.replace(/{to}/g, this.to);
return html;
} catch (error) {
console.error('Error generating invitation email HTML:', error);
throw error;
}
}
};

View File

@ -0,0 +1,42 @@
const { getNotification } = require('../../notifications/helpers');
const path = require('path');
const { promises: fs } = require('fs');
module.exports = class PasswordResetEmail {
constructor(to, link) {
this.to = to;
this.link = link;
}
get subject() {
return getNotification(
'emails.passwordReset.subject',
getNotification('app.title'),
);
}
async html() {
try {
const templatePath = path.join(
__dirname,
'../../email/htmlTemplates/passwordReset/passwordResetEmail.html',
);
const template = await fs.readFile(templatePath, 'utf8');
const appTitle = getNotification('app.title');
const resetUrl = this.link;
const accountName = this.to;
let html = template
.replace(/{appTitle}/g, appTitle)
.replace(/{resetUrl}/g, resetUrl)
.replace(/{accountName}/g, accountName);
return html;
} catch (error) {
console.error('Error generating invitation email HTML:', error);
throw error;
}
}
};

View File

@ -0,0 +1,202 @@
const formidable = require('formidable');
const fs = require('fs');
const config = require('../config');
const path = require('path');
const { format } = require('util');
const ensureDirectoryExistence = (filePath) => {
const dirname = path.dirname(filePath);
if (fs.existsSync(dirname)) {
return true;
}
ensureDirectoryExistence(dirname);
fs.mkdirSync(dirname);
};
const uploadLocal = (
folder,
validations = {
entity: null,
maxFileSize: null,
folderIncludesAuthenticationUid: false,
},
) => {
return (req, res) => {
if (!req.currentUser) {
res.sendStatus(403);
return;
}
if (validations.entity) {
res.sendStatus(403);
return;
}
if (validations.folderIncludesAuthenticationUid) {
folder = folder.replace(':userId', req.currentUser.authenticationUid);
if (
!req.currentUser.authenticationUid ||
!folder.includes(req.currentUser.authenticationUid)
) {
res.sendStatus(403);
return;
}
}
const form = new formidable.IncomingForm();
form.uploadDir = config.uploadDir;
if (validations && validations.maxFileSize) {
form.maxFileSize = validations.maxFileSize;
}
form.parse(req, function (err, fields, files) {
const filename = String(fields.filename);
const fileTempUrl = files.file.path;
if (!filename) {
fs.unlinkSync(fileTempUrl);
res.sendStatus(500);
return;
}
const privateUrl = path.join(form.uploadDir, folder, filename);
ensureDirectoryExistence(privateUrl);
fs.renameSync(fileTempUrl, privateUrl);
res.sendStatus(200);
});
form.on('error', function (err) {
res.status(500).send(err);
});
};
};
const downloadLocal = async (req, res) => {
const privateUrl = req.query.privateUrl;
if (!privateUrl) {
return res.sendStatus(404);
}
res.download(path.join(config.uploadDir, privateUrl));
};
const initGCloud = () => {
const processFile = require('../middlewares/upload');
const { Storage } = require('@google-cloud/storage');
const crypto = require('crypto');
const hash = config.gcloud.hash;
const privateKey = process.env.GC_PRIVATE_KEY.replace(/\\\n/g, '\n');
const storage = new Storage({
projectId: process.env.GC_PROJECT_ID,
credentials: {
client_email: process.env.GC_CLIENT_EMAIL,
private_key: privateKey,
},
});
const bucket = storage.bucket(config.gcloud.bucket);
return { hash, bucket, processFile };
};
const uploadGCloud = async (folder, req, res) => {
try {
const { hash, bucket, processFile } = initGCloud();
await processFile(req, res);
let buffer = await req.file.buffer;
let filename = await req.body.filename;
if (!req.file) {
return res.status(400).send({ message: 'Please upload a file!' });
}
let path = `${hash}/${folder}/${filename}`;
let blob = bucket.file(path);
console.log(path);
const blobStream = blob.createWriteStream({
resumable: false,
});
blobStream.on('error', (err) => {
console.log('Upload error');
console.log(err.message);
res.status(500).send({ message: err.message });
});
console.log(`https://storage.googleapis.com/${bucket.name}/${blob.name}`);
blobStream.on('finish', async (data) => {
const publicUrl = format(
`https://storage.googleapis.com/${bucket.name}/${blob.name}`,
);
res.status(200).send({
message: 'Uploaded the file successfully: ' + path,
url: publicUrl,
});
});
blobStream.end(buffer);
} catch (err) {
console.log(err);
res.status(500).send({
message: `Could not upload the file. ${err}`,
});
}
};
const downloadGCloud = async (req, res) => {
try {
const { hash, bucket, processFile } = initGCloud();
const privateUrl = await req.query.privateUrl;
const filePath = `${hash}/${privateUrl}`;
const file = bucket.file(filePath);
const fileExists = await file.exists();
if (fileExists[0]) {
const stream = file.createReadStream();
stream.pipe(res);
} else {
res.status(404).send({
message: 'Could not download the file. ' + err,
});
}
} catch (err) {
res.status(404).send({
message: 'Could not download the file. ' + err,
});
}
};
const deleteGCloud = async (privateUrl) => {
try {
const { hash, bucket, processFile } = initGCloud();
const filePath = `${hash}/${privateUrl}`;
const file = bucket.file(filePath);
const fileExists = await file.exists();
if (fileExists[0]) {
file.delete();
}
} catch (err) {
console.log(`Cannot find the file ${privateUrl}`);
}
};
module.exports = {
initGCloud,
uploadLocal,
downloadLocal,
deleteGCloud,
uploadGCloud,
downloadGCloud,
};

View File

@ -0,0 +1,121 @@
const db = require('../db/models');
const Human_resourcesDBApi = require('../db/api/human_resources');
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 Human_resourcesService {
static async create(data, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await Human_resourcesDBApi.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 Human_resourcesDBApi.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 human_resources = await Human_resourcesDBApi.findBy(
{ id },
{ transaction },
);
if (!human_resources) {
throw new ValidationError('human_resourcesNotFound');
}
const updatedHuman_resources = await Human_resourcesDBApi.update(
id,
data,
{
currentUser,
transaction,
},
);
await transaction.commit();
return updatedHuman_resources;
} catch (error) {
await transaction.rollback();
throw error;
}
}
static async deleteByIds(ids, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await Human_resourcesDBApi.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 Human_resourcesDBApi.remove(id, {
currentUser,
transaction,
});
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
};

View File

@ -0,0 +1,114 @@
const db = require('../db/models');
const InventoryDBApi = require('../db/api/inventory');
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 InventoryService {
static async create(data, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await InventoryDBApi.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 InventoryDBApi.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 inventory = await InventoryDBApi.findBy({ id }, { transaction });
if (!inventory) {
throw new ValidationError('inventoryNotFound');
}
const updatedInventory = await InventoryDBApi.update(id, data, {
currentUser,
transaction,
});
await transaction.commit();
return updatedInventory;
} catch (error) {
await transaction.rollback();
throw error;
}
}
static async deleteByIds(ids, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await InventoryDBApi.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 InventoryDBApi.remove(id, {
currentUser,
transaction,
});
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
};

View File

@ -0,0 +1,114 @@
const db = require('../db/models');
const MachineryDBApi = require('../db/api/machinery');
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 MachineryService {
static async create(data, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await MachineryDBApi.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 MachineryDBApi.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 machinery = await MachineryDBApi.findBy({ id }, { transaction });
if (!machinery) {
throw new ValidationError('machineryNotFound');
}
const updatedMachinery = await MachineryDBApi.update(id, data, {
currentUser,
transaction,
});
await transaction.commit();
return updatedMachinery;
} catch (error) {
await transaction.rollback();
throw error;
}
}
static async deleteByIds(ids, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await MachineryDBApi.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 MachineryDBApi.remove(id, {
currentUser,
transaction,
});
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
};

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,22 @@
const axios = require('axios');
const { v4: uuid } = require('uuid');
const RoleService = require('./roles');
const config = require('../config');
module.exports = class OpenAiService {
static async getWidget(payload, userId, roleId) {
const response = await axios.post(
`${config.flHost}/${config.project_uuid}/project_customization_widgets.json`,
payload,
);
if (response.status >= 200 && response.status < 300) {
const { widget_id } = await response.data;
await RoleService.addRoleInfo(roleId, userId, 'widgets', widget_id);
return widget_id;
} else {
console.error('=======error=======', response.data);
return { value: null, error: response.data };
}
}
};

View File

@ -0,0 +1,114 @@
const db = require('../db/models');
const PermissionsDBApi = require('../db/api/permissions');
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 PermissionsService {
static async create(data, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await PermissionsDBApi.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 PermissionsDBApi.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 permissions = await PermissionsDBApi.findBy({ id }, { transaction });
if (!permissions) {
throw new ValidationError('permissionsNotFound');
}
const updatedPermissions = await PermissionsDBApi.update(id, data, {
currentUser,
transaction,
});
await transaction.commit();
return updatedPermissions;
} catch (error) {
await transaction.rollback();
throw error;
}
}
static async deleteByIds(ids, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await PermissionsDBApi.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 PermissionsDBApi.remove(id, {
currentUser,
transaction,
});
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
};

View File

@ -0,0 +1,121 @@
const db = require('../db/models');
const Quality_controlDBApi = require('../db/api/quality_control');
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 Quality_controlService {
static async create(data, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await Quality_controlDBApi.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 Quality_controlDBApi.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 quality_control = await Quality_controlDBApi.findBy(
{ id },
{ transaction },
);
if (!quality_control) {
throw new ValidationError('quality_controlNotFound');
}
const updatedQuality_control = await Quality_controlDBApi.update(
id,
data,
{
currentUser,
transaction,
},
);
await transaction.commit();
return updatedQuality_control;
} catch (error) {
await transaction.rollback();
throw error;
}
}
static async deleteByIds(ids, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await Quality_controlDBApi.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 Quality_controlDBApi.remove(id, {
currentUser,
transaction,
});
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
};

View File

@ -0,0 +1,117 @@
const db = require('../db/models');
const Raw_materialsDBApi = require('../db/api/raw_materials');
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 Raw_materialsService {
static async create(data, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await Raw_materialsDBApi.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 Raw_materialsDBApi.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 raw_materials = await Raw_materialsDBApi.findBy(
{ id },
{ transaction },
);
if (!raw_materials) {
throw new ValidationError('raw_materialsNotFound');
}
const updatedRaw_materials = await Raw_materialsDBApi.update(id, data, {
currentUser,
transaction,
});
await transaction.commit();
return updatedRaw_materials;
} catch (error) {
await transaction.rollback();
throw error;
}
}
static async deleteByIds(ids, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await Raw_materialsDBApi.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 Raw_materialsDBApi.remove(id, {
currentUser,
transaction,
});
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
};

View File

@ -0,0 +1,391 @@
const db = require('../db/models');
const RolesDBApi = require('../db/api/roles');
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');
function buildWidgetResult(widget, queryResult, queryString) {
if (queryResult[0] && queryResult[0].length) {
const key = Object.keys(queryResult[0][0])[0];
const value =
widget.widget_type === 'scalar' ? queryResult[0][0][key] : queryResult[0];
const widgetData = JSON.parse(widget.data);
return { ...widget, ...widgetData, value, query: queryString };
} else {
return { ...widget, value: [], query: queryString };
}
}
async function executeQuery(queryString, currentUser) {
try {
return await db.sequelize.query(queryString, {
replacements: { organizationId: currentUser.organizationId },
});
} catch (e) {
console.log(e);
return [];
}
}
function insertWhereConditions(queryString, whereConditions) {
if (!whereConditions) return queryString;
const whereIndex = queryString.toLowerCase().indexOf('where');
const groupByIndex = queryString.toLowerCase().indexOf('group by');
const insertIndex =
whereIndex === -1
? groupByIndex !== -1
? groupByIndex
: queryString.length
: whereIndex + 5;
const prefix = queryString.substring(0, insertIndex);
const suffix = queryString.substring(insertIndex);
const conditionString =
whereIndex === -1
? ` WHERE ${whereConditions} `
: ` ${whereConditions} AND `;
return `${prefix}${conditionString}${suffix}`;
}
function constructWhereConditions(mainTable, currentUser, replacements) {
const {
organizationId,
app_role: { globalAccess },
} = currentUser;
const tablesWithoutOrgId = ['permissions', 'roles'];
let whereConditions = '';
if (!globalAccess && !tablesWithoutOrgId.includes(mainTable)) {
whereConditions += `"${mainTable}"."organizationId" = :organizationId`;
replacements.organizationId = organizationId;
}
if (mainTable !== 'users') {
whereConditions += whereConditions ? ' AND ' : '';
whereConditions += `"${mainTable}"."deletedAt" IS NULL`;
}
return whereConditions;
}
function extractTableName(queryString) {
const tableNameRegex = /FROM\s+("?)([^"\s]+)\1\s*/i;
const match = tableNameRegex.exec(queryString);
return match ? match[2] : null;
}
function buildQueryString(widget, currentUser) {
let queryString = widget?.query || '';
const tableName = extractTableName(queryString);
const mainTable = JSON.parse(widget?.data)?.main_table || tableName;
const replacements = {};
const whereConditions = constructWhereConditions(
mainTable,
currentUser,
replacements,
);
queryString = insertWhereConditions(queryString, whereConditions);
console.log(queryString, 'queryString');
return queryString;
}
async function constructWidgetsResults(widgets, currentUser) {
const widgetsResults = [];
for (const widget of widgets) {
if (!widget) continue;
const queryString = buildQueryString(widget, currentUser);
const queryResult = await executeQuery(queryString, currentUser);
widgetsResults.push(buildWidgetResult(widget, queryResult, queryString));
}
return widgetsResults;
}
async function fetchWidgetsData(widgets) {
const widgetPromises = (widgets || []).map((widgetId) =>
axios.get(
`${config.flHost}/${config.project_uuid}/project_customization_widgets/${widgetId}.json`,
),
);
const widgetResults = widgetPromises
? await Promise.allSettled(widgetPromises)
: [];
return widgetResults
.filter((result) => result.status === 'fulfilled')
.map((result) => result.value.data);
}
async function processWidgets(widgets, currentUser) {
const widgetData = await fetchWidgetsData(widgets);
return constructWidgetsResults(widgetData, currentUser);
}
function parseCustomization(role) {
try {
return JSON.parse(role.role_customization || '{}');
} catch (e) {
console.log(e);
return {};
}
}
async function findRole(roleId, currentUser) {
const transaction = await db.sequelize.transaction();
try {
const role = roleId
? await RolesDBApi.findBy({ id: roleId }, { transaction })
: await RolesDBApi.findBy({ name: 'User' }, { transaction });
await transaction.commit();
return role;
} catch (error) {
await transaction.rollback();
throw error;
}
}
module.exports = class RolesService {
static async create(data, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await RolesDBApi.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 RolesDBApi.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 roles = await RolesDBApi.findBy({ id }, { transaction });
if (!roles) {
throw new ValidationError('rolesNotFound');
}
const updatedRoles = await RolesDBApi.update(id, data, {
currentUser,
transaction,
});
await transaction.commit();
return updatedRoles;
} catch (error) {
await transaction.rollback();
throw error;
}
}
static async deleteByIds(ids, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await RolesDBApi.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 RolesDBApi.remove(id, {
currentUser,
transaction,
});
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
static async addRoleInfo(roleId, userId, key, widgetId, currentUser) {
const regexExpForUuid =
/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/gi;
const widgetIdIsUUID = regexExpForUuid.test(widgetId);
const transaction = await db.sequelize.transaction();
let role;
if (roleId) {
role = await RolesDBApi.findBy({ id: roleId }, { transaction });
} else {
role = await RolesDBApi.findBy({ name: 'User' }, { transaction });
}
if (!role) {
throw new ValidationError('rolesNotFound');
}
try {
let customization = {};
try {
customization = JSON.parse(role.role_customization || '{}');
} catch (e) {
console.log(e);
}
if (widgetIdIsUUID && Array.isArray(customization[key])) {
const el = customization[key].find((e) => e === widgetId);
!el ? customization[key].unshift(widgetId) : null;
}
if (widgetIdIsUUID && !customization[key]) {
customization[key] = [widgetId];
}
const newRole = await RolesDBApi.update(
role.id,
{
role_customization: JSON.stringify(customization),
name: role.name,
permissions: role.permissions,
globalAccess: role.globalAccess,
},
{
currentUser,
transaction,
},
);
await transaction.commit();
return newRole;
} catch (error) {
await transaction.rollback();
throw error;
}
}
static async removeRoleInfoById(infoId, roleId, key, currentUser) {
const transaction = await db.sequelize.transaction();
let role;
if (roleId) {
role = await RolesDBApi.findBy({ id: roleId }, { transaction });
} else {
role = await RolesDBApi.findBy({ name: 'User' }, { transaction });
}
if (!role) {
await transaction.rollback();
throw new ValidationError('rolesNotFound');
}
let customization = {};
try {
customization = JSON.parse(role.role_customization || '{}');
} catch (e) {
console.log(e);
}
customization[key] = customization[key].filter((item) => item !== infoId);
const response = await axios.delete(
`${config.flHost}/${config.project_uuid}/project_customization_widgets/${infoId}.json`,
);
const { status } = await response;
try {
const result = await RolesDBApi.update(
role.id,
{
role_customization: JSON.stringify(customization),
name: role.name,
permissions: role.permissions,
globalAccess: role.globalAccess,
},
{
currentUser,
transaction,
},
);
await transaction.commit();
return result;
} catch (error) {
await transaction.rollback();
throw error;
}
}
static async getRoleInfoByKey(key, roleId, currentUser) {
const transaction = await db.sequelize.transaction();
const organizationId = currentUser.organizationId;
let globalAccess = currentUser.app_role?.globalAccess;
let queryString = '';
try {
const role = await findRole(roleId, currentUser);
const customization = parseCustomization(role);
let result;
if (key === 'widgets') {
result = await processWidgets(customization[key], currentUser);
} else {
result = customization[key];
}
await transaction.commit();
return result;
} catch (error) {
console.error(error);
await transaction.rollback();
} finally {
if (transaction.finished !== 'commit') {
await transaction.rollback();
}
}
}
};

View File

@ -0,0 +1,169 @@
const db = require('../db/models');
const ValidationError = require('./notifications/errors/validation');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
/**
* @param {string} permission
* @param {object} currentUser
*/
async function checkPermissions(permission, currentUser) {
if (!currentUser) {
throw new ValidationError('auth.unauthorized');
}
const userPermission = currentUser.custom_permissions.find(
(cp) => cp.name === permission,
);
if (userPermission) {
return true;
}
try {
if (!currentUser.app_role) {
throw new ValidationError('auth.forbidden');
}
const permissions = await currentUser.app_role.getPermissions();
return !!permissions.find((p) => p.name === permission);
} catch (e) {
throw e;
}
}
module.exports = class SearchService {
static async search(searchQuery, currentUser, organizationId, globalAccess) {
try {
if (!searchQuery) {
throw new ValidationError('iam.errors.searchQueryRequired');
}
const tableColumns = {
users: ['firstName', 'lastName', 'phoneNumber', 'email'],
human_resources: ['employee_name', 'shift'],
inventory: ['product_name'],
machinery: ['machine_name'],
quality_control: ['check_name'],
raw_materials: ['material_name'],
subsidiaries: ['name', 'address', 'contact_number'],
suppliers: ['supplier_name', 'contract_terms'],
work_orders: ['order_number'],
subsidiary: ['name'],
};
const columnsInt = {
human_resources: ['payroll'],
inventory: [
'available_quantity',
'reserved_quantity',
'returned_quantity',
],
machinery: ['downtime_hours'],
raw_materials: ['quantity', 'reorder_level'],
};
let allFoundRecords = [];
for (const tableName in tableColumns) {
if (tableColumns.hasOwnProperty(tableName)) {
const attributesToSearch = tableColumns[tableName];
const attributesIntToSearch = columnsInt[tableName] || [];
const whereCondition = {
[Op.or]: [
...attributesToSearch.map((attribute) => ({
[attribute]: {
[Op.iLike]: `%${searchQuery}%`,
},
})),
...attributesIntToSearch.map((attribute) =>
Sequelize.where(
Sequelize.cast(
Sequelize.col(`${tableName}.${attribute}`),
'varchar',
),
{ [Op.iLike]: `%${searchQuery}%` },
),
),
],
};
if (
!globalAccess &&
tableName !== 'organizations' &&
organizationId
) {
whereCondition.organizationId = organizationId;
}
const hasPermission = await checkPermissions(
`READ_${tableName.toUpperCase()}`,
currentUser,
);
if (!hasPermission) {
continue;
}
const foundRecords = await db[tableName].findAll({
where: whereCondition,
attributes: [
...tableColumns[tableName],
'id',
...attributesIntToSearch,
],
});
const modifiedRecords = foundRecords.map((record) => {
const matchAttribute = [];
for (const attribute of attributesToSearch) {
if (
record[attribute]
?.toLowerCase()
?.includes(searchQuery.toLowerCase())
) {
matchAttribute.push(attribute);
}
}
for (const attribute of attributesIntToSearch) {
const castedValue = String(record[attribute]);
if (
castedValue &&
castedValue.toLowerCase().includes(searchQuery.toLowerCase())
) {
matchAttribute.push(attribute);
}
}
return {
...record.get(),
matchAttribute,
tableName,
};
});
allFoundRecords = allFoundRecords.concat(modifiedRecords);
}
}
return allFoundRecords;
} catch (error) {
throw error;
}
}
};

View File

@ -0,0 +1,117 @@
const db = require('../db/models');
const SubsidiariesDBApi = require('../db/api/subsidiaries');
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 SubsidiariesService {
static async create(data, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await SubsidiariesDBApi.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 SubsidiariesDBApi.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 subsidiaries = await SubsidiariesDBApi.findBy(
{ id },
{ transaction },
);
if (!subsidiaries) {
throw new ValidationError('subsidiariesNotFound');
}
const updatedSubsidiaries = await SubsidiariesDBApi.update(id, data, {
currentUser,
transaction,
});
await transaction.commit();
return updatedSubsidiaries;
} catch (error) {
await transaction.rollback();
throw error;
}
}
static async deleteByIds(ids, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await SubsidiariesDBApi.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 SubsidiariesDBApi.remove(id, {
currentUser,
transaction,
});
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
};

View File

@ -0,0 +1,114 @@
const db = require('../db/models');
const SubsidiaryDBApi = require('../db/api/subsidiary');
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 SubsidiaryService {
static async create(data, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await SubsidiaryDBApi.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 SubsidiaryDBApi.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 subsidiary = await SubsidiaryDBApi.findBy({ id }, { transaction });
if (!subsidiary) {
throw new ValidationError('subsidiaryNotFound');
}
const updatedSubsidiary = await SubsidiaryDBApi.update(id, data, {
currentUser,
transaction,
});
await transaction.commit();
return updatedSubsidiary;
} catch (error) {
await transaction.rollback();
throw error;
}
}
static async deleteByIds(ids, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await SubsidiaryDBApi.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 SubsidiaryDBApi.remove(id, {
currentUser,
transaction,
});
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
};

View File

@ -0,0 +1,114 @@
const db = require('../db/models');
const SuppliersDBApi = require('../db/api/suppliers');
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 SuppliersService {
static async create(data, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await SuppliersDBApi.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 SuppliersDBApi.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 suppliers = await SuppliersDBApi.findBy({ id }, { transaction });
if (!suppliers) {
throw new ValidationError('suppliersNotFound');
}
const updatedSuppliers = await SuppliersDBApi.update(id, data, {
currentUser,
transaction,
});
await transaction.commit();
return updatedSuppliers;
} catch (error) {
await transaction.rollback();
throw error;
}
}
static async deleteByIds(ids, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await SuppliersDBApi.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 SuppliersDBApi.remove(id, {
currentUser,
transaction,
});
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
};

View File

@ -0,0 +1,163 @@
const db = require('../db/models');
const UsersDBApi = require('../db/api/users');
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');
const InvitationEmail = require('./email/list/invitation');
const EmailSender = require('./email');
const AuthService = require('./auth');
module.exports = class UsersService {
static async create(data, currentUser, sendInvitationEmails = true, host) {
let transaction = await db.sequelize.transaction();
const globalAccess = currentUser.app_role.globalAccess;
let email = data.email;
let emailsToInvite = [];
try {
if (email) {
let user = await UsersDBApi.findBy({ email }, { transaction });
if (user) {
throw new ValidationError('iam.errors.userAlreadyExists');
} else {
await UsersDBApi.create(
{ data },
globalAccess,
{
currentUser,
transaction,
},
);
emailsToInvite.push(email);
}
} else {
throw new ValidationError('iam.errors.emailRequired');
}
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
if (emailsToInvite && emailsToInvite.length) {
if (!sendInvitationEmails) return;
AuthService.sendPasswordResetEmail(email, 'invitation', host);
}
}
static async bulkImport(req, res, sendInvitationEmails = true, host) {
const transaction = await db.sequelize.transaction();
let emailsToInvite = [];
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', () => {
console.log('results csv', results);
resolve();
})
.on('error', (error) => reject(error));
});
const hasAllEmails = results.every((result) => result.email);
if (!hasAllEmails) {
throw new ValidationError('importer.errors.userEmailMissing');
}
await UsersDBApi.bulkImport(results, {
transaction,
ignoreDuplicates: true,
validate: true,
currentUser: req.currentUser,
});
emailsToInvite = results.map((result) => result.email);
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
if (emailsToInvite && emailsToInvite.length && !sendInvitationEmails) {
emailsToInvite.forEach((email) => {
AuthService.sendPasswordResetEmail(email, 'invitation', host);
});
}
}
static async update(data, id, currentUser) {
const transaction = await db.sequelize.transaction();
const globalAccess = currentUser.app_role.globalAccess;
try {
let users = await UsersDBApi.findBy({ id }, { transaction });
if (!users) {
throw new ValidationError('iam.errors.userNotFound');
}
const updatedUser = await UsersDBApi.update(
id,
data,
globalAccess,
{
currentUser,
transaction,
},
);
await transaction.commit();
return updatedUser;
} catch (error) {
await transaction.rollback();
throw error;
}
}
static async remove(id, currentUser) {
const transaction = await db.sequelize.transaction();
try {
if (currentUser.id === id) {
throw new ValidationError('iam.errors.deletingHimself');
}
if (
currentUser.app_role?.name !== config.roles.admin &&
currentUser.app_role?.name !== config.roles.super_admin
) {
throw new ValidationError('errors.forbidden.message');
}
await UsersDBApi.remove(id, {
currentUser,
transaction,
});
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
};

View File

@ -0,0 +1,114 @@
const db = require('../db/models');
const Work_ordersDBApi = require('../db/api/work_orders');
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 Work_ordersService {
static async create(data, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await Work_ordersDBApi.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 Work_ordersDBApi.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 work_orders = await Work_ordersDBApi.findBy({ id }, { transaction });
if (!work_orders) {
throw new ValidationError('work_ordersNotFound');
}
const updatedWork_orders = await Work_ordersDBApi.update(id, data, {
currentUser,
transaction,
});
await transaction.commit();
return updatedWork_orders;
} catch (error) {
await transaction.rollback();
throw error;
}
}
static async deleteByIds(ids, currentUser) {
const transaction = await db.sequelize.transaction();
try {
await Work_ordersDBApi.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 Work_ordersDBApi.remove(id, {
currentUser,
transaction,
});
await transaction.commit();
} catch (error) {
await transaction.rollback();
throw error;
}
}
};

4470
backend/yarn.lock Normal file

File diff suppressed because it is too large Load Diff

11
frontend/.eslintrc.cjs Normal file
View File

@ -0,0 +1,11 @@
module.exports = {
extends: [
'next/core-web-vitals',
'eslint-config-prettier',
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
],
parser: '@typescript-eslint/parser',
plugins: ['@typescript-eslint'],
root: true,
};

10
frontend/.prettierrc Normal file
View File

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

19
frontend/Dockerfile Normal file
View File

@ -0,0 +1,19 @@
FROM node:20.15.1-alpine
# 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 3000
CMD [ "yarn", "dev" ]

21
frontend/LICENSE-justboil Normal file
View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2019-current JustBoil.me (https://justboil.me)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

91
frontend/README.md Normal file
View File

@ -0,0 +1,91 @@
# GMW ERP
## This project was generated by Flatlogic Platform.
## Install
`cd` to project's dir and run `npm install`
### Builds
Build are handled by Next.js CLI &mdash; [Info](https://nextjs.org/docs/api-reference/cli)
### Hot-reloads for development
```
npm run dev
```
### Builds and minifies for production
```
npm run build
```
### Exports build for static hosts
```
npm run export
```
### Lint
```
npm run lint
```
### Format with prettier
```
npm run format
```
## Support
For any additional information please refer to [Flatlogic homepage](https://flatlogic.com).
## 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`

5
frontend/next-env.d.ts vendored Normal file
View File

@ -0,0 +1,5 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/pages/building-your-application/configuring/typescript for more information.

51
frontend/next.config.mjs Normal file
View File

@ -0,0 +1,51 @@
/**
* @type {import('next').NextConfig}
*/
const output = process.env.NODE_ENV === 'production' ? 'export' : 'standalone';
const nextConfig = {
trailingSlash: true,
distDir: 'build',
output,
basePath: '',
swcMinify: false,
images: {
unoptimized: true,
remotePatterns: [
{
protocol: 'https',
hostname: '**',
},
],
},
async rewrites() {
return [
{
source: '/home',
destination: '/web_pages/home',
},
{
source: '/about',
destination: '/web_pages/about',
},
{
source: '/services',
destination: '/web_pages/services',
},
{
source: '/portfolio_gallery',
destination: '/web_pages/portfolio_gallery',
},
{
source: '/contact',
destination: '/web_pages/contact',
},
];
},
};
export default nextConfig;

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