Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6b8c666c65 | ||
|
|
3fa7195d98 | ||
|
|
74905956ef | ||
|
|
0e02d4ba52 | ||
|
|
7b829087d9 |
0
.perm_test_apache
Normal file
0
.perm_test_apache
Normal file
0
.perm_test_exec
Normal file
0
.perm_test_exec
Normal file
BIN
assets/pasted-20260314-132921-6765892c.webp
Normal file
BIN
assets/pasted-20260314-132921-6765892c.webp
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 12 KiB |
@ -279,7 +279,7 @@ module.exports = class Employee_pay_typesDBApi {
|
||||
}
|
||||
},
|
||||
]
|
||||
} : {},
|
||||
} : undefined,
|
||||
|
||||
},
|
||||
|
||||
@ -296,7 +296,7 @@ module.exports = class Employee_pay_typesDBApi {
|
||||
}
|
||||
},
|
||||
]
|
||||
} : {},
|
||||
} : undefined,
|
||||
|
||||
},
|
||||
|
||||
|
||||
@ -264,7 +264,7 @@ module.exports = class Job_chemical_usagesDBApi {
|
||||
}
|
||||
},
|
||||
]
|
||||
} : {},
|
||||
} : undefined,
|
||||
|
||||
},
|
||||
|
||||
@ -281,7 +281,7 @@ module.exports = class Job_chemical_usagesDBApi {
|
||||
}
|
||||
},
|
||||
]
|
||||
} : {},
|
||||
} : undefined,
|
||||
|
||||
},
|
||||
|
||||
|
||||
@ -90,6 +90,10 @@ module.exports = class Job_logsDBApi {
|
||||
transaction,
|
||||
});
|
||||
|
||||
await job_logs.setWorkersCompClass( data.workersCompClass || null, {
|
||||
transaction,
|
||||
});
|
||||
|
||||
|
||||
|
||||
|
||||
@ -248,6 +252,15 @@ module.exports = class Job_logsDBApi {
|
||||
);
|
||||
}
|
||||
|
||||
if (data.workersCompClass !== undefined) {
|
||||
await job_logs.setWorkersCompClass(
|
||||
|
||||
data.workersCompClass,
|
||||
|
||||
{ transaction }
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@ -356,6 +369,10 @@ module.exports = class Job_logsDBApi {
|
||||
transaction
|
||||
});
|
||||
|
||||
output.workersCompClass = await job_logs.getWorkersCompClass({
|
||||
transaction
|
||||
});
|
||||
|
||||
|
||||
|
||||
return output;
|
||||
@ -395,7 +412,7 @@ module.exports = class Job_logsDBApi {
|
||||
}
|
||||
},
|
||||
]
|
||||
} : {},
|
||||
} : undefined,
|
||||
|
||||
},
|
||||
|
||||
@ -412,7 +429,7 @@ module.exports = class Job_logsDBApi {
|
||||
}
|
||||
},
|
||||
]
|
||||
} : {},
|
||||
} : undefined,
|
||||
|
||||
},
|
||||
|
||||
@ -429,7 +446,7 @@ module.exports = class Job_logsDBApi {
|
||||
}
|
||||
},
|
||||
]
|
||||
} : {},
|
||||
} : undefined,
|
||||
|
||||
},
|
||||
|
||||
@ -446,9 +463,24 @@ module.exports = class Job_logsDBApi {
|
||||
}
|
||||
},
|
||||
]
|
||||
} : {},
|
||||
} : undefined,
|
||||
|
||||
},
|
||||
|
||||
{
|
||||
model: db.workers_comp_classes,
|
||||
as: 'workersCompClass',
|
||||
where: filter.workersCompClass ? {
|
||||
[Op.or]: [
|
||||
{ id: { [Op.in]: filter.workersCompClass.split('|').map(term => Utils.uuid(term)) } },
|
||||
{
|
||||
name: {
|
||||
[Op.or]: filter.workersCompClass.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
|
||||
}
|
||||
},
|
||||
]
|
||||
} : undefined,
|
||||
},
|
||||
|
||||
|
||||
|
||||
|
||||
@ -141,10 +141,10 @@ module.exports = class Pay_typesDBApi {
|
||||
if (data.pay_method !== undefined) updatePayload.pay_method = data.pay_method;
|
||||
|
||||
|
||||
if (data.hourly_rate !== undefined) updatePayload.hourly_rate = data.hourly_rate;
|
||||
if (data.hourly_rate !== undefined) updatePayload.hourly_rate = data.hourly_rate === "" ? null : data.hourly_rate;
|
||||
|
||||
|
||||
if (data.commission_rate !== undefined) updatePayload.commission_rate = data.commission_rate;
|
||||
if (data.commission_rate !== undefined) updatePayload.commission_rate = data.commission_rate === "" ? null : data.commission_rate;
|
||||
|
||||
|
||||
if (data.active !== undefined) updatePayload.active = data.active;
|
||||
|
||||
@ -1,4 +1,3 @@
|
||||
|
||||
const db = require('../models');
|
||||
const FileDBApi = require('./file');
|
||||
const crypto = require('crypto');
|
||||
@ -36,6 +35,11 @@ module.exports = class Payroll_line_itemsDBApi {
|
||||
null
|
||||
,
|
||||
|
||||
workers_comp_amount: data.workers_comp_amount
|
||||
||
|
||||
null
|
||||
,
|
||||
|
||||
total_client_paid: data.total_client_paid
|
||||
||
|
||||
null
|
||||
@ -92,6 +96,11 @@ module.exports = class Payroll_line_itemsDBApi {
|
||||
total_commission_base: item.total_commission_base
|
||||
||
|
||||
null
|
||||
,
|
||||
|
||||
workers_comp_amount: item.workers_comp_amount
|
||||
||
|
||||
null
|
||||
,
|
||||
|
||||
total_client_paid: item.total_client_paid
|
||||
@ -140,6 +149,9 @@ module.exports = class Payroll_line_itemsDBApi {
|
||||
if (data.total_commission_base !== undefined) updatePayload.total_commission_base = data.total_commission_base;
|
||||
|
||||
|
||||
if (data.workers_comp_amount !== undefined) updatePayload.workers_comp_amount = data.workers_comp_amount;
|
||||
|
||||
|
||||
if (data.total_client_paid !== undefined) updatePayload.total_client_paid = data.total_client_paid;
|
||||
|
||||
|
||||
@ -303,7 +315,7 @@ module.exports = class Payroll_line_itemsDBApi {
|
||||
}
|
||||
},
|
||||
]
|
||||
} : {},
|
||||
} : undefined,
|
||||
|
||||
},
|
||||
|
||||
@ -320,7 +332,7 @@ module.exports = class Payroll_line_itemsDBApi {
|
||||
}
|
||||
},
|
||||
]
|
||||
} : {},
|
||||
} : undefined,
|
||||
|
||||
},
|
||||
|
||||
@ -425,6 +437,30 @@ module.exports = class Payroll_line_itemsDBApi {
|
||||
}
|
||||
}
|
||||
|
||||
if (filter.workers_comp_amountRange) {
|
||||
const [start, end] = filter.workers_comp_amountRange;
|
||||
|
||||
if (start !== undefined && start !== null && start !== '') {
|
||||
where = {
|
||||
...where,
|
||||
workers_comp_amount: {
|
||||
...where.workers_comp_amount,
|
||||
[Op.gte]: start,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (end !== undefined && end !== null && end !== '') {
|
||||
where = {
|
||||
...where,
|
||||
workers_comp_amount: {
|
||||
...where.workers_comp_amount,
|
||||
[Op.lte]: end,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (filter.total_client_paidRange) {
|
||||
const [start, end] = filter.total_client_paidRange;
|
||||
|
||||
@ -556,5 +592,4 @@ module.exports = class Payroll_line_itemsDBApi {
|
||||
}
|
||||
|
||||
|
||||
};
|
||||
|
||||
};
|
||||
@ -484,7 +484,7 @@ module.exports = class UsersDBApi {
|
||||
}
|
||||
},
|
||||
]
|
||||
} : {},
|
||||
} : undefined,
|
||||
|
||||
},
|
||||
|
||||
|
||||
188
backend/src/db/api/workers_comp_classes.js
Normal file
188
backend/src/db/api/workers_comp_classes.js
Normal file
@ -0,0 +1,188 @@
|
||||
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 Workers_comp_classesDBApi {
|
||||
static async create(data, options) {
|
||||
const currentUser = (options && options.currentUser) || { id: null };
|
||||
const transaction = (options && options.transaction) || undefined;
|
||||
|
||||
const workers_comp_classes = await db.workers_comp_classes.create(
|
||||
{
|
||||
id: data.id || undefined,
|
||||
name: data.name || null,
|
||||
percentage: data.percentage !== undefined ? data.percentage : null,
|
||||
importHash: data.importHash || null,
|
||||
createdById: currentUser.id,
|
||||
updatedById: currentUser.id,
|
||||
},
|
||||
{ transaction },
|
||||
);
|
||||
|
||||
return workers_comp_classes;
|
||||
}
|
||||
|
||||
static async update(id, data, options) {
|
||||
const currentUser = (options && options.currentUser) || {id: null};
|
||||
const transaction = (options && options.transaction) || undefined;
|
||||
|
||||
const workers_comp_classes = await db.workers_comp_classes.findByPk(id, {}, {transaction});
|
||||
|
||||
const updatePayload = {};
|
||||
|
||||
if (data.name !== undefined) updatePayload.name = data.name;
|
||||
if (data.percentage !== undefined) updatePayload.percentage = data.percentage === "" ? null : data.percentage;
|
||||
|
||||
updatePayload.updatedById = currentUser.id;
|
||||
|
||||
await workers_comp_classes.update(updatePayload, {transaction});
|
||||
|
||||
return workers_comp_classes;
|
||||
}
|
||||
|
||||
static async deleteByIds(ids, options) {
|
||||
const currentUser = (options && options.currentUser) || { id: null };
|
||||
const transaction = (options && options.transaction) || undefined;
|
||||
|
||||
const workers_comp_classes = await db.workers_comp_classes.findAll({
|
||||
where: {
|
||||
id: {
|
||||
[Op.in]: ids,
|
||||
},
|
||||
},
|
||||
transaction,
|
||||
});
|
||||
|
||||
await db.sequelize.transaction(async (transaction) => {
|
||||
for (const record of workers_comp_classes) {
|
||||
await record.update(
|
||||
{deletedBy: currentUser.id},
|
||||
{transaction}
|
||||
);
|
||||
}
|
||||
for (const record of workers_comp_classes) {
|
||||
await record.destroy({transaction});
|
||||
}
|
||||
});
|
||||
|
||||
return workers_comp_classes;
|
||||
}
|
||||
|
||||
static async remove(id, options) {
|
||||
const currentUser = (options && options.currentUser) || {id: null};
|
||||
const transaction = (options && options.transaction) || undefined;
|
||||
|
||||
const workers_comp_classes = await db.workers_comp_classes.findByPk(id, options);
|
||||
|
||||
await workers_comp_classes.update({
|
||||
deletedBy: currentUser.id
|
||||
}, {
|
||||
transaction,
|
||||
});
|
||||
|
||||
await workers_comp_classes.destroy({
|
||||
transaction
|
||||
});
|
||||
|
||||
return workers_comp_classes;
|
||||
}
|
||||
|
||||
static async findBy(where, options) {
|
||||
const transaction = (options && options.transaction) || undefined;
|
||||
|
||||
const workers_comp_classes = await db.workers_comp_classes.findOne(
|
||||
{ where },
|
||||
{ transaction },
|
||||
);
|
||||
|
||||
if (!workers_comp_classes) {
|
||||
return workers_comp_classes;
|
||||
}
|
||||
|
||||
const output = workers_comp_classes.get({plain: true});
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
static async findAll(filter, options) {
|
||||
const limit = filter.limit || 0;
|
||||
let offset = 0;
|
||||
let where = {};
|
||||
const currentPage = +filter.page;
|
||||
|
||||
offset = currentPage * limit;
|
||||
|
||||
const 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('workers_comp_classes', 'name', filter.name),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const queryOptions = {
|
||||
where,
|
||||
include,
|
||||
distinct: true,
|
||||
order: filter && filter.field && filter.sort
|
||||
? [[filter.field, filter.sort]]
|
||||
: [['createdAt', 'desc']],
|
||||
transaction: options && options.transaction,
|
||||
};
|
||||
|
||||
if (!(options && options.countOnly)) {
|
||||
queryOptions.limit = limit ? Number(limit) : undefined;
|
||||
queryOptions.offset = offset ? Number(offset) : undefined;
|
||||
}
|
||||
|
||||
try {
|
||||
const { rows, count } = await db.workers_comp_classes.findAndCountAll(queryOptions);
|
||||
|
||||
return {
|
||||
rows: (options && 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('workers_comp_classes', 'name', query),
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
const records = await db.workers_comp_classes.findAll({
|
||||
attributes: [ 'id', 'name' ],
|
||||
where,
|
||||
limit: limit ? Number(limit) : undefined,
|
||||
offset: offset ? Number(offset) : undefined,
|
||||
order: [['name', 'ASC']],
|
||||
});
|
||||
|
||||
return records.map((record) => ({
|
||||
id: record.id,
|
||||
label: record.name,
|
||||
}));
|
||||
}
|
||||
};
|
||||
32
backend/src/db/migrations/1773330455690.js
Normal file
32
backend/src/db/migrations/1773330455690.js
Normal file
@ -0,0 +1,32 @@
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
await queryInterface.createTable("usersCustom_permissionsPermissions", {
|
||||
id: {
|
||||
type: Sequelize.DataTypes.UUID,
|
||||
defaultValue: Sequelize.DataTypes.UUIDV4,
|
||||
primaryKey: true,
|
||||
},
|
||||
users_custom_permissionsId: {
|
||||
type: Sequelize.DataTypes.UUID,
|
||||
references: {
|
||||
model: "users",
|
||||
key: "id",
|
||||
},
|
||||
onDelete: "CASCADE",
|
||||
},
|
||||
permissionId: {
|
||||
type: Sequelize.DataTypes.UUID,
|
||||
references: {
|
||||
model: "permissions",
|
||||
key: "id",
|
||||
},
|
||||
onDelete: "CASCADE",
|
||||
},
|
||||
createdAt: { type: Sequelize.DataTypes.DATE },
|
||||
updatedAt: { type: Sequelize.DataTypes.DATE },
|
||||
});
|
||||
},
|
||||
async down(queryInterface, Sequelize) {
|
||||
await queryInterface.dropTable("usersCustom_permissionsPermissions");
|
||||
}
|
||||
};
|
||||
12
backend/src/db/migrations/1773330455692.js
Normal file
12
backend/src/db/migrations/1773330455692.js
Normal file
@ -0,0 +1,12 @@
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
await queryInterface.addColumn('pay_types', 'workers_comp_percentage', {
|
||||
type: Sequelize.DataTypes.DECIMAL,
|
||||
allowNull: true,
|
||||
defaultValue: 0,
|
||||
});
|
||||
},
|
||||
async down(queryInterface, Sequelize) {
|
||||
await queryInterface.removeColumn('pay_types', 'workers_comp_percentage');
|
||||
}
|
||||
};
|
||||
12
backend/src/db/migrations/1773330455693.js
Normal file
12
backend/src/db/migrations/1773330455693.js
Normal file
@ -0,0 +1,12 @@
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
await queryInterface.addColumn('payroll_line_items', 'workers_comp_amount', {
|
||||
type: Sequelize.DataTypes.DECIMAL,
|
||||
allowNull: true,
|
||||
defaultValue: 0,
|
||||
});
|
||||
},
|
||||
async down(queryInterface, Sequelize) {
|
||||
await queryInterface.removeColumn('payroll_line_items', 'workers_comp_amount');
|
||||
}
|
||||
};
|
||||
@ -0,0 +1,51 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = {
|
||||
up: async (queryInterface, Sequelize) => {
|
||||
await queryInterface.createTable('workers_comp_classes', {
|
||||
id: {
|
||||
type: Sequelize.UUID,
|
||||
defaultValue: Sequelize.UUIDV4,
|
||||
primaryKey: true,
|
||||
},
|
||||
name: {
|
||||
type: Sequelize.TEXT,
|
||||
},
|
||||
percentage: {
|
||||
type: Sequelize.DECIMAL,
|
||||
},
|
||||
importHash: {
|
||||
type: Sequelize.STRING(255),
|
||||
allowNull: true,
|
||||
unique: true,
|
||||
},
|
||||
createdAt: {
|
||||
type: Sequelize.DATE,
|
||||
},
|
||||
updatedAt: {
|
||||
type: Sequelize.DATE,
|
||||
},
|
||||
deletedAt: {
|
||||
type: Sequelize.DATE,
|
||||
},
|
||||
createdById: {
|
||||
type: Sequelize.UUID,
|
||||
references: {
|
||||
model: 'users',
|
||||
key: 'id',
|
||||
},
|
||||
},
|
||||
updatedById: {
|
||||
type: Sequelize.UUID,
|
||||
references: {
|
||||
model: 'users',
|
||||
key: 'id',
|
||||
},
|
||||
},
|
||||
});
|
||||
},
|
||||
|
||||
down: async (queryInterface, Sequelize) => {
|
||||
await queryInterface.dropTable('workers_comp_classes');
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,24 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = {
|
||||
up: async (queryInterface, Sequelize) => {
|
||||
await queryInterface.addColumn('job_logs', 'workersCompClassId', {
|
||||
type: Sequelize.UUID,
|
||||
references: {
|
||||
model: 'workers_comp_classes',
|
||||
key: 'id',
|
||||
},
|
||||
});
|
||||
// Remove the old enum column
|
||||
// The enum type might cause issues if we try to drop it directly without dropping dependent views,
|
||||
// but just dropping the column is usually fine.
|
||||
await queryInterface.removeColumn('job_logs', 'workers_comp_class');
|
||||
},
|
||||
|
||||
down: async (queryInterface, Sequelize) => {
|
||||
await queryInterface.removeColumn('job_logs', 'workersCompClassId');
|
||||
await queryInterface.addColumn('job_logs', 'workers_comp_class', {
|
||||
type: Sequelize.ENUM('roof', 'ladder', 'ground'),
|
||||
});
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,62 @@
|
||||
'use strict';
|
||||
const { v4: uuid } = require('uuid');
|
||||
|
||||
module.exports = {
|
||||
up: async (queryInterface, Sequelize) => {
|
||||
const createdAt = new Date();
|
||||
const updatedAt = new Date();
|
||||
const entity = 'workers_comp_classes';
|
||||
|
||||
const permissions = [
|
||||
{ id: uuid(), name: `CREATE_${entity.toUpperCase()}`, createdAt, updatedAt },
|
||||
{ id: uuid(), name: `READ_${entity.toUpperCase()}`, createdAt, updatedAt },
|
||||
{ id: uuid(), name: `UPDATE_${entity.toUpperCase()}`, createdAt, updatedAt },
|
||||
{ id: uuid(), name: `DELETE_${entity.toUpperCase()}`, createdAt, updatedAt },
|
||||
];
|
||||
|
||||
await queryInterface.bulkInsert('permissions', permissions);
|
||||
|
||||
// Get Admin and SystemOwner roles
|
||||
const roles = await queryInterface.sequelize.query(
|
||||
`SELECT id, name FROM roles WHERE name IN ('Administrator', 'SystemOwner');`,
|
||||
{ type: Sequelize.QueryTypes.SELECT }
|
||||
);
|
||||
|
||||
const rolePermissions = [];
|
||||
for (const role of roles) {
|
||||
for (const perm of permissions) {
|
||||
rolePermissions.push({
|
||||
roles_permissionsId: role.id,
|
||||
permissionId: perm.id,
|
||||
createdAt,
|
||||
updatedAt,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (rolePermissions.length > 0) {
|
||||
await queryInterface.bulkInsert('rolesPermissionsPermissions', rolePermissions);
|
||||
}
|
||||
},
|
||||
|
||||
down: async (queryInterface, Sequelize) => {
|
||||
const entity = 'workers_comp_classes';
|
||||
const permissionNames = [
|
||||
`CREATE_${entity.toUpperCase()}`,
|
||||
`READ_${entity.toUpperCase()}`,
|
||||
`UPDATE_${entity.toUpperCase()}`,
|
||||
`DELETE_${entity.toUpperCase()}`,
|
||||
];
|
||||
|
||||
await queryInterface.sequelize.query(
|
||||
`DELETE FROM "rolesPermissionsPermissions" WHERE "permissionId" IN (SELECT id FROM permissions WHERE name IN (:names));`,
|
||||
{ replacements: { names: permissionNames } }
|
||||
);
|
||||
|
||||
await queryInterface.bulkDelete('permissions', {
|
||||
name: {
|
||||
[Sequelize.Op.in]: permissionNames,
|
||||
},
|
||||
});
|
||||
},
|
||||
};
|
||||
@ -0,0 +1,39 @@
|
||||
'use strict';
|
||||
module.exports = {
|
||||
up: async (queryInterface, Sequelize) => {
|
||||
const createdAt = new Date();
|
||||
const updatedAt = new Date();
|
||||
// Find all roles
|
||||
const roles = await queryInterface.sequelize.query(
|
||||
`SELECT id, name FROM roles WHERE name != 'Public';`,
|
||||
{ type: Sequelize.QueryTypes.SELECT }
|
||||
);
|
||||
// Find the read permission
|
||||
const permissions = await queryInterface.sequelize.query(
|
||||
`SELECT id, name FROM permissions WHERE name = 'READ_WORKERS_COMP_CLASSES';`,
|
||||
{ type: Sequelize.QueryTypes.SELECT }
|
||||
);
|
||||
if (permissions.length === 0) return;
|
||||
const readPerm = permissions[0];
|
||||
const rolePermissions = [];
|
||||
const existing = await queryInterface.sequelize.query(
|
||||
`SELECT "roles_permissionsId", "permissionId" FROM "rolesPermissionsPermissions" WHERE "permissionId" = '${readPerm.id}';`,
|
||||
{ type: Sequelize.QueryTypes.SELECT }
|
||||
);
|
||||
const existingSet = new Set(existing.map(e => e.roles_permissionsId + '-' + e.permissionId));
|
||||
for (const role of roles) {
|
||||
if (!existingSet.has(role.id + '-' + readPerm.id)) {
|
||||
rolePermissions.push({
|
||||
roles_permissionsId: role.id,
|
||||
permissionId: readPerm.id,
|
||||
createdAt,
|
||||
updatedAt,
|
||||
});
|
||||
}
|
||||
}
|
||||
if (rolePermissions.length > 0) {
|
||||
await queryInterface.bulkInsert('rolesPermissionsPermissions', rolePermissions);
|
||||
}
|
||||
},
|
||||
down: async (queryInterface, Sequelize) => {}
|
||||
};
|
||||
@ -0,0 +1,42 @@
|
||||
'use strict';
|
||||
module.exports = {
|
||||
up: async (queryInterface, Sequelize) => {
|
||||
const createdAt = new Date();
|
||||
const updatedAt = new Date();
|
||||
|
||||
const roles = await queryInterface.sequelize.query(
|
||||
`SELECT id, name FROM roles WHERE name != 'Public';`,
|
||||
{ type: Sequelize.QueryTypes.SELECT }
|
||||
);
|
||||
|
||||
const permissions = await queryInterface.sequelize.query(
|
||||
`SELECT id, name FROM permissions WHERE name = 'READ_EMPLOYEE_PAY_TYPES';`,
|
||||
{ type: Sequelize.QueryTypes.SELECT }
|
||||
);
|
||||
|
||||
if (permissions.length === 0) return;
|
||||
const readPerm = permissions[0];
|
||||
const rolePermissions = [];
|
||||
|
||||
const existing = await queryInterface.sequelize.query(
|
||||
`SELECT "roles_permissionsId", "permissionId" FROM "rolesPermissionsPermissions" WHERE "permissionId" = '${readPerm.id}';`,
|
||||
{ type: Sequelize.QueryTypes.SELECT }
|
||||
);
|
||||
const existingSet = new Set(existing.map(e => e.roles_permissionsId + '-' + e.permissionId));
|
||||
|
||||
for (const role of roles) {
|
||||
if (!existingSet.has(role.id + '-' + readPerm.id)) {
|
||||
rolePermissions.push({
|
||||
roles_permissionsId: role.id,
|
||||
permissionId: readPerm.id,
|
||||
createdAt,
|
||||
updatedAt,
|
||||
});
|
||||
}
|
||||
}
|
||||
if (rolePermissions.length > 0) {
|
||||
await queryInterface.bulkInsert('rolesPermissionsPermissions', rolePermissions);
|
||||
}
|
||||
},
|
||||
down: async (queryInterface, Sequelize) => {}
|
||||
};
|
||||
@ -35,25 +35,6 @@ client_paid: {
|
||||
|
||||
},
|
||||
|
||||
workers_comp_class: {
|
||||
type: DataTypes.ENUM,
|
||||
|
||||
|
||||
|
||||
values: [
|
||||
|
||||
"roof",
|
||||
|
||||
|
||||
"ladder",
|
||||
|
||||
|
||||
"ground"
|
||||
|
||||
],
|
||||
|
||||
},
|
||||
|
||||
odometer_start: {
|
||||
type: DataTypes.INTEGER,
|
||||
|
||||
@ -180,6 +161,14 @@ notes_to_admin: {
|
||||
constraints: false,
|
||||
});
|
||||
|
||||
db.job_logs.belongsTo(db.workers_comp_classes, {
|
||||
as: 'workersCompClass',
|
||||
foreignKey: {
|
||||
name: 'workersCompClassId',
|
||||
},
|
||||
constraints: false,
|
||||
});
|
||||
|
||||
|
||||
|
||||
|
||||
@ -195,6 +184,4 @@ notes_to_admin: {
|
||||
|
||||
|
||||
return job_logs;
|
||||
};
|
||||
|
||||
|
||||
};
|
||||
@ -49,6 +49,13 @@ commission_rate: {
|
||||
|
||||
|
||||
|
||||
},
|
||||
|
||||
workers_comp_percentage: {
|
||||
type: DataTypes.DECIMAL,
|
||||
|
||||
|
||||
|
||||
},
|
||||
|
||||
active: {
|
||||
@ -135,6 +142,4 @@ description: {
|
||||
|
||||
|
||||
return pay_types;
|
||||
};
|
||||
|
||||
|
||||
};
|
||||
@ -33,6 +33,13 @@ total_commission_base: {
|
||||
|
||||
|
||||
|
||||
},
|
||||
|
||||
workers_comp_amount: {
|
||||
type: DataTypes.DECIMAL,
|
||||
|
||||
|
||||
|
||||
},
|
||||
|
||||
total_client_paid: {
|
||||
@ -116,6 +123,4 @@ summary: {
|
||||
|
||||
|
||||
return payroll_line_items;
|
||||
};
|
||||
|
||||
|
||||
};
|
||||
54
backend/src/db/models/workers_comp_classes.js
Normal file
54
backend/src/db/models/workers_comp_classes.js
Normal file
@ -0,0 +1,54 @@
|
||||
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 workers_comp_classes = sequelize.define(
|
||||
'workers_comp_classes',
|
||||
{
|
||||
id: {
|
||||
type: DataTypes.UUID,
|
||||
defaultValue: DataTypes.UUIDV4,
|
||||
primaryKey: true,
|
||||
},
|
||||
name: {
|
||||
type: DataTypes.TEXT,
|
||||
},
|
||||
percentage: {
|
||||
type: DataTypes.DECIMAL,
|
||||
},
|
||||
importHash: {
|
||||
type: DataTypes.STRING(255),
|
||||
allowNull: true,
|
||||
unique: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
timestamps: true,
|
||||
paranoid: true,
|
||||
freezeTableName: true,
|
||||
},
|
||||
);
|
||||
|
||||
workers_comp_classes.associate = (db) => {
|
||||
db.workers_comp_classes.hasMany(db.job_logs, {
|
||||
as: 'job_logs_workers_comp_class',
|
||||
foreignKey: {
|
||||
name: 'workersCompClassId',
|
||||
},
|
||||
constraints: false,
|
||||
});
|
||||
|
||||
db.workers_comp_classes.belongsTo(db.users, {
|
||||
as: 'createdBy',
|
||||
});
|
||||
|
||||
db.workers_comp_classes.belongsTo(db.users, {
|
||||
as: 'updatedBy',
|
||||
});
|
||||
};
|
||||
|
||||
return workers_comp_classes;
|
||||
};
|
||||
@ -32,6 +32,8 @@ const customersRoutes = require('./routes/customers');
|
||||
const vehiclesRoutes = require('./routes/vehicles');
|
||||
|
||||
const pay_typesRoutes = require('./routes/pay_types');
|
||||
const workers_comp_classesRoutes = require('./routes/workers_comp_classes');
|
||||
const workers_comp_reportRoutes = require('./routes/workers_comp_report');
|
||||
|
||||
const employee_pay_typesRoutes = require('./routes/employee_pay_types');
|
||||
|
||||
@ -44,6 +46,7 @@ const job_chemical_usagesRoutes = require('./routes/job_chemical_usages');
|
||||
const payroll_runsRoutes = require('./routes/payroll_runs');
|
||||
|
||||
const payroll_line_itemsRoutes = require('./routes/payroll_line_items');
|
||||
const reportsRoutes = require("./routes/reports");
|
||||
|
||||
|
||||
const getBaseUrl = (url) => {
|
||||
@ -114,6 +117,8 @@ app.use('/api/customers', passport.authenticate('jwt', {session: false}), custom
|
||||
app.use('/api/vehicles', passport.authenticate('jwt', {session: false}), vehiclesRoutes);
|
||||
|
||||
app.use('/api/pay_types', passport.authenticate('jwt', {session: false}), pay_typesRoutes);
|
||||
app.use('/api/workers_comp_classes', passport.authenticate('jwt', {session: false}), workers_comp_classesRoutes);
|
||||
app.use('/api/workers_comp_report', passport.authenticate('jwt', {session: false}), workers_comp_reportRoutes);
|
||||
|
||||
app.use('/api/employee_pay_types', passport.authenticate('jwt', {session: false}), employee_pay_typesRoutes);
|
||||
|
||||
@ -126,6 +131,8 @@ app.use('/api/job_chemical_usages', passport.authenticate('jwt', {session: false
|
||||
app.use('/api/payroll_runs', passport.authenticate('jwt', {session: false}), payroll_runsRoutes);
|
||||
|
||||
app.use('/api/payroll_line_items', passport.authenticate('jwt', {session: false}), payroll_line_itemsRoutes);
|
||||
app.use('/api/reports', passport.authenticate('jwt', {session: false}), reportsRoutes);
|
||||
app.use('/api/payroll_generator', require('./routes/payroll_generator'));
|
||||
|
||||
app.use(
|
||||
'/api/openai',
|
||||
@ -166,7 +173,7 @@ if (fs.existsSync(publicDir)) {
|
||||
const PORT = process.env.NODE_ENV === 'dev_stage' ? 3000 : 8080;
|
||||
|
||||
app.listen(PORT, () => {
|
||||
console.log(`Listening on port ${PORT}`);
|
||||
console.log(`Listening on port ${PORT}`); console.log('Watcher triggered');
|
||||
});
|
||||
|
||||
module.exports = app;
|
||||
|
||||
199
backend/src/routes/payroll_generator.js
Normal file
199
backend/src/routes/payroll_generator.js
Normal file
@ -0,0 +1,199 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const passport = require('passport');
|
||||
const db = require('../db/models');
|
||||
const { wrapAsync } = require('../helpers');
|
||||
const { Op } = require('sequelize');
|
||||
|
||||
router.post('/preview', passport.authenticate('jwt', { session: false }), wrapAsync(async (req, res) => {
|
||||
const { startDate, endDate } = req.body;
|
||||
|
||||
if (!startDate || !endDate) {
|
||||
return res.status(400).send('startDate and endDate are required');
|
||||
}
|
||||
|
||||
// Find job logs in range that are not paid
|
||||
const jobLogs = await db.job_logs.findAll({
|
||||
where: {
|
||||
work_date: {
|
||||
[Op.between]: [new Date(startDate), new Date(endDate)]
|
||||
},
|
||||
status: {
|
||||
[Op.ne]: 'paid'
|
||||
}
|
||||
},
|
||||
include: [
|
||||
{ model: db.users, as: 'employee' },
|
||||
{ model: db.pay_types, as: 'pay_type' }
|
||||
]
|
||||
});
|
||||
|
||||
const employeeTotals = {};
|
||||
|
||||
jobLogs.forEach(log => {
|
||||
const empId = log.employeeId;
|
||||
if (!empId) return;
|
||||
|
||||
if (!employeeTotals[empId]) {
|
||||
employeeTotals[empId] = {
|
||||
employee: log.employee,
|
||||
total_hours: 0,
|
||||
total_commission_base: 0,
|
||||
gross_pay: 0,
|
||||
job_log_ids: []
|
||||
};
|
||||
}
|
||||
|
||||
const totals = employeeTotals[empId];
|
||||
totals.job_log_ids.push(log.id);
|
||||
|
||||
const hours = parseFloat(log.hours_conducted || 0);
|
||||
totals.total_hours += hours;
|
||||
|
||||
const clientPaid = parseFloat(log.client_paid || 0);
|
||||
totals.total_commission_base += clientPaid;
|
||||
|
||||
let pay = 0;
|
||||
if (log.pay_type) {
|
||||
if (log.pay_type.pay_method === 'hourly') {
|
||||
pay = hours * parseFloat(log.pay_type.hourly_rate || 0);
|
||||
} else if (log.pay_type.pay_method === 'commission') {
|
||||
pay = clientPaid * (parseFloat(log.pay_type.commission_rate || 0) / 100);
|
||||
}
|
||||
}
|
||||
totals.gross_pay += pay;
|
||||
});
|
||||
|
||||
const summary = {
|
||||
totalGrossPay: 0,
|
||||
totalHours: 0
|
||||
};
|
||||
|
||||
const lineItems = Object.values(employeeTotals).map(item => {
|
||||
summary.totalGrossPay += item.gross_pay;
|
||||
summary.totalHours += item.total_hours;
|
||||
return item;
|
||||
});
|
||||
|
||||
res.json({ lineItems, summary });
|
||||
}));
|
||||
|
||||
router.post('/generate', passport.authenticate('jwt', { session: false }), wrapAsync(async (req, res) => {
|
||||
const { startDate, endDate, name, notes } = req.body;
|
||||
|
||||
if (!startDate || !endDate) {
|
||||
return res.status(400).send('startDate and endDate are required');
|
||||
}
|
||||
|
||||
// Find job logs
|
||||
const jobLogs = await db.job_logs.findAll({
|
||||
where: {
|
||||
work_date: {
|
||||
[Op.between]: [new Date(startDate), new Date(endDate)]
|
||||
},
|
||||
status: {
|
||||
[Op.ne]: 'paid'
|
||||
}
|
||||
},
|
||||
include: [
|
||||
{ model: db.users, as: 'employee' },
|
||||
{ model: db.pay_types, as: 'pay_type' }
|
||||
]
|
||||
});
|
||||
|
||||
if (jobLogs.length === 0) {
|
||||
return res.status(400).send('No unpaid job logs found in this date range.');
|
||||
}
|
||||
|
||||
const employeeTotals = {};
|
||||
|
||||
jobLogs.forEach(log => {
|
||||
const empId = log.employeeId;
|
||||
if (!empId) return;
|
||||
|
||||
if (!employeeTotals[empId]) {
|
||||
employeeTotals[empId] = {
|
||||
total_hours: 0,
|
||||
total_commission_base: 0,
|
||||
gross_pay: 0,
|
||||
workers_comp_amount: 0,
|
||||
employeeId: empId,
|
||||
job_log_ids: []
|
||||
};
|
||||
}
|
||||
|
||||
const totals = employeeTotals[empId];
|
||||
totals.job_log_ids.push(log.id);
|
||||
|
||||
const hours = parseFloat(log.hours_conducted || 0);
|
||||
totals.total_hours += hours;
|
||||
|
||||
const clientPaid = parseFloat(log.client_paid || 0);
|
||||
totals.total_commission_base += clientPaid;
|
||||
|
||||
let pay = 0;
|
||||
let wcAmount = 0;
|
||||
if (log.pay_type) {
|
||||
if (log.pay_type.pay_method === 'hourly') {
|
||||
pay = hours * parseFloat(log.pay_type.hourly_rate || 0);
|
||||
} else if (log.pay_type.pay_method === 'commission') {
|
||||
pay = clientPaid * (parseFloat(log.pay_type.commission_rate || 0) / 100);
|
||||
}
|
||||
if (log.pay_type.workers_comp_percentage) {
|
||||
wcAmount = pay * (parseFloat(log.pay_type.workers_comp_percentage) / 100);
|
||||
}
|
||||
}
|
||||
totals.gross_pay += pay;
|
||||
totals.workers_comp_amount += wcAmount;
|
||||
});
|
||||
|
||||
// Create a transaction
|
||||
const transaction = await db.sequelize.transaction();
|
||||
try {
|
||||
// Create payroll run
|
||||
const payrollRun = await db.payroll_runs.create({
|
||||
name: name || `Payroll ${startDate} to ${endDate}`,
|
||||
period_start: startDate,
|
||||
period_end: endDate,
|
||||
run_date: new Date(),
|
||||
status: 'finalized',
|
||||
notes: notes || '',
|
||||
createdById: req.currentUser.id
|
||||
}, { transaction });
|
||||
|
||||
// Create line items
|
||||
for (const empId of Object.keys(employeeTotals)) {
|
||||
const totals = employeeTotals[empId];
|
||||
await db.payroll_line_items.create({
|
||||
payroll_runId: payrollRun.id,
|
||||
employeeId: totals.employeeId,
|
||||
total_hours: totals.total_hours,
|
||||
gross_pay: totals.gross_pay,
|
||||
total_commission_base: totals.total_commission_base,
|
||||
workers_comp_amount: totals.workers_comp_amount,
|
||||
createdById: req.currentUser.id
|
||||
}, { transaction });
|
||||
|
||||
// Mark job logs as paid
|
||||
await db.job_logs.update({
|
||||
status: 'paid'
|
||||
}, {
|
||||
where: {
|
||||
id: {
|
||||
[Op.in]: totals.job_log_ids
|
||||
}
|
||||
},
|
||||
transaction
|
||||
});
|
||||
}
|
||||
|
||||
await transaction.commit();
|
||||
res.json({ success: true, payrollRunId: payrollRun.id });
|
||||
} catch (error) {
|
||||
await transaction.rollback();
|
||||
console.error(error);
|
||||
res.status(500).send('Error generating payroll');
|
||||
}
|
||||
}));
|
||||
|
||||
module.exports = router;
|
||||
36
backend/src/routes/reports.js
Normal file
36
backend/src/routes/reports.js
Normal file
@ -0,0 +1,36 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const passport = require('passport');
|
||||
const db = require('../db/models');
|
||||
const { wrapAsync } = require('../helpers');
|
||||
const { Op } = require('sequelize');
|
||||
|
||||
router.post('/', passport.authenticate('jwt', { session: false }), wrapAsync(async (req, res) => {
|
||||
const { startDate, endDate, employeeId } = req.body;
|
||||
|
||||
const where = {};
|
||||
if (startDate || endDate) {
|
||||
where.createdAt = {};
|
||||
if (startDate) where.createdAt[Op.gte] = new Date(startDate);
|
||||
if (endDate) where.createdAt[Op.lte] = new Date(endDate);
|
||||
}
|
||||
if (employeeId) {
|
||||
where.employeeId = employeeId;
|
||||
}
|
||||
|
||||
const lineItems = await db.payroll_line_items.findAll({
|
||||
where,
|
||||
include: [{ model: db.users, as: 'employee' }]
|
||||
});
|
||||
|
||||
const summary = lineItems.reduce((acc, item) => {
|
||||
acc.totalGrossPay += parseFloat(item.gross_pay || 0);
|
||||
acc.totalHours += parseFloat(item.total_hours || 0);
|
||||
acc.totalWorkersComp += parseFloat(item.workers_comp_amount || 0);
|
||||
return acc;
|
||||
}, { totalGrossPay: 0, totalHours: 0, totalWorkersComp: 0 });
|
||||
|
||||
res.json({ lineItems, summary });
|
||||
}));
|
||||
|
||||
module.exports = router;
|
||||
439
backend/src/routes/workers_comp_classes.js
Normal file
439
backend/src/routes/workers_comp_classes.js
Normal file
@ -0,0 +1,439 @@
|
||||
|
||||
const express = require('express');
|
||||
|
||||
const Workers_comp_classesService = require('../services/workers_comp_classes');
|
||||
const Workers_comp_classesDBApi = require('../db/api/workers_comp_classes');
|
||||
const wrapAsync = require('../helpers').wrapAsync;
|
||||
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
const { parse } = require('json2csv');
|
||||
|
||||
|
||||
const {
|
||||
checkCrudPermissions,
|
||||
} = require('../middlewares/check-permissions');
|
||||
|
||||
router.use(checkCrudPermissions('workers_comp_classes'));
|
||||
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* components:
|
||||
* schemas:
|
||||
* Workers_comp_classes:
|
||||
* type: object
|
||||
* properties:
|
||||
|
||||
* name:
|
||||
* type: string
|
||||
* default: name
|
||||
* description:
|
||||
* type: string
|
||||
* default: description
|
||||
|
||||
|
||||
* hourly_rate:
|
||||
* type: integer
|
||||
* format: int64
|
||||
* commission_rate:
|
||||
* type: integer
|
||||
* format: int64
|
||||
|
||||
*
|
||||
*/
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* tags:
|
||||
* name: Workers_comp_classes
|
||||
* description: The Workers_comp_classes managing API
|
||||
*/
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /api/workers_comp_classes:
|
||||
* post:
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* tags: [Workers_comp_classes]
|
||||
* 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/Workers_comp_classes"
|
||||
* responses:
|
||||
* 200:
|
||||
* description: The item was successfully added
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: "#/components/schemas/Workers_comp_classes"
|
||||
* 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 Workers_comp_classesService.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: [Workers_comp_classes]
|
||||
* 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/Workers_comp_classes"
|
||||
* responses:
|
||||
* 200:
|
||||
* description: The items were successfully imported
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: "#/components/schemas/Workers_comp_classes"
|
||||
* 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 Workers_comp_classesService.bulkImport(req, res, true, link.host);
|
||||
const payload = true;
|
||||
res.status(200).send(payload);
|
||||
}));
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /api/workers_comp_classes/{id}:
|
||||
* put:
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* tags: [Workers_comp_classes]
|
||||
* 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/Workers_comp_classes"
|
||||
* required:
|
||||
* - id
|
||||
* responses:
|
||||
* 200:
|
||||
* description: The item data was successfully updated
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: "#/components/schemas/Workers_comp_classes"
|
||||
* 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 Workers_comp_classesService.update(req.body.data, req.body.id, req.currentUser);
|
||||
const payload = true;
|
||||
res.status(200).send(payload);
|
||||
}));
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /api/workers_comp_classes/{id}:
|
||||
* delete:
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* tags: [Workers_comp_classes]
|
||||
* 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/Workers_comp_classes"
|
||||
* 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 Workers_comp_classesService.remove(req.params.id, req.currentUser);
|
||||
const payload = true;
|
||||
res.status(200).send(payload);
|
||||
}));
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /api/workers_comp_classes/deleteByIds:
|
||||
* post:
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* tags: [Workers_comp_classes]
|
||||
* 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/Workers_comp_classes"
|
||||
* 401:
|
||||
* $ref: "#/components/responses/UnauthorizedError"
|
||||
* 404:
|
||||
* description: Items not found
|
||||
* 500:
|
||||
* description: Some server error
|
||||
*/
|
||||
router.post('/deleteByIds', wrapAsync(async (req, res) => {
|
||||
await Workers_comp_classesService.deleteByIds(req.body.data, req.currentUser);
|
||||
const payload = true;
|
||||
res.status(200).send(payload);
|
||||
}));
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /api/workers_comp_classes:
|
||||
* get:
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* tags: [Workers_comp_classes]
|
||||
* summary: Get all workers_comp_classes
|
||||
* description: Get all workers_comp_classes
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Workers_comp_classes list successfully received
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: array
|
||||
* items:
|
||||
* $ref: "#/components/schemas/Workers_comp_classes"
|
||||
* 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 Workers_comp_classesDBApi.findAll(
|
||||
req.query, { currentUser }
|
||||
);
|
||||
if (filetype && filetype === 'csv') {
|
||||
const fields = ['id','name','description',
|
||||
|
||||
'hourly_rate','commission_rate',
|
||||
|
||||
];
|
||||
const opts = { fields };
|
||||
try {
|
||||
const csv = parse(payload.rows, opts);
|
||||
res.status(200).attachment(csv);
|
||||
res.send(csv)
|
||||
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
}
|
||||
} else {
|
||||
res.status(200).send(payload);
|
||||
}
|
||||
|
||||
}));
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /api/workers_comp_classes/count:
|
||||
* get:
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* tags: [Workers_comp_classes]
|
||||
* summary: Count all workers_comp_classes
|
||||
* description: Count all workers_comp_classes
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Workers_comp_classes count successfully received
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: array
|
||||
* items:
|
||||
* $ref: "#/components/schemas/Workers_comp_classes"
|
||||
* 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 Workers_comp_classesDBApi.findAll(
|
||||
req.query,
|
||||
null,
|
||||
{ countOnly: true, currentUser }
|
||||
);
|
||||
|
||||
res.status(200).send(payload);
|
||||
}));
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /api/workers_comp_classes/autocomplete:
|
||||
* get:
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* tags: [Workers_comp_classes]
|
||||
* summary: Find all workers_comp_classes that match search criteria
|
||||
* description: Find all workers_comp_classes that match search criteria
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Workers_comp_classes list successfully received
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: array
|
||||
* items:
|
||||
* $ref: "#/components/schemas/Workers_comp_classes"
|
||||
* 401:
|
||||
* $ref: "#/components/responses/UnauthorizedError"
|
||||
* 404:
|
||||
* description: Data not found
|
||||
* 500:
|
||||
* description: Some server error
|
||||
*/
|
||||
router.get('/autocomplete', async (req, res) => {
|
||||
|
||||
const payload = await Workers_comp_classesDBApi.findAllAutocomplete(
|
||||
req.query.query,
|
||||
req.query.limit,
|
||||
req.query.offset,
|
||||
|
||||
);
|
||||
|
||||
res.status(200).send(payload);
|
||||
});
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /api/workers_comp_classes/{id}:
|
||||
* get:
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* tags: [Workers_comp_classes]
|
||||
* 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/Workers_comp_classes"
|
||||
* 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 Workers_comp_classesDBApi.findBy(
|
||||
{ id: req.params.id },
|
||||
);
|
||||
|
||||
|
||||
|
||||
res.status(200).send(payload);
|
||||
}));
|
||||
|
||||
router.use('/', require('../helpers').commonErrorHandler);
|
||||
|
||||
module.exports = router;
|
||||
54
backend/src/routes/workers_comp_report.js
Normal file
54
backend/src/routes/workers_comp_report.js
Normal file
@ -0,0 +1,54 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const passport = require('passport');
|
||||
const db = require('../db/models');
|
||||
const { wrapAsync } = require('../helpers');
|
||||
const { Op } = require('sequelize');
|
||||
|
||||
router.get('/report', passport.authenticate('jwt', { session: false }), wrapAsync(async (req, res) => {
|
||||
const { startDate, endDate, classId } = req.query;
|
||||
|
||||
const where = {};
|
||||
if (startDate || endDate) {
|
||||
where.work_date = {};
|
||||
if (startDate) where.work_date[Op.gte] = new Date(startDate);
|
||||
if (endDate) where.work_date[Op.lte] = new Date(endDate);
|
||||
}
|
||||
if (classId) {
|
||||
where.workersCompClassId = classId;
|
||||
}
|
||||
|
||||
const jobLogs = await db.job_logs.findAll({
|
||||
where,
|
||||
include: [
|
||||
{ model: db.workers_comp_classes, as: 'workersCompClass' },
|
||||
{ model: db.pay_types, as: 'pay_type' },
|
||||
{ model: db.users, as: 'employee' }
|
||||
]
|
||||
});
|
||||
|
||||
const totalsByClass = {};
|
||||
let totalComp = 0;
|
||||
|
||||
jobLogs.forEach(log => {
|
||||
if (!log.workersCompClass || !log.pay_type) return;
|
||||
|
||||
let employeePay = 0;
|
||||
if (log.pay_type.pay_method === 'hourly') {
|
||||
employeePay = Number(log.hours_conducted || 0) * Number(log.pay_type.hourly_rate || 0);
|
||||
} else if (log.pay_type.pay_method === 'commission') {
|
||||
employeePay = Number(log.client_paid || 0) * (Number(log.pay_type.commission_rate || 0) / 100);
|
||||
}
|
||||
|
||||
const compAmount = employeePay * (Number(log.workersCompClass.percentage || 0) / 100);
|
||||
const className = log.workersCompClass.name;
|
||||
|
||||
if (!totalsByClass[className]) totalsByClass[className] = 0;
|
||||
totalsByClass[className] += compAmount;
|
||||
totalComp += compAmount;
|
||||
});
|
||||
|
||||
res.json({ totalsByClass, totalComp });
|
||||
}));
|
||||
|
||||
module.exports = router;
|
||||
@ -1,5 +1,6 @@
|
||||
const db = require('../db/models');
|
||||
const Job_logsDBApi = require('../db/api/job_logs');
|
||||
const CustomersDBApi = require('../db/api/customers');
|
||||
const processFile = require("../middlewares/upload");
|
||||
const ValidationError = require('./notifications/errors/validation');
|
||||
const csv = require('csv-parser');
|
||||
@ -7,22 +8,44 @@ const axios = require('axios');
|
||||
const config = require('../config');
|
||||
const stream = require('stream');
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
module.exports = class Job_logsService {
|
||||
static async create(data, currentUser) {
|
||||
const transaction = await db.sequelize.transaction();
|
||||
try {
|
||||
await Job_logsDBApi.create(
|
||||
data,
|
||||
let customerId = data.customer;
|
||||
|
||||
// If customer is a string and not a UUID, try to find or create
|
||||
if (typeof customerId === 'string' && customerId.length > 0 && !customerId.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/)) {
|
||||
let customer = await db.customers.findOne({ where: { name: customerId }, transaction });
|
||||
if (!customer) {
|
||||
customer = await CustomersDBApi.create({ name: customerId }, { currentUser, transaction });
|
||||
}
|
||||
customerId = customer.id;
|
||||
}
|
||||
|
||||
const createdJob = await Job_logsDBApi.create(
|
||||
{ ...data, customer: customerId },
|
||||
{
|
||||
currentUser,
|
||||
transaction,
|
||||
},
|
||||
);
|
||||
|
||||
if (data.chemical_usages && Array.isArray(data.chemical_usages)) {
|
||||
for (const usage of data.chemical_usages) {
|
||||
if (usage.chemical_product && usage.quantity_used) {
|
||||
await db.job_chemical_usages.create({
|
||||
job_logId: createdJob.id,
|
||||
chemical_productId: usage.chemical_product,
|
||||
quantity_used: usage.quantity_used,
|
||||
notes: usage.notes || '',
|
||||
createdById: currentUser.id,
|
||||
updatedById: currentUser.id
|
||||
}, { transaction });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await transaction.commit();
|
||||
} catch (error) {
|
||||
await transaction.rollback();
|
||||
@ -78,10 +101,21 @@ module.exports = class Job_logsService {
|
||||
'job_logsNotFound',
|
||||
);
|
||||
}
|
||||
|
||||
let customerId = data.customer;
|
||||
|
||||
// If customer is a string and not a UUID, try to find or create
|
||||
if (typeof customerId === 'string' && customerId.length > 0 && !customerId.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/)) {
|
||||
let customer = await db.customers.findOne({ where: { name: customerId }, transaction });
|
||||
if (!customer) {
|
||||
customer = await CustomersDBApi.create({ name: customerId }, { currentUser, transaction });
|
||||
}
|
||||
customerId = customer.id;
|
||||
}
|
||||
|
||||
const updatedJob_logs = await Job_logsDBApi.update(
|
||||
id,
|
||||
data,
|
||||
{ ...data, customer: customerId },
|
||||
{
|
||||
currentUser,
|
||||
transaction,
|
||||
@ -131,8 +165,4 @@ module.exports = class Job_logsService {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
};
|
||||
|
||||
|
||||
};
|
||||
@ -15,6 +15,15 @@ module.exports = class Payroll_line_itemsService {
|
||||
static async create(data, currentUser) {
|
||||
const transaction = await db.sequelize.transaction();
|
||||
try {
|
||||
if (data.job_logId && data.gross_pay) {
|
||||
const jobLog = await db.job_logs.findByPk(data.job_logId, { transaction });
|
||||
if (jobLog && jobLog.workersCompClassId) {
|
||||
const compClass = await db.workers_comp_classes.findByPk(jobLog.workersCompClassId, { transaction });
|
||||
if (compClass && compClass.percentage) {
|
||||
data.workers_comp_amount = (Number(data.gross_pay || 0) * Number(compClass.percentage || 0)) / 100;
|
||||
}
|
||||
}
|
||||
}
|
||||
await Payroll_line_itemsDBApi.create(
|
||||
data,
|
||||
{
|
||||
|
||||
138
backend/src/services/workers_comp_classes.js
Normal file
138
backend/src/services/workers_comp_classes.js
Normal file
@ -0,0 +1,138 @@
|
||||
const db = require('../db/models');
|
||||
const Workers_comp_classesDBApi = require('../db/api/workers_comp_classes');
|
||||
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 Workers_comp_classesService {
|
||||
static async create(data, currentUser) {
|
||||
const transaction = await db.sequelize.transaction();
|
||||
try {
|
||||
await Workers_comp_classesDBApi.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 Workers_comp_classesDBApi.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 workers_comp_classes = await Workers_comp_classesDBApi.findBy(
|
||||
{id},
|
||||
{transaction},
|
||||
);
|
||||
|
||||
if (!workers_comp_classes) {
|
||||
throw new ValidationError(
|
||||
'workers_comp_classesNotFound',
|
||||
);
|
||||
}
|
||||
|
||||
const updatedWorkers_comp_classes = await Workers_comp_classesDBApi.update(
|
||||
id,
|
||||
data,
|
||||
{
|
||||
currentUser,
|
||||
transaction,
|
||||
},
|
||||
);
|
||||
|
||||
await transaction.commit();
|
||||
return updatedWorkers_comp_classes;
|
||||
|
||||
} catch (error) {
|
||||
await transaction.rollback();
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
static async deleteByIds(ids, currentUser) {
|
||||
const transaction = await db.sequelize.transaction();
|
||||
|
||||
try {
|
||||
await Workers_comp_classesDBApi.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 Workers_comp_classesDBApi.remove(
|
||||
id,
|
||||
{
|
||||
currentUser,
|
||||
transaction,
|
||||
},
|
||||
);
|
||||
|
||||
await transaction.commit();
|
||||
} catch (error) {
|
||||
await transaction.rollback();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
};
|
||||
|
||||
|
||||
1
fix.sql
Normal file
1
fix.sql
Normal file
@ -0,0 +1 @@
|
||||
ALTER TABLE "usersCustom_permissionsPermissions" ADD COLUMN "permissionId" UUID REFERENCES "permissions"(id);
|
||||
BIN
frontend/public/assets/logo.webp
Normal file
BIN
frontend/public/assets/logo.webp
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 12 KiB |
BIN
frontend/public/assets/vm-shot-2026-03-14T13-28-33-023Z.jpg
Normal file
BIN
frontend/public/assets/vm-shot-2026-03-14T13-28-33-023Z.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 196 KiB |
@ -39,7 +39,7 @@ export default function AsideMenuLayer({ menu, className = '', ...props }: Props
|
||||
>
|
||||
<div className="text-center flex-1 lg:text-left lg:pl-6 xl:text-center xl:pl-0">
|
||||
|
||||
<b className="font-black">Pressure Wash Payroll</b>
|
||||
<div className="flex items-center justify-center lg:justify-start gap-2"><img src="/assets/logo.webp" alt="Logo" className="h-8" /><b className="font-black text-xs">Major League Pressure Washing</b></div>
|
||||
|
||||
|
||||
</div>
|
||||
|
||||
@ -15,8 +15,8 @@ export default function FooterBar({ children }: Props) {
|
||||
<div className="text-center md:text-left mb-6 md:mb-0">
|
||||
<b>
|
||||
©{year},{` `}
|
||||
<a href="https://flatlogic.com/" rel="noreferrer" target="_blank">
|
||||
Flatlogic
|
||||
<a href="#" rel="noreferrer" target="_blank">
|
||||
Major League Pressure Washing
|
||||
</a>
|
||||
.
|
||||
</b>
|
||||
@ -25,7 +25,7 @@ export default function FooterBar({ children }: Props) {
|
||||
</div>
|
||||
|
||||
<div className="flex item-center md:py-2 gap-4">
|
||||
<a href="https://flatlogic.com/" rel="noreferrer" target="_blank">
|
||||
<a href="#" rel="noreferrer" target="_blank">
|
||||
<Logo className="w-auto h-8 md:h-6 mx-auto" />
|
||||
</a>
|
||||
</div>
|
||||
|
||||
@ -141,7 +141,7 @@ const CardJob_logs = ({
|
||||
<dt className=' text-gray-500 dark:text-dark-600'>WorkmansCompensationClass</dt>
|
||||
<dd className='flex items-start gap-x-2'>
|
||||
<div className='font-medium line-clamp-4'>
|
||||
{ item.workers_comp_class }
|
||||
{ item.workersCompClass?.name }
|
||||
</div>
|
||||
</dd>
|
||||
</div>
|
||||
|
||||
@ -89,7 +89,7 @@ const ListJob_logs = ({ job_logs, loading, onDelete, currentPage, numPages, onPa
|
||||
|
||||
<div className={'flex-1 px-3'}>
|
||||
<p className={'text-xs text-gray-500 '}>WorkmansCompensationClass</p>
|
||||
<p className={'line-clamp-2'}>{ item.workers_comp_class }</p>
|
||||
<p className={'line-clamp-2'}>{ item.workersCompClass?.name }</p>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
@ -136,7 +136,7 @@ export const loadColumns = async (
|
||||
},
|
||||
|
||||
{
|
||||
field: 'workers_comp_class',
|
||||
field: 'workersCompClass', valueGetter: (params) => params.row?.workersCompClass?.name,
|
||||
headerName: 'WorkmansCompensationClass',
|
||||
flex: 1,
|
||||
minWidth: 120,
|
||||
|
||||
@ -7,9 +7,9 @@ type Props = {
|
||||
export default function Logo({ className = '' }: Props) {
|
||||
return (
|
||||
<img
|
||||
src={"https://flatlogic.com/logo.svg"}
|
||||
src={"/assets/logo.webp"}
|
||||
className={className}
|
||||
alt={'Flatlogic logo'}>
|
||||
alt={'Major League Pressure Washing logo'}>
|
||||
</img>
|
||||
)
|
||||
}
|
||||
|
||||
@ -1,6 +1,5 @@
|
||||
import React, {useEffect, useRef} from 'react'
|
||||
import React, {useEffect, useRef, useState } from 'react'
|
||||
import Link from 'next/link'
|
||||
import { useState } from 'react'
|
||||
import { mdiChevronUp, mdiChevronDown } from '@mdi/js'
|
||||
import BaseDivider from './BaseDivider'
|
||||
import BaseIcon from './BaseIcon'
|
||||
|
||||
@ -0,0 +1,171 @@
|
||||
import React from 'react';
|
||||
import ImageField from '../ImageField';
|
||||
import ListActionsPopover from '../ListActionsPopover';
|
||||
import { useAppSelector } from '../../stores/hooks';
|
||||
import dataFormatter from '../../helpers/dataFormatter';
|
||||
import { Pagination } from '../Pagination';
|
||||
import {saveFile} from "../../helpers/fileSaver";
|
||||
import LoadingSpinner from "../LoadingSpinner";
|
||||
import Link from 'next/link';
|
||||
|
||||
import {hasPermission} from "../../helpers/userPermissions";
|
||||
|
||||
|
||||
type Props = {
|
||||
workers_comp_classes: any[];
|
||||
loading: boolean;
|
||||
onDelete: (id: string) => void;
|
||||
currentPage: number;
|
||||
numPages: number;
|
||||
onPageChange: (page: number) => void;
|
||||
};
|
||||
|
||||
const CardWorkers_comp_classes = ({
|
||||
workers_comp_classes,
|
||||
loading,
|
||||
onDelete,
|
||||
currentPage,
|
||||
numPages,
|
||||
onPageChange,
|
||||
}: Props) => {
|
||||
const asideScrollbarsStyle = useAppSelector(
|
||||
(state) => state.style.asideScrollbarsStyle,
|
||||
);
|
||||
const bgColor = useAppSelector((state) => state.style.cardsColor);
|
||||
const darkMode = useAppSelector((state) => state.style.darkMode);
|
||||
const corners = useAppSelector((state) => state.style.corners);
|
||||
const focusRing = useAppSelector((state) => state.style.focusRingColor);
|
||||
|
||||
const currentUser = useAppSelector((state) => state.auth.currentUser);
|
||||
const hasUpdatePermission = hasPermission(currentUser, 'UPDATE_PAY_TYPES')
|
||||
|
||||
|
||||
return (
|
||||
<div className={'p-4'}>
|
||||
{loading && <LoadingSpinner />}
|
||||
<ul
|
||||
role='list'
|
||||
className='grid grid-cols-1 gap-x-6 gap-y-8 lg:grid-cols-3 2xl:grid-cols-4 xl:gap-x-8'
|
||||
>
|
||||
{!loading && workers_comp_classes.map((item, index) => (
|
||||
<li
|
||||
key={item.id}
|
||||
className={`overflow-hidden ${corners !== 'rounded-full'? corners : 'rounded-3xl'} border ${focusRing} border-gray-200 dark:border-dark-700 ${
|
||||
darkMode ? 'aside-scrollbars-[slate]' : asideScrollbarsStyle
|
||||
}`}
|
||||
>
|
||||
|
||||
<div className={`flex items-center ${bgColor} p-6 gap-x-4 border-b border-gray-900/5 bg-gray-50 dark:bg-dark-800 relative`}>
|
||||
|
||||
<Link href={`/workers_comp_classes/workers_comp_classes-view/?id=${item.id}`} className='text-lg font-bold leading-6 line-clamp-1'>
|
||||
{item.name}
|
||||
</Link>
|
||||
|
||||
|
||||
<div className='ml-auto '>
|
||||
<ListActionsPopover
|
||||
onDelete={onDelete}
|
||||
itemId={item.id}
|
||||
pathEdit={`/workers_comp_classes/workers_comp_classes-edit/?id=${item.id}`}
|
||||
pathView={`/workers_comp_classes/workers_comp_classes-view/?id=${item.id}`}
|
||||
|
||||
hasUpdatePermission={hasUpdatePermission}
|
||||
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<dl className='divide-y divide-stone-300 dark:divide-dark-700 px-6 py-4 text-sm leading-6 h-64 overflow-y-auto'>
|
||||
|
||||
|
||||
<div className='flex justify-between gap-x-4 py-3'>
|
||||
<dt className=' text-gray-500 dark:text-dark-600'>WorkersCompClassName</dt>
|
||||
<dd className='flex items-start gap-x-2'>
|
||||
<div className='font-medium line-clamp-4'>
|
||||
{ item.name }
|
||||
</div>
|
||||
</dd>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
|
||||
<div className='flex justify-between gap-x-4 py-3'>
|
||||
<dt className=' text-gray-500 dark:text-dark-600'>PayMethod</dt>
|
||||
<dd className='flex items-start gap-x-2'>
|
||||
<div className='font-medium line-clamp-4'>
|
||||
{ item.pay_method }
|
||||
</div>
|
||||
</dd>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
|
||||
<div className='flex justify-between gap-x-4 py-3'>
|
||||
<dt className=' text-gray-500 dark:text-dark-600'>HourlyRate</dt>
|
||||
<dd className='flex items-start gap-x-2'>
|
||||
<div className='font-medium line-clamp-4'>
|
||||
{ item.hourly_rate }
|
||||
</div>
|
||||
</dd>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
|
||||
<div className='flex justify-between gap-x-4 py-3'>
|
||||
<dt className=' text-gray-500 dark:text-dark-600'>CommissionRate</dt>
|
||||
<dd className='flex items-start gap-x-2'>
|
||||
<div className='font-medium line-clamp-4'>
|
||||
{ item.commission_rate }
|
||||
</div>
|
||||
</dd>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
|
||||
<div className='flex justify-between gap-x-4 py-3'>
|
||||
<dt className=' text-gray-500 dark:text-dark-600'>Active</dt>
|
||||
<dd className='flex items-start gap-x-2'>
|
||||
<div className='font-medium line-clamp-4'>
|
||||
{ dataFormatter.booleanFormatter(item.active) }
|
||||
</div>
|
||||
</dd>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
|
||||
<div className='flex justify-between gap-x-4 py-3'>
|
||||
<dt className=' text-gray-500 dark:text-dark-600'>Description</dt>
|
||||
<dd className='flex items-start gap-x-2'>
|
||||
<div className='font-medium line-clamp-4'>
|
||||
{ item.description }
|
||||
</div>
|
||||
</dd>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</dl>
|
||||
</li>
|
||||
))}
|
||||
{!loading && workers_comp_classes.length === 0 && (
|
||||
<div className='col-span-full flex items-center justify-center h-40'>
|
||||
<p className=''>No data to display</p>
|
||||
</div>
|
||||
)}
|
||||
</ul>
|
||||
<div className={'flex items-center justify-center my-6'}>
|
||||
<Pagination
|
||||
currentPage={currentPage}
|
||||
numPages={numPages}
|
||||
setCurrentPage={onPageChange}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default CardWorkers_comp_classes;
|
||||
@ -0,0 +1,128 @@
|
||||
import React from 'react';
|
||||
import CardBox from '../CardBox';
|
||||
import ImageField from '../ImageField';
|
||||
import dataFormatter from '../../helpers/dataFormatter';
|
||||
import {saveFile} from "../../helpers/fileSaver";
|
||||
import ListActionsPopover from "../ListActionsPopover";
|
||||
import {useAppSelector} from "../../stores/hooks";
|
||||
import {Pagination} from "../Pagination";
|
||||
import LoadingSpinner from "../LoadingSpinner";
|
||||
import Link from 'next/link';
|
||||
|
||||
import {hasPermission} from "../../helpers/userPermissions";
|
||||
|
||||
|
||||
type Props = {
|
||||
workers_comp_classes: any[];
|
||||
loading: boolean;
|
||||
onDelete: (id: string) => void;
|
||||
currentPage: number;
|
||||
numPages: number;
|
||||
onPageChange: (page: number) => void;
|
||||
};
|
||||
|
||||
const ListWorkers_comp_classes = ({ workers_comp_classes, loading, onDelete, currentPage, numPages, onPageChange }: Props) => {
|
||||
|
||||
const currentUser = useAppSelector((state) => state.auth.currentUser);
|
||||
const hasUpdatePermission = hasPermission(currentUser, 'UPDATE_PAY_TYPES')
|
||||
|
||||
const corners = useAppSelector((state) => state.style.corners);
|
||||
const bgColor = useAppSelector((state) => state.style.cardsColor);
|
||||
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className='relative overflow-x-auto p-4 space-y-4'>
|
||||
{loading && <LoadingSpinner />}
|
||||
{!loading && workers_comp_classes.map((item) => (
|
||||
<div key={item.id}>
|
||||
<CardBox hasTable isList className={'rounded shadow-none'}>
|
||||
<div className={`flex rounded dark:bg-dark-900 border border-stone-300 items-center overflow-hidden`}>
|
||||
|
||||
<Link
|
||||
href={`/workers_comp_classes/workers_comp_classes-view/?id=${item.id}`}
|
||||
className={
|
||||
'flex-1 px-4 py-6 h-24 flex divide-x-2 divide-stone-300 items-center overflow-hidden`}> dark:divide-dark-700 overflow-x-auto'
|
||||
}
|
||||
>
|
||||
|
||||
|
||||
<div className={'flex-1 px-3'}>
|
||||
<p className={'text-xs text-gray-500 '}>WorkersCompClassName</p>
|
||||
<p className={'line-clamp-2'}>{ item.name }</p>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
|
||||
<div className={'flex-1 px-3'}>
|
||||
<p className={'text-xs text-gray-500 '}>PayMethod</p>
|
||||
<p className={'line-clamp-2'}>{ item.pay_method }</p>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
|
||||
<div className={'flex-1 px-3'}>
|
||||
<p className={'text-xs text-gray-500 '}>HourlyRate</p>
|
||||
<p className={'line-clamp-2'}>{ item.hourly_rate }</p>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
|
||||
<div className={'flex-1 px-3'}>
|
||||
<p className={'text-xs text-gray-500 '}>CommissionRate</p>
|
||||
<p className={'line-clamp-2'}>{ item.commission_rate }</p>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
|
||||
<div className={'flex-1 px-3'}>
|
||||
<p className={'text-xs text-gray-500 '}>Active</p>
|
||||
<p className={'line-clamp-2'}>{ dataFormatter.booleanFormatter(item.active) }</p>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
|
||||
<div className={'flex-1 px-3'}>
|
||||
<p className={'text-xs text-gray-500 '}>Description</p>
|
||||
<p className={'line-clamp-2'}>{ item.description }</p>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
</Link>
|
||||
<ListActionsPopover
|
||||
onDelete={onDelete}
|
||||
itemId={item.id}
|
||||
pathEdit={`/workers_comp_classes/workers_comp_classes-edit/?id=${item.id}`}
|
||||
pathView={`/workers_comp_classes/workers_comp_classes-view/?id=${item.id}`}
|
||||
|
||||
hasUpdatePermission={hasUpdatePermission}
|
||||
|
||||
/>
|
||||
</div>
|
||||
</CardBox>
|
||||
</div>
|
||||
))}
|
||||
{!loading && workers_comp_classes.length === 0 && (
|
||||
<div className='col-span-full flex items-center justify-center h-40'>
|
||||
<p className=''>No data to display</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className={'flex items-center justify-center my-6'}>
|
||||
<Pagination
|
||||
currentPage={currentPage}
|
||||
numPages={numPages}
|
||||
setCurrentPage={onPageChange}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
};
|
||||
|
||||
export default ListWorkers_comp_classes
|
||||
@ -0,0 +1,463 @@
|
||||
import React, { useEffect, useState, useMemo } from 'react'
|
||||
import { createPortal } from 'react-dom';
|
||||
import { ToastContainer, toast } from 'react-toastify';
|
||||
import BaseButton from '../BaseButton'
|
||||
import CardBoxModal from '../CardBoxModal'
|
||||
import CardBox from "../CardBox";
|
||||
import { fetch, update, deleteItem, setRefetch, deleteItemsByIds } from '../../stores/workers_comp_classes/workers_comp_classesSlice'
|
||||
import { useAppDispatch, useAppSelector } from '../../stores/hooks'
|
||||
import { useRouter } from 'next/router'
|
||||
import { Field, Form, Formik } from "formik";
|
||||
import {
|
||||
DataGrid,
|
||||
GridColDef,
|
||||
} from '@mui/x-data-grid';
|
||||
import {loadColumns} from "./configureWorkers_comp_classesCols";
|
||||
import _ from 'lodash';
|
||||
import dataFormatter from '../../helpers/dataFormatter'
|
||||
import {dataGridStyles} from "../../styles";
|
||||
|
||||
|
||||
|
||||
const perPage = 10
|
||||
|
||||
const TableSampleWorkers_comp_classes = ({ filterItems, setFilterItems, filters, showGrid }) => {
|
||||
const notify = (type, msg) => toast( msg, {type, position: "bottom-center"});
|
||||
|
||||
const dispatch = useAppDispatch();
|
||||
const router = useRouter();
|
||||
|
||||
const pagesList = [];
|
||||
const [id, setId] = useState(null);
|
||||
const [currentPage, setCurrentPage] = useState(0);
|
||||
const [filterRequest, setFilterRequest] = React.useState('');
|
||||
const [columns, setColumns] = useState<GridColDef[]>([]);
|
||||
const [selectedRows, setSelectedRows] = useState([]);
|
||||
const [sortModel, setSortModel] = useState([
|
||||
{
|
||||
field: '',
|
||||
sort: 'desc',
|
||||
},
|
||||
]);
|
||||
|
||||
const { workers_comp_classes, loading, count, notify: workers_comp_classesNotify, refetch } = useAppSelector((state) => state.workers_comp_classes)
|
||||
const { currentUser } = useAppSelector((state) => state.auth);
|
||||
const focusRing = useAppSelector((state) => state.style.focusRingColor);
|
||||
const bgColor = useAppSelector((state) => state.style.bgLayoutColor);
|
||||
const corners = useAppSelector((state) => state.style.corners);
|
||||
const numPages = Math.floor(count / perPage) === 0 ? 1 : Math.ceil(count / perPage);
|
||||
for (let i = 0; i < numPages; i++) {
|
||||
pagesList.push(i);
|
||||
}
|
||||
|
||||
const loadData = async (page = currentPage, request = filterRequest) => {
|
||||
if (page !== currentPage) setCurrentPage(page);
|
||||
if (request !== filterRequest) setFilterRequest(request);
|
||||
const { sort, field } = sortModel[0];
|
||||
|
||||
const query = `?page=${page}&limit=${perPage}${request}&sort=${sort}&field=${field}`;
|
||||
dispatch(fetch({ limit: perPage, page, query }));
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (workers_comp_classesNotify.showNotification) {
|
||||
notify(workers_comp_classesNotify.typeNotification, workers_comp_classesNotify.textNotification);
|
||||
}
|
||||
}, [workers_comp_classesNotify.showNotification]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!currentUser) return;
|
||||
loadData();
|
||||
}, [sortModel, currentUser]);
|
||||
|
||||
useEffect(() => {
|
||||
if (refetch) {
|
||||
loadData(0);
|
||||
dispatch(setRefetch(false));
|
||||
}
|
||||
}, [refetch, dispatch]);
|
||||
|
||||
const [isModalInfoActive, setIsModalInfoActive] = useState(false)
|
||||
const [isModalTrashActive, setIsModalTrashActive] = useState(false)
|
||||
|
||||
const handleModalAction = () => {
|
||||
setIsModalInfoActive(false)
|
||||
setIsModalTrashActive(false)
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
const handleDeleteModalAction = (id: string) => {
|
||||
setId(id)
|
||||
setIsModalTrashActive(true)
|
||||
}
|
||||
const handleDeleteAction = async () => {
|
||||
if (id) {
|
||||
await dispatch(deleteItem(id));
|
||||
await loadData(0);
|
||||
setIsModalTrashActive(false);
|
||||
}
|
||||
};
|
||||
|
||||
const generateFilterRequests = useMemo(() => {
|
||||
let request = '&';
|
||||
filterItems.forEach((item) => {
|
||||
const isRangeFilter = filters.find(
|
||||
(filter) =>
|
||||
filter.title === item.fields.selectedField &&
|
||||
(filter.number || filter.date),
|
||||
);
|
||||
|
||||
if (isRangeFilter) {
|
||||
const from = item.fields.filterValueFrom;
|
||||
const to = item.fields.filterValueTo;
|
||||
if (from) {
|
||||
request += `${item.fields.selectedField}Range=${from}&`;
|
||||
}
|
||||
if (to) {
|
||||
request += `${item.fields.selectedField}Range=${to}&`;
|
||||
}
|
||||
} else {
|
||||
const value = item.fields.filterValue;
|
||||
if (value) {
|
||||
request += `${item.fields.selectedField}=${value}&`;
|
||||
}
|
||||
}
|
||||
});
|
||||
return request;
|
||||
}, [filterItems, filters]);
|
||||
|
||||
const deleteFilter = (value) => {
|
||||
const newItems = filterItems.filter((item) => item.id !== value);
|
||||
|
||||
if (newItems.length) {
|
||||
setFilterItems(newItems);
|
||||
} else {
|
||||
loadData(0, '');
|
||||
|
||||
setFilterItems(newItems);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSubmit = () => {
|
||||
loadData(0, generateFilterRequests);
|
||||
|
||||
};
|
||||
|
||||
const handleChange = (id) => (e) => {
|
||||
const value = e.target.value;
|
||||
const name = e.target.name;
|
||||
|
||||
setFilterItems(
|
||||
filterItems.map((item) => {
|
||||
if (item.id !== id) return item;
|
||||
if (name === 'selectedField') return { id, fields: { [name]: value } };
|
||||
|
||||
return { id, fields: { ...item.fields, [name]: value } }
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
const handleReset = () => {
|
||||
setFilterItems([]);
|
||||
loadData(0, '');
|
||||
|
||||
};
|
||||
|
||||
const onPageChange = (page: number) => {
|
||||
loadData(page);
|
||||
setCurrentPage(page);
|
||||
};
|
||||
|
||||
|
||||
useEffect(() => {
|
||||
if (!currentUser) return;
|
||||
|
||||
loadColumns(
|
||||
handleDeleteModalAction,
|
||||
`workers_comp_classes`,
|
||||
currentUser,
|
||||
).then((newCols) => setColumns(newCols));
|
||||
}, [currentUser]);
|
||||
|
||||
|
||||
|
||||
const handleTableSubmit = async (id: string, data) => {
|
||||
|
||||
if (!_.isEmpty(data)) {
|
||||
await dispatch(update({ id, data }))
|
||||
.unwrap()
|
||||
.then((res) => res)
|
||||
.catch((err) => {
|
||||
throw new Error(err);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const onDeleteRows = async (selectedRows) => {
|
||||
await dispatch(deleteItemsByIds(selectedRows));
|
||||
await loadData(0);
|
||||
};
|
||||
|
||||
const controlClasses =
|
||||
'w-full py-2 px-2 my-2 rounded dark:placeholder-gray-400 ' +
|
||||
` ${bgColor} ${focusRing} ${corners} ` +
|
||||
'dark:bg-slate-800 border';
|
||||
|
||||
|
||||
const dataGrid = (
|
||||
<div className='relative overflow-x-auto'>
|
||||
<DataGrid
|
||||
autoHeight
|
||||
rowHeight={64}
|
||||
sx={dataGridStyles}
|
||||
className={'datagrid--table'}
|
||||
getRowClassName={() => `datagrid--row`}
|
||||
rows={workers_comp_classes ?? []}
|
||||
columns={columns}
|
||||
initialState={{
|
||||
pagination: {
|
||||
paginationModel: {
|
||||
pageSize: 10,
|
||||
},
|
||||
},
|
||||
}}
|
||||
disableRowSelectionOnClick
|
||||
onProcessRowUpdateError={(params) => {
|
||||
console.log('Error', params);
|
||||
}}
|
||||
processRowUpdate={async (newRow, oldRow) => {
|
||||
const data = dataFormatter.dataGridEditFormatter(newRow);
|
||||
|
||||
try {
|
||||
await handleTableSubmit(newRow.id, data);
|
||||
return newRow;
|
||||
} catch {
|
||||
return oldRow;
|
||||
}
|
||||
}}
|
||||
sortingMode={'server'}
|
||||
checkboxSelection
|
||||
onRowSelectionModelChange={(ids) => {
|
||||
setSelectedRows(ids)
|
||||
}}
|
||||
onSortModelChange={(params) => {
|
||||
params.length
|
||||
? setSortModel(params)
|
||||
: setSortModel([{ field: '', sort: 'desc' }]);
|
||||
}}
|
||||
rowCount={count}
|
||||
pageSizeOptions={[10]}
|
||||
paginationMode={'server'}
|
||||
loading={loading}
|
||||
onPaginationModelChange={(params) => {
|
||||
onPageChange(params.page);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
|
||||
return (
|
||||
<>
|
||||
{filterItems && Array.isArray( filterItems ) && filterItems.length ?
|
||||
<CardBox>
|
||||
<Formik
|
||||
initialValues={{
|
||||
checkboxes: ['lorem'],
|
||||
switches: ['lorem'],
|
||||
radio: 'lorem',
|
||||
}}
|
||||
onSubmit={() => null}
|
||||
>
|
||||
<Form>
|
||||
<>
|
||||
{filterItems && filterItems.map((filterItem) => {
|
||||
return (
|
||||
<div key={filterItem.id} className="flex mb-4">
|
||||
<div className="flex flex-col w-full mr-3">
|
||||
<div className=" text-gray-500 font-bold">Filter</div>
|
||||
<Field
|
||||
className={controlClasses}
|
||||
name='selectedField'
|
||||
id='selectedField'
|
||||
component='select'
|
||||
value={filterItem?.fields?.selectedField || ''}
|
||||
onChange={handleChange(filterItem.id)}
|
||||
>
|
||||
{filters.map((selectOption) => (
|
||||
<option
|
||||
key={selectOption.title}
|
||||
value={`${selectOption.title}`}
|
||||
>
|
||||
{selectOption.label}
|
||||
</option>
|
||||
))}
|
||||
</Field>
|
||||
</div>
|
||||
{filters.find((filter) =>
|
||||
filter.title === filterItem?.fields?.selectedField
|
||||
)?.type === 'enum' ? (
|
||||
<div className="flex flex-col w-full mr-3">
|
||||
<div className="text-gray-500 font-bold">
|
||||
Value
|
||||
</div>
|
||||
<Field
|
||||
className={controlClasses}
|
||||
name="filterValue"
|
||||
id='filterValue'
|
||||
component="select"
|
||||
value={filterItem?.fields?.filterValue || ''}
|
||||
onChange={handleChange(filterItem.id)}
|
||||
>
|
||||
<option value="">Select Value</option>
|
||||
{filters.find((filter) =>
|
||||
filter.title === filterItem?.fields?.selectedField
|
||||
)?.options?.map((option) => (
|
||||
<option key={option} value={option}>
|
||||
{option}
|
||||
</option>
|
||||
))}
|
||||
</Field>
|
||||
</div>
|
||||
) : filters.find((filter) =>
|
||||
filter.title === filterItem?.fields?.selectedField
|
||||
)?.number ? (
|
||||
<div className="flex flex-row w-full mr-3">
|
||||
<div className="flex flex-col w-full mr-3">
|
||||
<div className=" text-gray-500 font-bold">From</div>
|
||||
<Field
|
||||
className={controlClasses}
|
||||
name='filterValueFrom'
|
||||
placeholder='From'
|
||||
id='filterValueFrom'
|
||||
value={filterItem?.fields?.filterValueFrom || ''}
|
||||
onChange={handleChange(filterItem.id)}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col w-full">
|
||||
<div className=" text-gray-500 font-bold">To</div>
|
||||
<Field
|
||||
className={controlClasses}
|
||||
name='filterValueTo'
|
||||
placeholder='to'
|
||||
id='filterValueTo'
|
||||
value={filterItem?.fields?.filterValueTo || ''}
|
||||
onChange={handleChange(filterItem.id)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
) : filters.find(
|
||||
(filter) =>
|
||||
filter.title ===
|
||||
filterItem?.fields?.selectedField
|
||||
)?.date ? (
|
||||
<div className='flex flex-row w-full mr-3'>
|
||||
<div className='flex flex-col w-full mr-3'>
|
||||
<div className=' text-gray-500 font-bold'>
|
||||
From
|
||||
</div>
|
||||
<Field
|
||||
className={controlClasses}
|
||||
name='filterValueFrom'
|
||||
placeholder='From'
|
||||
id='filterValueFrom'
|
||||
type='datetime-local'
|
||||
value={filterItem?.fields?.filterValueFrom || ''}
|
||||
onChange={handleChange(filterItem.id)}
|
||||
/>
|
||||
</div>
|
||||
<div className='flex flex-col w-full'>
|
||||
<div className=' text-gray-500 font-bold'>To</div>
|
||||
<Field
|
||||
className={controlClasses}
|
||||
name='filterValueTo'
|
||||
placeholder='to'
|
||||
id='filterValueTo'
|
||||
type='datetime-local'
|
||||
value={filterItem?.fields?.filterValueTo || ''}
|
||||
onChange={handleChange(filterItem.id)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col w-full mr-3">
|
||||
<div className=" text-gray-500 font-bold">Contains</div>
|
||||
<Field
|
||||
className={controlClasses}
|
||||
name='filterValue'
|
||||
placeholder='Contained'
|
||||
id='filterValue'
|
||||
value={filterItem?.fields?.filterValue || ''}
|
||||
onChange={handleChange(filterItem.id)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex flex-col">
|
||||
<div className=" text-gray-500 font-bold">Action</div>
|
||||
<BaseButton
|
||||
className="my-2"
|
||||
type='reset'
|
||||
color='danger'
|
||||
label='Delete'
|
||||
onClick={() => {
|
||||
deleteFilter(filterItem.id)
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
<div className="flex">
|
||||
<BaseButton
|
||||
className="my-2 mr-3"
|
||||
color="success"
|
||||
label='Apply'
|
||||
onClick={handleSubmit}
|
||||
/>
|
||||
<BaseButton
|
||||
className="my-2"
|
||||
color='info'
|
||||
label='Cancel'
|
||||
onClick={handleReset}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
</Form>
|
||||
</Formik>
|
||||
</CardBox> : null
|
||||
}
|
||||
<CardBoxModal
|
||||
title="Please confirm"
|
||||
buttonColor="info"
|
||||
buttonLabel={loading ? 'Deleting...' : 'Confirm'}
|
||||
isActive={isModalTrashActive}
|
||||
onConfirm={handleDeleteAction}
|
||||
onCancel={handleModalAction}
|
||||
>
|
||||
<p>Are you sure you want to delete this item?</p>
|
||||
</CardBoxModal>
|
||||
|
||||
|
||||
{dataGrid}
|
||||
|
||||
|
||||
|
||||
|
||||
{selectedRows.length > 0 &&
|
||||
createPortal(
|
||||
<BaseButton
|
||||
className='me-4'
|
||||
color='danger'
|
||||
label={`Delete ${selectedRows.length === 1 ? 'Row' : 'Rows'}`}
|
||||
onClick={() => onDeleteRows(selectedRows)}
|
||||
/>,
|
||||
document.getElementById('delete-rows-button'),
|
||||
)}
|
||||
<ToastContainer />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default TableSampleWorkers_comp_classes
|
||||
@ -0,0 +1,88 @@
|
||||
import React from 'react';
|
||||
import BaseIcon from '../BaseIcon';
|
||||
import { mdiEye, mdiTrashCan, mdiPencilOutline } from '@mdi/js';
|
||||
import axios from 'axios';
|
||||
import {
|
||||
GridActionsCellItem,
|
||||
GridRowParams,
|
||||
GridValueGetterParams,
|
||||
} from '@mui/x-data-grid';
|
||||
import ImageField from '../ImageField';
|
||||
import {saveFile} from "../../helpers/fileSaver";
|
||||
import dataFormatter from '../../helpers/dataFormatter'
|
||||
import DataGridMultiSelect from "../DataGridMultiSelect";
|
||||
import ListActionsPopover from '../ListActionsPopover';
|
||||
|
||||
import {hasPermission} from "../../helpers/userPermissions";
|
||||
|
||||
type Params = (id: string) => void;
|
||||
|
||||
export const loadColumns = async (
|
||||
onDelete: Params,
|
||||
entityName: string,
|
||||
|
||||
user
|
||||
|
||||
) => {
|
||||
async function callOptionsApi(entityName: string) {
|
||||
|
||||
if (!hasPermission(user, 'READ_' + entityName.toUpperCase())) return [];
|
||||
|
||||
try {
|
||||
const data = await axios(`/${entityName}/autocomplete?limit=100`);
|
||||
return data.data;
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
const hasUpdatePermission = hasPermission(user, 'UPDATE_WORKERS_COMP_CLASSES')
|
||||
|
||||
return [
|
||||
{
|
||||
field: 'name',
|
||||
headerName: 'Name',
|
||||
flex: 1,
|
||||
minWidth: 120,
|
||||
filterable: false,
|
||||
headerClassName: 'datagrid--header',
|
||||
cellClassName: 'datagrid--cell',
|
||||
editable: hasUpdatePermission,
|
||||
},
|
||||
{
|
||||
field: 'percentage',
|
||||
headerName: 'Percentage (%)',
|
||||
flex: 1,
|
||||
minWidth: 120,
|
||||
filterable: false,
|
||||
headerClassName: 'datagrid--header',
|
||||
cellClassName: 'datagrid--cell',
|
||||
editable: hasUpdatePermission,
|
||||
type: 'number',
|
||||
},
|
||||
{
|
||||
field: 'actions',
|
||||
type: 'actions',
|
||||
minWidth: 30,
|
||||
headerClassName: 'datagrid--header',
|
||||
cellClassName: 'datagrid--cell',
|
||||
getActions: (params: GridRowParams) => {
|
||||
|
||||
return [
|
||||
<div key={params?.row?.id}>
|
||||
<ListActionsPopover
|
||||
onDelete={onDelete}
|
||||
itemId={params?.row?.id}
|
||||
pathEdit={`/workers_comp_classes/workers_comp_classes-edit/?id=${params?.row?.id}`}
|
||||
pathView={`/workers_comp_classes/workers_comp_classes-view/?id=${params?.row?.id}`}
|
||||
|
||||
hasUpdatePermission={hasUpdatePermission}
|
||||
|
||||
/>
|
||||
</div>,
|
||||
]
|
||||
},
|
||||
},
|
||||
];
|
||||
};
|
||||
@ -8,7 +8,7 @@ export const localStorageStyleKey = 'style'
|
||||
|
||||
export const containerMaxW = 'xl:max-w-full xl:mx-auto 2xl:mx-20'
|
||||
|
||||
export const appTitle = 'created by Flatlogic generator!'
|
||||
export const appTitle = 'Major League Pressure Washing'
|
||||
|
||||
export const getPageTitle = (currentPageTitle: string) => `${currentPageTitle} — ${appTitle}`
|
||||
|
||||
|
||||
@ -1,5 +1,4 @@
|
||||
import React, { ReactNode, useEffect } from 'react'
|
||||
import { useState } from 'react'
|
||||
import React, { ReactNode, useEffect , useState } from 'react'
|
||||
import jwt from 'jsonwebtoken';
|
||||
import { mdiForwardburger, mdiBackburger, mdiMenu } from '@mdi/js'
|
||||
import menuAside from '../menuAside'
|
||||
|
||||
@ -6,6 +6,20 @@ const menuAside: MenuAsideItem[] = [
|
||||
href: '/dashboard',
|
||||
icon: icon.mdiViewDashboardOutline,
|
||||
label: 'Dashboard',
|
||||
permissions: 'UPDATE_USERS',
|
||||
},
|
||||
|
||||
{
|
||||
href: '/log-work',
|
||||
label: 'Log Work',
|
||||
icon: icon.mdiPencil,
|
||||
permissions: 'CREATE_JOB_LOGS'
|
||||
},
|
||||
{
|
||||
href: '/my-logs',
|
||||
label: 'My Logs',
|
||||
icon: icon.mdiViewList,
|
||||
permissions: 'READ_JOB_LOGS'
|
||||
},
|
||||
|
||||
{
|
||||
@ -14,7 +28,7 @@ const menuAside: MenuAsideItem[] = [
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
icon: icon.mdiAccountGroup ?? icon.mdiTable,
|
||||
permissions: 'READ_USERS'
|
||||
permissions: 'UPDATE_USERS'
|
||||
},
|
||||
{
|
||||
href: '/roles/roles-list',
|
||||
@ -22,7 +36,7 @@ const menuAside: MenuAsideItem[] = [
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
icon: icon.mdiShieldAccountVariantOutline ?? icon.mdiTable,
|
||||
permissions: 'READ_ROLES'
|
||||
permissions: 'UPDATE_USERS'
|
||||
},
|
||||
{
|
||||
href: '/permissions/permissions-list',
|
||||
@ -30,7 +44,7 @@ const menuAside: MenuAsideItem[] = [
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
icon: icon.mdiShieldAccountOutline ?? icon.mdiTable,
|
||||
permissions: 'READ_PERMISSIONS'
|
||||
permissions: 'UPDATE_USERS'
|
||||
},
|
||||
{
|
||||
href: '/customers/customers-list',
|
||||
@ -38,7 +52,7 @@ const menuAside: MenuAsideItem[] = [
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
icon: 'mdiAccountMultiple' in icon ? icon['mdiAccountMultiple' as keyof typeof icon] : icon.mdiTable ?? icon.mdiTable,
|
||||
permissions: 'READ_CUSTOMERS'
|
||||
permissions: 'UPDATE_USERS'
|
||||
},
|
||||
{
|
||||
href: '/vehicles/vehicles-list',
|
||||
@ -46,7 +60,13 @@ const menuAside: MenuAsideItem[] = [
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
icon: 'mdiTruck' in icon ? icon['mdiTruck' as keyof typeof icon] : icon.mdiTable ?? icon.mdiTable,
|
||||
permissions: 'READ_VEHICLES'
|
||||
permissions: 'UPDATE_USERS'
|
||||
},
|
||||
{
|
||||
href: '/workers_comp_classes/workers_comp_classes-list',
|
||||
label: 'Workmans Comp',
|
||||
icon: icon.mdiTable,
|
||||
permissions: 'UPDATE_USERS'
|
||||
},
|
||||
{
|
||||
href: '/pay_types/pay_types-list',
|
||||
@ -54,7 +74,7 @@ const menuAside: MenuAsideItem[] = [
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
icon: 'mdiCashMultiple' in icon ? icon['mdiCashMultiple' as keyof typeof icon] : icon.mdiTable ?? icon.mdiTable,
|
||||
permissions: 'READ_PAY_TYPES'
|
||||
permissions: 'UPDATE_USERS'
|
||||
},
|
||||
{
|
||||
href: '/employee_pay_types/employee_pay_types-list',
|
||||
@ -62,7 +82,7 @@ const menuAside: MenuAsideItem[] = [
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
icon: 'mdiLinkVariant' in icon ? icon['mdiLinkVariant' as keyof typeof icon] : icon.mdiTable ?? icon.mdiTable,
|
||||
permissions: 'READ_EMPLOYEE_PAY_TYPES'
|
||||
permissions: 'UPDATE_USERS'
|
||||
},
|
||||
{
|
||||
href: '/chemical_products/chemical_products-list',
|
||||
@ -70,15 +90,13 @@ const menuAside: MenuAsideItem[] = [
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
icon: 'mdiFlask' in icon ? icon['mdiFlask' as keyof typeof icon] : icon.mdiTable ?? icon.mdiTable,
|
||||
permissions: 'READ_CHEMICAL_PRODUCTS'
|
||||
permissions: 'UPDATE_USERS'
|
||||
},
|
||||
{
|
||||
href: '/job_logs/job_logs-list',
|
||||
label: 'Job logs',
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
label: 'All Job Logs',
|
||||
icon: 'mdiClipboardTextClock' in icon ? icon['mdiClipboardTextClock' as keyof typeof icon] : icon.mdiTable ?? icon.mdiTable,
|
||||
permissions: 'READ_JOB_LOGS'
|
||||
permissions: 'UPDATE_USERS'
|
||||
},
|
||||
{
|
||||
href: '/job_chemical_usages/job_chemical_usages-list',
|
||||
@ -86,7 +104,7 @@ const menuAside: MenuAsideItem[] = [
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
icon: 'mdiFlaskOutline' in icon ? icon['mdiFlaskOutline' as keyof typeof icon] : icon.mdiTable ?? icon.mdiTable,
|
||||
permissions: 'READ_JOB_CHEMICAL_USAGES'
|
||||
permissions: 'UPDATE_USERS'
|
||||
},
|
||||
{
|
||||
href: '/payroll_runs/payroll_runs-list',
|
||||
@ -94,7 +112,7 @@ const menuAside: MenuAsideItem[] = [
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
icon: 'mdiCalendarClock' in icon ? icon['mdiCalendarClock' as keyof typeof icon] : icon.mdiTable ?? icon.mdiTable,
|
||||
permissions: 'READ_PAYROLL_RUNS'
|
||||
permissions: 'UPDATE_USERS'
|
||||
},
|
||||
{
|
||||
href: '/payroll_line_items/payroll_line_items-list',
|
||||
@ -102,7 +120,13 @@ const menuAside: MenuAsideItem[] = [
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
icon: 'mdiFileDocumentOutline' in icon ? icon['mdiFileDocumentOutline' as keyof typeof icon] : icon.mdiTable ?? icon.mdiTable,
|
||||
permissions: 'READ_PAYROLL_LINE_ITEMS'
|
||||
permissions: 'UPDATE_USERS'
|
||||
},
|
||||
{
|
||||
href: '/reports',
|
||||
label: 'Payroll Dashboard',
|
||||
icon: icon.mdiChartBar,
|
||||
permissions: 'UPDATE_USERS'
|
||||
},
|
||||
{
|
||||
href: '/profile',
|
||||
@ -116,8 +140,8 @@ const menuAside: MenuAsideItem[] = [
|
||||
target: '_blank',
|
||||
label: 'Swagger API',
|
||||
icon: icon.mdiFileCode,
|
||||
permissions: 'READ_API_DOCS'
|
||||
permissions: 'UPDATE_USERS'
|
||||
},
|
||||
]
|
||||
|
||||
export default menuAside
|
||||
export default menuAside
|
||||
@ -149,7 +149,7 @@ function MyApp({ Component, pageProps }: AppPropsWithLayout) {
|
||||
setStepsEnabled(false);
|
||||
};
|
||||
|
||||
const title = 'Pressure Wash Payroll'
|
||||
const title = 'Major League Pressure Washing'
|
||||
const description = "Internal payroll app for pressure washing techs to log jobs, track mileage and chemicals, and run payroll reports."
|
||||
const url = "https://flatlogic.com/"
|
||||
const image = "https://project-screens.s3.amazonaws.com/screenshots/39157/app-hero-20260312-154649.png"
|
||||
|
||||
@ -46,9 +46,18 @@ const Dashboard = () => {
|
||||
const { isFetchingQuery } = useAppSelector((state) => state.openAi);
|
||||
|
||||
const { rolesWidgets, loading } = useAppSelector((state) => state.roles);
|
||||
const isAdmin = hasPermission(currentUser, "UPDATE_USERS");
|
||||
|
||||
|
||||
async function loadData() {
|
||||
if (!currentUser) return;
|
||||
|
||||
if (!isAdmin) {
|
||||
// For regular employees, we just want to load their own logs
|
||||
axios.get('/job_logs/count?employee=' + currentUser.id).then((res) => setJob_logs(res.data.count)).catch(() => setJob_logs(0));
|
||||
return;
|
||||
}
|
||||
|
||||
const entities = ['users','roles','permissions','customers','vehicles','pay_types','employee_pay_types','chemical_products','job_logs','job_chemical_usages','payroll_runs','payroll_line_items',];
|
||||
const fns = [setUsers,setRoles,setPermissions,setCustomers,setVehicles,setPay_types,setEmployee_pay_types,setChemical_products,setJob_logs,setJob_chemical_usages,setPayroll_runs,setPayroll_line_items,];
|
||||
|
||||
@ -142,9 +151,12 @@ const Dashboard = () => {
|
||||
))}
|
||||
</div>
|
||||
|
||||
|
||||
{!!rolesWidgets.length && <hr className='my-6 ' />}
|
||||
|
||||
{isAdmin ? (
|
||||
<div id="dashboard" className='grid grid-cols-1 gap-6 lg:grid-cols-3 mb-6'>
|
||||
|
||||
|
||||
|
||||
{hasPermission(currentUser, 'READ_USERS') && <Link href={'/users/users-list'}>
|
||||
@ -481,11 +493,34 @@ const Dashboard = () => {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</Link>}
|
||||
|
||||
|
||||
</div>
|
||||
) : (
|
||||
<div id="dashboard" className="grid grid-cols-1 gap-6 lg:grid-cols-3 mb-6">
|
||||
<Link href={'/my-logs'}>
|
||||
<div className={"dark:bg-dark-900 dark:border-dark-700 p-6 " + (corners !== 'rounded-full' ? corners : 'rounded-3xl') + " " + cardsStyle}>
|
||||
<div className="flex justify-between align-center">
|
||||
<div>
|
||||
<div className="text-lg leading-tight text-gray-500 dark:text-gray-400">
|
||||
My Logs
|
||||
</div>
|
||||
<div className="text-3xl leading-tight font-semibold">
|
||||
{job_logs}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<BaseIcon className={iconsColor} w="w-16" h="h-16" size={48} path={icon.mdiClipboardTextClock} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
</SectionMain>
|
||||
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@ -26,7 +26,7 @@ export default function Starter() {
|
||||
const [contentPosition, setContentPosition] = useState('left');
|
||||
const textColor = useAppSelector((state) => state.style.linkColor);
|
||||
|
||||
const title = 'Pressure Wash Payroll'
|
||||
const title = 'Major League Pressure Washing'
|
||||
|
||||
// Fetch Pexels image/video
|
||||
useEffect(() => {
|
||||
@ -128,7 +128,7 @@ export default function Starter() {
|
||||
: null}
|
||||
<div className='flex items-center justify-center flex-col space-y-4 w-full lg:w-full'>
|
||||
<CardBox className='w-full md:w-3/5 lg:w-2/3'>
|
||||
<CardBoxComponentTitle title="Welcome to your Pressure Wash Payroll app!"/>
|
||||
<CardBoxComponentTitle title="Welcome to your Major League Pressure Washing app!"/>
|
||||
|
||||
<div className="space-y-3">
|
||||
<p className='text-center text-gray-500'>This is a React.js/Node.js app generated by the <a className={`${textColor}`} href="https://flatlogic.com/generator">Flatlogic Web App Generator</a></p>
|
||||
|
||||
@ -196,7 +196,7 @@ const EditJob_logsPage = () => {
|
||||
|
||||
|
||||
|
||||
workers_comp_class: '',
|
||||
workersCompClass: '',
|
||||
|
||||
|
||||
|
||||
@ -723,17 +723,9 @@ const EditJob_logsPage = () => {
|
||||
|
||||
|
||||
|
||||
<FormField label="WorkmansCompensationClass" labelFor="workers_comp_class">
|
||||
<Field name="workers_comp_class" id="workers_comp_class" component="select">
|
||||
|
||||
<option value="roof">roof</option>
|
||||
|
||||
<option value="ladder">ladder</option>
|
||||
|
||||
<option value="ground">ground</option>
|
||||
|
||||
</Field>
|
||||
</FormField>
|
||||
<FormField label="Workmans Comp Class" labelFor="workersCompClassId">
|
||||
<Field name="workersCompClass" id="workersCompClass" component={SelectField} options={initialValues.workersCompClass} itemRef={'workers_comp_classes'} showField={'name'}></Field>
|
||||
</FormField>
|
||||
|
||||
|
||||
|
||||
|
||||
@ -119,7 +119,7 @@ const initialValues = {
|
||||
|
||||
|
||||
|
||||
workers_comp_class: 'roof',
|
||||
workersCompClass: '',
|
||||
|
||||
|
||||
|
||||
@ -457,16 +457,8 @@ const Job_logsNew = () => {
|
||||
|
||||
|
||||
|
||||
<FormField label="WorkmansCompensationClass" labelFor="workers_comp_class">
|
||||
<Field name="workers_comp_class" id="workers_comp_class" component="select">
|
||||
|
||||
<option value="roof">roof</option>
|
||||
|
||||
<option value="ladder">ladder</option>
|
||||
|
||||
<option value="ground">ground</option>
|
||||
|
||||
</Field>
|
||||
<FormField label="Workmans Comp Class" labelFor="workersCompClassId">
|
||||
<Field name="workersCompClass" id="workersCompClass" component={SelectField} options={[]} itemRef={'workers_comp_classes'} showField={'name'}></Field>
|
||||
</FormField>
|
||||
|
||||
|
||||
|
||||
181
frontend/src/pages/log-work.tsx
Normal file
181
frontend/src/pages/log-work.tsx
Normal file
@ -0,0 +1,181 @@
|
||||
import { mdiPencil, mdiPlus, mdiTrashCan } from '@mdi/js';
|
||||
import Head from 'next/head';
|
||||
import React, { ReactElement, useEffect, useState } from 'react';
|
||||
import CardBox from '../components/CardBox';
|
||||
import LayoutAuthenticated from '../layouts/Authenticated';
|
||||
import SectionMain from '../components/SectionMain';
|
||||
import SectionTitleLineWithButton from '../components/SectionTitleLineWithButton';
|
||||
import { getPageTitle } from '../config';
|
||||
|
||||
import { Field, Form, Formik, FieldArray } from 'formik';
|
||||
import FormField from '../components/FormField';
|
||||
import BaseDivider from '../components/BaseDivider';
|
||||
import BaseButtons from '../components/BaseButtons';
|
||||
import BaseButton from '../components/BaseButton';
|
||||
import { SelectField } from '../components/SelectField';
|
||||
import { useRouter } from 'next/router';
|
||||
import { create } from '../stores/job_logs/job_logsSlice';
|
||||
import { useAppDispatch, useAppSelector } from '../stores/hooks';
|
||||
import axios from 'axios';
|
||||
|
||||
const LogWorkPage = () => {
|
||||
const router = useRouter();
|
||||
const dispatch = useAppDispatch();
|
||||
const currentUser = useAppSelector((state) => state.auth.currentUser);
|
||||
const [assignedPayTypes, setAssignedPayTypes] = useState<any[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
if (currentUser?.id) {
|
||||
axios.get(`/employee_pay_types?employee=${currentUser.id}&active=true`)
|
||||
.then((res) => {
|
||||
if (res.data && res.data.rows) {
|
||||
// Ensure we are extracting the inner pay_type relation from employee_pay_types
|
||||
const payTypes = res.data.rows.map((row: any) => row.pay_type).filter(Boolean);
|
||||
setAssignedPayTypes(payTypes);
|
||||
}
|
||||
})
|
||||
.catch((err) => console.error('Failed to fetch assigned pay types:', err));
|
||||
}
|
||||
}, [currentUser]);
|
||||
|
||||
const initialValues = {
|
||||
work_date: new Date().toISOString().slice(0, 16),
|
||||
employee: currentUser?.id || '',
|
||||
customer: '',
|
||||
hours_conducted: '',
|
||||
client_paid: '',
|
||||
workersCompClass: '',
|
||||
pay_type: '',
|
||||
vehicle: '',
|
||||
odometer_start: '',
|
||||
odometer_end: '',
|
||||
job_address: '',
|
||||
status: 'submitted',
|
||||
notes_to_admin: '',
|
||||
chemical_usages: [],
|
||||
};
|
||||
|
||||
const handleSubmit = async (data: any) => {
|
||||
await dispatch(create(data));
|
||||
await router.push('/my-logs');
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<title>{getPageTitle('Log Work')}</title>
|
||||
</Head>
|
||||
<SectionMain>
|
||||
<SectionTitleLineWithButton icon={mdiPencil} title="Log Work" main>
|
||||
{''}
|
||||
</SectionTitleLineWithButton>
|
||||
<CardBox>
|
||||
<Formik initialValues={initialValues} onSubmit={(values) => handleSubmit(values)}>
|
||||
{({ values }) => (
|
||||
<Form>
|
||||
<FormField label="Work Date">
|
||||
<Field type="datetime-local" name="work_date" />
|
||||
</FormField>
|
||||
<FormField label="Customer" labelFor="customer">
|
||||
<Field name="customer" id="customer" placeholder="Enter customer name" />
|
||||
</FormField>
|
||||
<FormField label="Hours Conducted">
|
||||
<Field type="number" name="hours_conducted" placeholder="Hours" />
|
||||
</FormField>
|
||||
<FormField label="Client Paid">
|
||||
<Field type="number" name="client_paid" placeholder="Amount" />
|
||||
</FormField>
|
||||
<FormField label="Worker's Comp Class" labelFor="workersCompClass">
|
||||
<Field name="workersCompClass" id="workersCompClass" component={SelectField} options={[]} itemRef={"workers_comp_classes"} showField={"name"} />
|
||||
</FormField>
|
||||
<FormField label="Pay Type" labelFor="pay_type">
|
||||
<Field name="pay_type" id="pay_type" as="select">
|
||||
<option value="">Select an assigned pay type</option>
|
||||
{assignedPayTypes.map((pt) => (
|
||||
<option key={pt.id} value={pt.id}>
|
||||
{pt.name || pt.pay_method}
|
||||
</option>
|
||||
))}
|
||||
</Field>
|
||||
</FormField>
|
||||
<FormField label="Vehicle" labelFor="vehicle">
|
||||
<Field name="vehicle" id="vehicle" component={SelectField} options={[]} itemRef={'vehicles'} />
|
||||
</FormField>
|
||||
<FormField label="Odometer Start">
|
||||
<Field type="number" name="odometer_start" placeholder="Start" />
|
||||
</FormField>
|
||||
<FormField label="Odometer End">
|
||||
<Field type="number" name="odometer_end" placeholder="End" />
|
||||
</FormField>
|
||||
<FormField label="Job Address">
|
||||
<Field name="job_address" placeholder="Address" />
|
||||
</FormField>
|
||||
<FormField label="Notes to Admin" hasTextareaHeight>
|
||||
<Field name="notes_to_admin" as="textarea" placeholder="Notes..." />
|
||||
</FormField>
|
||||
|
||||
<BaseDivider />
|
||||
<h3 className="text-lg font-bold mb-4">Chemical Usage (Optional)</h3>
|
||||
<FieldArray name="chemical_usages">
|
||||
{({ push, remove }) => (
|
||||
<div>
|
||||
{values.chemical_usages.map((usage, index) => (
|
||||
<div key={index} className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4 items-end border p-4 rounded-lg bg-gray-50 dark:bg-slate-800">
|
||||
<FormField label="Chemical Product" labelFor={`chemical_usages.${index}.chemical_product`}>
|
||||
<Field
|
||||
name={`chemical_usages.${index}.chemical_product`}
|
||||
id={`chemical_usages.${index}.chemical_product`}
|
||||
component={SelectField}
|
||||
itemRef="chemical_products"
|
||||
showField="name"
|
||||
/>
|
||||
</FormField>
|
||||
<FormField label="Quantity Used" labelFor={`chemical_usages.${index}.quantity_used`}>
|
||||
<Field
|
||||
type="number"
|
||||
name={`chemical_usages.${index}.quantity_used`}
|
||||
id={`chemical_usages.${index}.quantity_used`}
|
||||
placeholder="e.g. 5.5"
|
||||
step="0.01"
|
||||
/>
|
||||
</FormField>
|
||||
<div className="mb-4">
|
||||
<BaseButton
|
||||
type="button"
|
||||
color="danger"
|
||||
label="Remove"
|
||||
icon={mdiTrashCan}
|
||||
onClick={() => remove(index)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
<BaseButton
|
||||
type="button"
|
||||
color="success"
|
||||
label="Add Chemical"
|
||||
icon={mdiPlus}
|
||||
onClick={() => push({ chemical_product: '', quantity_used: '' })}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</FieldArray>
|
||||
|
||||
<BaseDivider />
|
||||
<BaseButtons>
|
||||
<BaseButton type="submit" color="info" label="Submit Work Log" />
|
||||
</BaseButtons>
|
||||
</Form>
|
||||
)}
|
||||
</Formik>
|
||||
</CardBox>
|
||||
</SectionMain>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
LogWorkPage.getLayout = function getLayout(page: ReactElement) {
|
||||
return <LayoutAuthenticated>{page}</LayoutAuthenticated>;
|
||||
};
|
||||
|
||||
export default LogWorkPage;
|
||||
@ -44,7 +44,7 @@ export default function Login() {
|
||||
password: '2fa72adf',
|
||||
remember: true })
|
||||
|
||||
const title = 'Pressure Wash Payroll'
|
||||
const title = 'Major League Pressure Washing'
|
||||
|
||||
// Fetch Pexels image/video
|
||||
useEffect( () => {
|
||||
@ -165,7 +165,7 @@ export default function Login() {
|
||||
|
||||
<CardBox id="loginRoles" className='w-full md:w-3/5 lg:w-2/3'>
|
||||
|
||||
<h2 className="text-4xl font-semibold my-4">{title}</h2>
|
||||
<div className="flex flex-col items-center"><img src="/assets/logo.webp" alt="Logo" className="h-24 mb-4" /><h2 className="text-4xl font-semibold my-4 text-center">{title}</h2></div>
|
||||
|
||||
<div className='flex flex-row text-gray-500 justify-between'>
|
||||
<div>
|
||||
|
||||
51
frontend/src/pages/my-logs.tsx
Normal file
51
frontend/src/pages/my-logs.tsx
Normal file
@ -0,0 +1,51 @@
|
||||
import { mdiViewList, mdiChartTimelineVariant } from '@mdi/js';
|
||||
import Head from 'next/head';
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import type { ReactElement } from 'react';
|
||||
import LayoutAuthenticated from '../layouts/Authenticated';
|
||||
import SectionMain from '../components/SectionMain';
|
||||
import SectionTitleLineWithButton from '../components/SectionTitleLineWithButton';
|
||||
import { getPageTitle } from '../config';
|
||||
import { useAppDispatch, useAppSelector } from '../stores/hooks';
|
||||
import { fetch } from '../stores/job_logs/job_logsSlice';
|
||||
import ListJob_logs from '../components/Job_logs/ListJob_logs';
|
||||
|
||||
const MyLogsPage = () => {
|
||||
const dispatch = useAppDispatch();
|
||||
const currentUser = useAppSelector((state) => state.auth.currentUser);
|
||||
const { job_logs, loading } = useAppSelector((state) => state.job_logs);
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
|
||||
useEffect(() => {
|
||||
if (currentUser?.id) {
|
||||
dispatch(fetch({ filter: { employee: currentUser.id }, page: currentPage }));
|
||||
}
|
||||
}, [dispatch, currentUser, currentPage]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<title>{getPageTitle('My Logs')}</title>
|
||||
</Head>
|
||||
<SectionMain>
|
||||
<SectionTitleLineWithButton icon={mdiViewList} title="My Logs" main>
|
||||
{''}
|
||||
</SectionTitleLineWithButton>
|
||||
<ListJob_logs
|
||||
job_logs={job_logs}
|
||||
loading={loading}
|
||||
onDelete={() => console.log('Delete')}
|
||||
currentPage={currentPage}
|
||||
numPages={1}
|
||||
onPageChange={setCurrentPage}
|
||||
/>
|
||||
</SectionMain>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
MyLogsPage.getLayout = function getLayout(page: ReactElement) {
|
||||
return <LayoutAuthenticated>{page}</LayoutAuthenticated>;
|
||||
};
|
||||
|
||||
export default MyLogsPage;
|
||||
@ -128,6 +128,11 @@ const EditPay_typesPage = () => {
|
||||
|
||||
|
||||
|
||||
|
||||
'workers_comp_percentage': '',
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@ -406,7 +411,15 @@ const EditPay_typesPage = () => {
|
||||
|
||||
|
||||
|
||||
|
||||
<FormField
|
||||
label="WorkersCompPercentage"
|
||||
>
|
||||
<Field
|
||||
type="number"
|
||||
name="workers_comp_percentage"
|
||||
placeholder="WorkersCompPercentage"
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
|
||||
|
||||
@ -503,4 +516,4 @@ EditPay_typesPage.getLayout = function getLayout(page: ReactElement) {
|
||||
)
|
||||
}
|
||||
|
||||
export default EditPay_typesPage
|
||||
export default EditPay_typesPage
|
||||
@ -80,6 +80,8 @@ const initialValues = {
|
||||
|
||||
|
||||
commission_rate: '',
|
||||
|
||||
workers_comp_percentage: '',
|
||||
|
||||
|
||||
|
||||
@ -285,6 +287,15 @@ const Pay_typesNew = () => {
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<FormField
|
||||
label="WorkersCompPercentage"
|
||||
>
|
||||
<Field
|
||||
type="number"
|
||||
name="workers_comp_percentage"
|
||||
placeholder="WorkersCompPercentage"
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
|
||||
|
||||
@ -393,4 +404,4 @@ Pay_typesNew.getLayout = function getLayout(page: ReactElement) {
|
||||
)
|
||||
}
|
||||
|
||||
export default Pay_typesNew
|
||||
export default Pay_typesNew
|
||||
@ -5,7 +5,7 @@ import LayoutGuest from '../layouts/Guest';
|
||||
import { getPageTitle } from '../config';
|
||||
|
||||
export default function PrivacyPolicy() {
|
||||
const title = 'Pressure Wash Payroll'
|
||||
const title = 'Major League Pressure Washing'
|
||||
const [projectUrl, setProjectUrl] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
267
frontend/src/pages/reports.tsx
Normal file
267
frontend/src/pages/reports.tsx
Normal file
@ -0,0 +1,267 @@
|
||||
import { mdiChartBar, mdiCashCheck, mdiHistory } from '@mdi/js';
|
||||
import Head from 'next/head';
|
||||
import React, { ReactElement, useState } from 'react';
|
||||
import CardBox from '../components/CardBox';
|
||||
import LayoutAuthenticated from '../layouts/Authenticated';
|
||||
import SectionMain from '../components/SectionMain';
|
||||
import SectionTitleLineWithButton from '../components/SectionTitleLineWithButton';
|
||||
import { getPageTitle } from '../config';
|
||||
import FormField from '../components/FormField';
|
||||
import BaseButton from '../components/BaseButton';
|
||||
import BaseButtons from '../components/BaseButtons';
|
||||
import axios from 'axios';
|
||||
|
||||
const ReportsPage = () => {
|
||||
const [activeTab, setActiveTab] = useState('current'); // 'current' or 'historical'
|
||||
|
||||
// Historical state
|
||||
const [reportData, setReportData] = useState(null);
|
||||
const [loadingHistory, setLoadingHistory] = useState(false);
|
||||
const [filtersHistory, setFiltersHistory] = useState({
|
||||
startDate: '',
|
||||
endDate: '',
|
||||
employeeId: ''
|
||||
});
|
||||
|
||||
// Current (Generator) state
|
||||
const [previewData, setPreviewData] = useState(null);
|
||||
const [loadingPreview, setLoadingPreview] = useState(false);
|
||||
const [generating, setGenerating] = useState(false);
|
||||
const [filtersCurrent, setFiltersCurrent] = useState({
|
||||
startDate: '',
|
||||
endDate: ''
|
||||
});
|
||||
const [runSuccess, setRunSuccess] = useState('');
|
||||
const [runError, setRunError] = useState('');
|
||||
|
||||
const fetchHistoricalReport = async () => {
|
||||
setLoadingHistory(true);
|
||||
try {
|
||||
const response = await axios.post('/reports', filtersHistory);
|
||||
setReportData(response.data);
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch historical report:', error);
|
||||
} finally {
|
||||
setLoadingHistory(false);
|
||||
}
|
||||
};
|
||||
|
||||
const fetchCurrentPreview = async () => {
|
||||
setLoadingPreview(true);
|
||||
setRunSuccess('');
|
||||
setRunError('');
|
||||
try {
|
||||
const response = await axios.post('/payroll_generator/preview', filtersCurrent);
|
||||
setPreviewData(response.data);
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch current preview:', error);
|
||||
setRunError(error.response?.data || 'Failed to fetch unpaid logs.');
|
||||
} finally {
|
||||
setLoadingPreview(false);
|
||||
}
|
||||
};
|
||||
|
||||
const generatePayroll = async () => {
|
||||
if (!confirm('Are you sure you want to run payroll? This will finalize these amounts and mark the associated logs as paid.')) return;
|
||||
|
||||
setGenerating(true);
|
||||
setRunError('');
|
||||
setRunSuccess('');
|
||||
try {
|
||||
await axios.post('/payroll_generator/generate', {
|
||||
startDate: filtersCurrent.startDate,
|
||||
endDate: filtersCurrent.endDate,
|
||||
name: `Payroll ${filtersCurrent.startDate} to ${filtersCurrent.endDate}`
|
||||
});
|
||||
setRunSuccess('Payroll Run successfully generated!');
|
||||
setPreviewData(null); // Clear preview since they are now paid
|
||||
} catch (error) {
|
||||
console.error('Failed to generate payroll:', error);
|
||||
setRunError(error.response?.data || 'An error occurred while generating payroll.');
|
||||
} finally {
|
||||
setGenerating(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<title>{getPageTitle('Payroll Reports')}</title>
|
||||
</Head>
|
||||
<SectionMain>
|
||||
<SectionTitleLineWithButton icon={mdiChartBar} title='Payroll Dashboard' main>
|
||||
{''}
|
||||
</SectionTitleLineWithButton>
|
||||
|
||||
<div className="flex mb-6 space-x-4 border-b pb-2">
|
||||
<button
|
||||
onClick={() => setActiveTab('current')}
|
||||
className={`px-4 py-2 font-semibold rounded-t-lg transition-colors flex items-center ${
|
||||
activeTab === 'current' ? 'bg-blue-600 text-white' : 'bg-gray-200 text-gray-700 hover:bg-gray-300'
|
||||
}`}
|
||||
>
|
||||
Current Unpaid Logs
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setActiveTab('historical')}
|
||||
className={`px-4 py-2 font-semibold rounded-t-lg transition-colors flex items-center ${
|
||||
activeTab === 'historical' ? 'bg-blue-600 text-white' : 'bg-gray-200 text-gray-700 hover:bg-gray-300'
|
||||
}`}
|
||||
>
|
||||
Historical Reports
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{activeTab === 'current' && (
|
||||
<div>
|
||||
<CardBox className="mb-6">
|
||||
<div className="mb-4 text-gray-600">
|
||||
Select a date range to view all <strong>unpaid</strong> Job Logs. From here, you can preview what your employees have currently earned and generate a finalized Payroll Run.
|
||||
</div>
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
|
||||
<FormField label="Start Date">
|
||||
<input type="date" value={filtersCurrent.startDate} onChange={e => setFiltersCurrent({...filtersCurrent, startDate: e.target.value})} className="px-3 py-2 border border-gray-300 rounded w-full" />
|
||||
</FormField>
|
||||
<FormField label="End Date">
|
||||
<input type="date" value={filtersCurrent.endDate} onChange={e => setFiltersCurrent({...filtersCurrent, endDate: e.target.value})} className="px-3 py-2 border border-gray-300 rounded w-full" />
|
||||
</FormField>
|
||||
<div className="flex items-end">
|
||||
<BaseButton label="Preview Current Payroll" color="info" onClick={fetchCurrentPreview} disabled={loadingPreview} className="w-full" />
|
||||
</div>
|
||||
</div>
|
||||
{runError && <div className="mt-4 p-3 bg-red-100 text-red-700 rounded">{runError}</div>}
|
||||
{runSuccess && <div className="mt-4 p-3 bg-green-100 text-green-700 rounded">{runSuccess}</div>}
|
||||
</CardBox>
|
||||
|
||||
{previewData && (
|
||||
<>
|
||||
<CardBox className="mb-6">
|
||||
<h2 className="text-xl font-bold mb-4">Live Preview Summary</h2>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="p-4 bg-gray-100 rounded">
|
||||
<p className="text-sm text-gray-500">Total Unpaid Gross Pay</p>
|
||||
<p className="text-2xl font-semibold">${previewData.summary.totalGrossPay.toFixed(2)}</p>
|
||||
</div>
|
||||
<div className="p-4 bg-gray-100 rounded">
|
||||
<p className="text-sm text-gray-500">Total Unpaid Hours</p>
|
||||
<p className="text-2xl font-semibold">{previewData.summary.totalHours.toFixed(2)}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-6">
|
||||
<BaseButton label="Run & Finalize Payroll" color="success" onClick={generatePayroll} disabled={generating} />
|
||||
</div>
|
||||
</CardBox>
|
||||
|
||||
<CardBox>
|
||||
<h2 className="text-xl font-bold mb-4">Employee Breakdown</h2>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-left">
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="p-2 border-b">Employee</th>
|
||||
<th className="p-2 border-b">Total Hours</th>
|
||||
<th className="p-2 border-b">Commission Base</th>
|
||||
<th className="p-2 border-b">Calculated Gross Pay</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{previewData.lineItems.map((item: any, idx: number) => (
|
||||
<tr key={idx}>
|
||||
<td className="p-2 border-b">{item.employee?.firstName} {item.employee?.lastName || ''}</td>
|
||||
<td className="p-2 border-b">{item.total_hours.toFixed(2)}</td>
|
||||
<td className="p-2 border-b">${item.total_commission_base.toFixed(2)}</td>
|
||||
<td className="p-2 border-b font-semibold text-green-600">${item.gross_pay.toFixed(2)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</CardBox>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{activeTab === 'historical' && (
|
||||
<div>
|
||||
<CardBox className="mb-6">
|
||||
<div className="mb-4 text-gray-600">
|
||||
View previously generated payroll line items by date range or employee ID.
|
||||
</div>
|
||||
<div className="grid grid-cols-1 md:grid-cols-4 gap-6">
|
||||
<FormField label="Start Date">
|
||||
<input type="date" value={filtersHistory.startDate} onChange={e => setFiltersHistory({...filtersHistory, startDate: e.target.value})} className="px-3 py-2 border border-gray-300 rounded w-full" />
|
||||
</FormField>
|
||||
<FormField label="End Date">
|
||||
<input type="date" value={filtersHistory.endDate} onChange={e => setFiltersHistory({...filtersHistory, endDate: e.target.value})} className="px-3 py-2 border border-gray-300 rounded w-full" />
|
||||
</FormField>
|
||||
<FormField label="Employee ID">
|
||||
<input type="text" value={filtersHistory.employeeId} onChange={e => setFiltersHistory({...filtersHistory, employeeId: e.target.value})} className="px-3 py-2 border border-gray-300 rounded w-full" />
|
||||
</FormField>
|
||||
<div className="flex items-end">
|
||||
<BaseButton label="View Historical Report" color="info" onClick={fetchHistoricalReport} disabled={loadingHistory} className="w-full" />
|
||||
</div>
|
||||
</div>
|
||||
</CardBox>
|
||||
|
||||
{reportData && (
|
||||
<>
|
||||
<CardBox className="mb-6">
|
||||
<h2 className="text-xl font-bold mb-4">Historical Summary</h2>
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
<div className="p-4 bg-gray-100 rounded">
|
||||
<p className="text-sm text-gray-500">Total Gross Pay</p>
|
||||
<p className="text-2xl font-semibold">${reportData.summary.totalGrossPay.toFixed(2)}</p>
|
||||
</div>
|
||||
<div className="p-4 bg-gray-100 rounded">
|
||||
<p className="text-sm text-gray-500">Total Hours</p>
|
||||
<p className="text-2xl font-semibold">{reportData.summary.totalHours.toFixed(2)}</p>
|
||||
</div>
|
||||
<div className="p-4 bg-gray-100 rounded">
|
||||
<p className="text-sm text-gray-500">Total Work Comp</p>
|
||||
<p className="text-2xl font-semibold">${reportData.summary.totalWorkersComp.toFixed(2)}</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardBox>
|
||||
<CardBox>
|
||||
<h2 className="text-xl font-bold mb-4">Line Items</h2>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-left">
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="p-2 border-b">Employee</th>
|
||||
<th className="p-2 border-b">Hours</th>
|
||||
<th className="p-2 border-b">Gross Pay</th>
|
||||
<th className="p-2 border-b">Work Comp Amount</th>
|
||||
<th className="p-2 border-b">Created At</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{reportData.lineItems.map((item: any) => (
|
||||
<tr key={item.id}>
|
||||
<td className="p-2 border-b">{item.employee?.firstName} {item.employee?.lastName || ''}</td>
|
||||
<td className="p-2 border-b">{item.total_hours}</td>
|
||||
<td className="p-2 border-b">${item.gross_pay}</td>
|
||||
<td className="p-2 border-b">${item.workers_comp_amount}</td>
|
||||
<td className="p-2 border-b">{new Date(item.createdAt).toLocaleDateString()}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</CardBox>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
</SectionMain>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
ReportsPage.getLayout = function getLayout(page: ReactElement) {
|
||||
return <LayoutAuthenticated>{page}</LayoutAuthenticated>;
|
||||
};
|
||||
|
||||
export default ReportsPage;
|
||||
@ -5,7 +5,7 @@ import LayoutGuest from '../layouts/Guest';
|
||||
import { getPageTitle } from '../config';
|
||||
|
||||
export default function PrivacyPolicy() {
|
||||
const title = 'Pressure Wash Payroll';
|
||||
const title = 'Major League Pressure Washing';
|
||||
const [projectUrl, setProjectUrl] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
@ -0,0 +1,509 @@
|
||||
import { mdiChartTimelineVariant, mdiUpload } from '@mdi/js'
|
||||
import Head from 'next/head'
|
||||
import React, { ReactElement, useEffect, useState } from 'react'
|
||||
import DatePicker from "react-datepicker";
|
||||
import "react-datepicker/dist/react-datepicker.css";
|
||||
import dayjs from "dayjs";
|
||||
|
||||
import CardBox from '../../components/CardBox'
|
||||
import LayoutAuthenticated from '../../layouts/Authenticated'
|
||||
import SectionMain from '../../components/SectionMain'
|
||||
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton'
|
||||
import { getPageTitle } from '../../config'
|
||||
|
||||
import { Field, Form, Formik } from 'formik'
|
||||
import FormField from '../../components/FormField'
|
||||
import BaseDivider from '../../components/BaseDivider'
|
||||
import BaseButtons from '../../components/BaseButtons'
|
||||
import BaseButton from '../../components/BaseButton'
|
||||
import FormCheckRadio from '../../components/FormCheckRadio'
|
||||
import FormCheckRadioGroup from '../../components/FormCheckRadioGroup'
|
||||
import FormFilePicker from '../../components/FormFilePicker'
|
||||
import FormImagePicker from '../../components/FormImagePicker'
|
||||
import { SelectField } from "../../components/SelectField";
|
||||
import { SelectFieldMany } from "../../components/SelectFieldMany";
|
||||
import { SwitchField } from '../../components/SwitchField'
|
||||
import {RichTextField} from "../../components/RichTextField";
|
||||
|
||||
import { update, fetch } from '../../stores/workers_comp_classes/workers_comp_classesSlice'
|
||||
import { useAppDispatch, useAppSelector } from '../../stores/hooks'
|
||||
import { useRouter } from 'next/router'
|
||||
import {saveFile} from "../../helpers/fileSaver";
|
||||
import dataFormatter from '../../helpers/dataFormatter';
|
||||
import ImageField from "../../components/ImageField";
|
||||
|
||||
|
||||
|
||||
const EditWorkers_comp_classes = () => {
|
||||
const router = useRouter()
|
||||
const dispatch = useAppDispatch()
|
||||
const initVals = {
|
||||
|
||||
|
||||
'name': '',
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
pay_method: '',
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
'hourly_rate': '',
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
'commission_rate': '',
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
active: false,
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
description: '',
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
const [initialValues, setInitialValues] = useState(initVals)
|
||||
|
||||
const { workers_comp_classes } = useAppSelector((state) => state.workers_comp_classes)
|
||||
|
||||
|
||||
const { workers_comp_classesId } = router.query
|
||||
|
||||
useEffect(() => {
|
||||
dispatch(fetch({ id: workers_comp_classesId }))
|
||||
}, [workers_comp_classesId])
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof workers_comp_classes === 'object') {
|
||||
setInitialValues(workers_comp_classes)
|
||||
}
|
||||
}, [workers_comp_classes])
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof workers_comp_classes === 'object') {
|
||||
|
||||
const newInitialVal = {...initVals};
|
||||
|
||||
Object.keys(initVals).forEach(el => newInitialVal[el] = (workers_comp_classes)[el])
|
||||
|
||||
setInitialValues(newInitialVal);
|
||||
}
|
||||
}, [workers_comp_classes])
|
||||
|
||||
const handleSubmit = async (data) => {
|
||||
await dispatch(update({ id: workers_comp_classesId, data }))
|
||||
await router.push('/workers_comp_classes/workers_comp_classes-list')
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<title>{getPageTitle('Edit workers_comp_classes')}</title>
|
||||
</Head>
|
||||
<SectionMain>
|
||||
<SectionTitleLineWithButton icon={mdiChartTimelineVariant} title={'Edit workers_comp_classes'} main>
|
||||
{''}
|
||||
</SectionTitleLineWithButton>
|
||||
<CardBox>
|
||||
<Formik
|
||||
enableReinitialize
|
||||
initialValues={initialValues}
|
||||
onSubmit={(values) => handleSubmit(values)}
|
||||
>
|
||||
<Form>
|
||||
|
||||
|
||||
|
||||
<FormField
|
||||
label="WorkersCompClassName"
|
||||
>
|
||||
<Field
|
||||
name="name"
|
||||
placeholder="WorkersCompClassName"
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<FormField label="PayMethod" labelFor="pay_method">
|
||||
<Field name="pay_method" id="pay_method" component="select">
|
||||
|
||||
<option value="hourly">hourly</option>
|
||||
|
||||
<option value="commission">commission</option>
|
||||
|
||||
</Field>
|
||||
</FormField>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<FormField
|
||||
label="HourlyRate"
|
||||
>
|
||||
<Field
|
||||
type="number"
|
||||
name="hourly_rate"
|
||||
placeholder="HourlyRate"
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<FormField
|
||||
label="CommissionRate"
|
||||
>
|
||||
<Field
|
||||
type="number"
|
||||
name="commission_rate"
|
||||
placeholder="CommissionRate"
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<FormField label='Active' labelFor='active'>
|
||||
<Field
|
||||
name='active'
|
||||
id='active'
|
||||
component={SwitchField}
|
||||
></Field>
|
||||
</FormField>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<FormField label="Description" hasTextareaHeight>
|
||||
<Field name="description" as="textarea" placeholder="Description" />
|
||||
</FormField>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<BaseDivider />
|
||||
<BaseButtons>
|
||||
<BaseButton type="submit" color="info" label="Submit" />
|
||||
<BaseButton type="reset" color="info" outline label="Reset" />
|
||||
<BaseButton type='reset' color='danger' outline label='Cancel' onClick={() => router.push('/workers_comp_classes/workers_comp_classes-list')}/>
|
||||
</BaseButtons>
|
||||
</Form>
|
||||
</Formik>
|
||||
</CardBox>
|
||||
</SectionMain>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
EditWorkers_comp_classes.getLayout = function getLayout(page: ReactElement) {
|
||||
return (
|
||||
<LayoutAuthenticated
|
||||
|
||||
permission={'UPDATE_PAY_TYPES'}
|
||||
|
||||
>
|
||||
{page}
|
||||
</LayoutAuthenticated>
|
||||
)
|
||||
}
|
||||
|
||||
export default EditWorkers_comp_classes
|
||||
@ -0,0 +1,101 @@
|
||||
import { mdiChartTimelineVariant } from '@mdi/js'
|
||||
import Head from 'next/head'
|
||||
import React, { ReactElement, useEffect, useState } from 'react'
|
||||
|
||||
import CardBox from '../../components/CardBox'
|
||||
import LayoutAuthenticated from '../../layouts/Authenticated'
|
||||
import SectionMain from '../../components/SectionMain'
|
||||
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton'
|
||||
import { getPageTitle } from '../../config'
|
||||
|
||||
import { Field, Form, Formik } from 'formik'
|
||||
import FormField from '../../components/FormField'
|
||||
import BaseDivider from '../../components/BaseDivider'
|
||||
import BaseButtons from '../../components/BaseButtons'
|
||||
import BaseButton from '../../components/BaseButton'
|
||||
|
||||
import { update, fetch } from '../../stores/workers_comp_classes/workers_comp_classesSlice'
|
||||
import { useAppDispatch, useAppSelector } from '../../stores/hooks'
|
||||
import { useRouter } from 'next/router'
|
||||
|
||||
const EditWorkers_comp_classesPage = () => {
|
||||
const router = useRouter()
|
||||
const dispatch = useAppDispatch()
|
||||
|
||||
const initVals = {
|
||||
name: '',
|
||||
percentage: '',
|
||||
}
|
||||
|
||||
const [initialValues, setInitialValues] = useState(initVals)
|
||||
|
||||
const { workers_comp_classes } = useAppSelector((state) => state.workers_comp_classes)
|
||||
const { id } = router.query
|
||||
|
||||
useEffect(() => {
|
||||
if (id) {
|
||||
dispatch(fetch({ id: id as string }))
|
||||
}
|
||||
}, [id, dispatch])
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof workers_comp_classes === 'object' && workers_comp_classes !== null) {
|
||||
const newInitialVal = { ...initVals };
|
||||
Object.keys(initVals).forEach(el => {
|
||||
if (workers_comp_classes[el] !== undefined) {
|
||||
newInitialVal[el] = workers_comp_classes[el];
|
||||
}
|
||||
});
|
||||
setInitialValues(newInitialVal);
|
||||
}
|
||||
}, [workers_comp_classes])
|
||||
|
||||
const handleSubmit = async (data: any) => {
|
||||
await dispatch(update({ id: id, data }))
|
||||
await router.push('/workers_comp_classes/workers_comp_classes-list')
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<title>{getPageTitle('Edit Workers Comp Class')}</title>
|
||||
</Head>
|
||||
<SectionMain>
|
||||
<SectionTitleLineWithButton icon={mdiChartTimelineVariant} title={'Edit Workers Comp Class'} main>
|
||||
{''}
|
||||
</SectionTitleLineWithButton>
|
||||
<CardBox>
|
||||
<Formik
|
||||
enableReinitialize
|
||||
initialValues={initialValues}
|
||||
onSubmit={(values) => handleSubmit(values)}
|
||||
>
|
||||
<Form>
|
||||
<FormField label="Name" labelFor="name">
|
||||
<Field name="name" id="name" type="text" />
|
||||
</FormField>
|
||||
<FormField label="Percentage" labelFor="percentage">
|
||||
<Field name="percentage" id="percentage" type="number" step="0.01" />
|
||||
</FormField>
|
||||
<BaseDivider />
|
||||
<BaseButtons>
|
||||
<BaseButton type="submit" color="info" label="Submit" />
|
||||
<BaseButton type="reset" color="info" outline label="Reset" />
|
||||
</BaseButtons>
|
||||
</Form>
|
||||
</Formik>
|
||||
</CardBox>
|
||||
</SectionMain>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
EditWorkers_comp_classesPage.getLayout = function getLayout(page: ReactElement) {
|
||||
return (
|
||||
<LayoutAuthenticated permission={'UPDATE_WORKERS_COMP_CLASSES'}>
|
||||
{page}
|
||||
</LayoutAuthenticated>
|
||||
)
|
||||
}
|
||||
|
||||
export default EditWorkers_comp_classesPage
|
||||
@ -0,0 +1,120 @@
|
||||
import { mdiChartTimelineVariant, mdiPlus } from '@mdi/js'
|
||||
import Head from 'next/head'
|
||||
import { uniqueId } from 'lodash'
|
||||
import React, { ReactElement, useEffect, useState } from 'react'
|
||||
import CardBox from '../../components/CardBox'
|
||||
import LayoutAuthenticated from '../../layouts/Authenticated'
|
||||
import SectionMain from '../../components/SectionMain'
|
||||
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton'
|
||||
import { getPageTitle } from '../../config'
|
||||
import TableWorkers_comp_classes from '../../components/Workers_comp_classes/TableWorkers_comp_classes'
|
||||
import BaseButton from '../../components/BaseButton'
|
||||
import axios from 'axios'
|
||||
import Link from 'next/link'
|
||||
import { useAppDispatch, useAppSelector } from '../../stores/hooks'
|
||||
import CardBoxModal from '../../components/CardBoxModal'
|
||||
import DragDropFilePicker from '../../components/DragDropFilePicker'
|
||||
import { setRefetch, uploadCsv } from '../../stores/workers_comp_classes/workers_comp_classesSlice'
|
||||
import { hasPermission } from '../../helpers/userPermissions'
|
||||
|
||||
const Workers_comp_classesList = () => {
|
||||
const [filterItems, setFilterItems] = useState<any[]>([]);
|
||||
const [filters] = useState([
|
||||
{label: 'Name', title: 'name'},
|
||||
{label: 'Percentage', title: 'percentage', number: 'true'},
|
||||
]);
|
||||
|
||||
const dispatch = useAppDispatch();
|
||||
const { currentUser } = useAppSelector((state) => state.auth);
|
||||
const [reportData, setReportData] = useState<any>(null);
|
||||
|
||||
const addFilter = () => {
|
||||
const newItem = {
|
||||
id: uniqueId(),
|
||||
fields: {
|
||||
filterValue: '',
|
||||
filterValueFrom: '',
|
||||
filterValueTo: '',
|
||||
selectedField: filters[0].title,
|
||||
},
|
||||
};
|
||||
setFilterItems([...filterItems, newItem]);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const fetchReport = async () => {
|
||||
try {
|
||||
const res = await axios.get('/workers_comp_report/report');
|
||||
setReportData(res.data);
|
||||
} catch (e) {
|
||||
console.error("Failed to fetch report", e);
|
||||
}
|
||||
};
|
||||
fetchReport();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<title>{getPageTitle('Workers Comp Classes')}</title>
|
||||
</Head>
|
||||
<SectionMain>
|
||||
<SectionTitleLineWithButton
|
||||
icon={mdiChartTimelineVariant}
|
||||
title={'Workers Comp Classes'}
|
||||
main
|
||||
>
|
||||
{hasPermission(currentUser, 'CREATE_WORKERS_COMP_CLASSES') && (
|
||||
<div className="flex items-center gap-2">
|
||||
<BaseButton
|
||||
color='info'
|
||||
label='Filter'
|
||||
onClick={addFilter}
|
||||
/>
|
||||
<Link href={'/workers_comp_classes/workers_comp_classes-new'}>
|
||||
<BaseButton
|
||||
color="info"
|
||||
icon={mdiPlus}
|
||||
label="New Workers Comp Class"
|
||||
/>
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
</SectionTitleLineWithButton>
|
||||
|
||||
{reportData && (
|
||||
<CardBox className="mb-6">
|
||||
<h3 className="text-xl font-semibold mb-4">Workman's Comp Totals (All Time)</h3>
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
|
||||
<div className="p-4 bg-blue-50 rounded shadow">
|
||||
<p className="text-sm text-blue-600 font-bold">Total Work Comp</p>
|
||||
<p className="text-2xl font-semibold">${reportData.totalComp.toFixed(2)}</p>
|
||||
</div>
|
||||
{Object.entries(reportData.totalsByClass).map(([className, total]: any) => (
|
||||
<div key={className} className="p-4 bg-gray-50 rounded shadow">
|
||||
<p className="text-sm text-gray-500 font-bold">{className}</p>
|
||||
<p className="text-xl font-semibold">${Number(total).toFixed(2)}</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardBox>
|
||||
)}
|
||||
|
||||
<CardBox className="mb-6" hasTable>
|
||||
<TableWorkers_comp_classes
|
||||
filterItems={filterItems}
|
||||
setFilterItems={setFilterItems}
|
||||
filters={filters}
|
||||
showGrid={false}
|
||||
/>
|
||||
</CardBox>
|
||||
</SectionMain>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
Workers_comp_classesList.getLayout = function getLayout(page: ReactElement) {
|
||||
return <LayoutAuthenticated>{page}</LayoutAuthenticated>
|
||||
}
|
||||
|
||||
export default Workers_comp_classesList
|
||||
@ -0,0 +1,76 @@
|
||||
import { mdiChartTimelineVariant } from '@mdi/js'
|
||||
import Head from 'next/head'
|
||||
import React, { ReactElement } from 'react'
|
||||
import CardBox from '../../components/CardBox'
|
||||
import LayoutAuthenticated from '../../layouts/Authenticated'
|
||||
import SectionMain from '../../components/SectionMain'
|
||||
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton'
|
||||
import { getPageTitle } from '../../config'
|
||||
|
||||
import { Field, Form, Formik } from 'formik'
|
||||
import FormField from '../../components/FormField'
|
||||
import BaseDivider from '../../components/BaseDivider'
|
||||
import BaseButtons from '../../components/BaseButtons'
|
||||
import BaseButton from '../../components/BaseButton'
|
||||
|
||||
import { create } from '../../stores/workers_comp_classes/workers_comp_classesSlice'
|
||||
import { useAppDispatch } from '../../stores/hooks'
|
||||
import { useRouter } from 'next/router'
|
||||
|
||||
const initialValues = {
|
||||
name: '',
|
||||
percentage: '',
|
||||
}
|
||||
|
||||
const Workers_comp_classesNew = () => {
|
||||
const router = useRouter()
|
||||
const dispatch = useAppDispatch()
|
||||
|
||||
const handleSubmit = async (data: any) => {
|
||||
await dispatch(create(data))
|
||||
await router.push('/workers_comp_classes/workers_comp_classes-list')
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<title>{getPageTitle('New Workers Comp Class')}</title>
|
||||
</Head>
|
||||
<SectionMain>
|
||||
<SectionTitleLineWithButton icon={mdiChartTimelineVariant} title="New Workers Comp Class" main>
|
||||
{''}
|
||||
</SectionTitleLineWithButton>
|
||||
<CardBox>
|
||||
<Formik
|
||||
initialValues={initialValues}
|
||||
onSubmit={(values) => handleSubmit(values)}
|
||||
>
|
||||
<Form>
|
||||
<FormField label="Name" labelFor="name">
|
||||
<Field name="name" id="name" type="text" />
|
||||
</FormField>
|
||||
<FormField label="Percentage" labelFor="percentage">
|
||||
<Field name="percentage" id="percentage" type="number" step="0.01" />
|
||||
</FormField>
|
||||
<BaseDivider />
|
||||
<BaseButtons>
|
||||
<BaseButton type="submit" color="info" label="Submit" />
|
||||
<BaseButton type="reset" color="info" outline label="Reset" />
|
||||
</BaseButtons>
|
||||
</Form>
|
||||
</Formik>
|
||||
</CardBox>
|
||||
</SectionMain>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
Workers_comp_classesNew.getLayout = function getLayout(page: ReactElement) {
|
||||
return (
|
||||
<LayoutAuthenticated permission={'CREATE_WORKERS_COMP_CLASSES'}>
|
||||
{page}
|
||||
</LayoutAuthenticated>
|
||||
)
|
||||
}
|
||||
|
||||
export default Workers_comp_classesNew
|
||||
@ -0,0 +1,164 @@
|
||||
import { mdiChartTimelineVariant } from '@mdi/js'
|
||||
import Head from 'next/head'
|
||||
import { uniqueId } from 'lodash';
|
||||
import React, { ReactElement, useState } from 'react'
|
||||
import CardBox from '../../components/CardBox'
|
||||
import LayoutAuthenticated from '../../layouts/Authenticated'
|
||||
import SectionMain from '../../components/SectionMain'
|
||||
import SectionTitleLineWithButton from '../../components/SectionTitleLineWithButton'
|
||||
import { getPageTitle } from '../../config'
|
||||
import TableWorkers_comp_classes from '../../components/Workers_comp_classes/TableWorkers_comp_classes'
|
||||
import BaseButton from '../../components/BaseButton'
|
||||
import axios from "axios";
|
||||
import Link from "next/link";
|
||||
import {useAppDispatch, useAppSelector} from "../../stores/hooks";
|
||||
import CardBoxModal from "../../components/CardBoxModal";
|
||||
import DragDropFilePicker from "../../components/DragDropFilePicker";
|
||||
import {setRefetch, uploadCsv} from '../../stores/workers_comp_classes/workers_comp_classesSlice';
|
||||
|
||||
|
||||
import {hasPermission} from "../../helpers/userPermissions";
|
||||
|
||||
|
||||
|
||||
const Workers_comp_classesTablesPage = () => {
|
||||
const [filterItems, setFilterItems] = useState([]);
|
||||
const [csvFile, setCsvFile] = useState<File | null>(null);
|
||||
const [isModalActive, setIsModalActive] = useState(false);
|
||||
const [showTableView, setShowTableView] = useState(false);
|
||||
|
||||
|
||||
const { currentUser } = useAppSelector((state) => state.auth);
|
||||
|
||||
|
||||
const dispatch = useAppDispatch();
|
||||
|
||||
|
||||
const [filters] = useState([{label: 'WorkersCompClassName', title: 'name'},{label: 'Description', title: 'description'},
|
||||
|
||||
{label: 'HourlyRate', title: 'hourly_rate', number: 'true'},{label: 'CommissionRate', title: 'commission_rate', number: 'true'},
|
||||
|
||||
|
||||
|
||||
{label: 'PayMethod', title: 'pay_method', type: 'enum', options: ['hourly','commission']},
|
||||
]);
|
||||
|
||||
const hasCreatePermission = currentUser && hasPermission(currentUser, 'CREATE_PAY_TYPES');
|
||||
|
||||
|
||||
const addFilter = () => {
|
||||
const newItem = {
|
||||
id: uniqueId(),
|
||||
fields: {
|
||||
filterValue: '',
|
||||
filterValueFrom: '',
|
||||
filterValueTo: '',
|
||||
selectedField: '',
|
||||
},
|
||||
};
|
||||
newItem.fields.selectedField = filters[0].title;
|
||||
setFilterItems([...filterItems, newItem]);
|
||||
};
|
||||
|
||||
const getWorkers_comp_classesCSV = async () => {
|
||||
const response = await axios({url: '/workers_comp_classes?filetype=csv', method: 'GET',responseType: 'blob'});
|
||||
const type = response.headers['content-type']
|
||||
const blob = new Blob([response.data], { type: type })
|
||||
const link = document.createElement('a')
|
||||
link.href = window.URL.createObjectURL(blob)
|
||||
link.download = 'workers_comp_classesCSV.csv'
|
||||
link.click()
|
||||
};
|
||||
|
||||
const onModalConfirm = async () => {
|
||||
if (!csvFile) return;
|
||||
await dispatch(uploadCsv(csvFile));
|
||||
dispatch(setRefetch(true));
|
||||
setCsvFile(null);
|
||||
setIsModalActive(false);
|
||||
};
|
||||
|
||||
const onModalCancel = () => {
|
||||
setCsvFile(null);
|
||||
setIsModalActive(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<title>{getPageTitle('Workers_comp_classes')}</title>
|
||||
</Head>
|
||||
<SectionMain>
|
||||
<SectionTitleLineWithButton icon={mdiChartTimelineVariant} title="Workers_comp_classes" main>
|
||||
{''}
|
||||
</SectionTitleLineWithButton>
|
||||
<CardBox className='mb-6' cardBoxClassName='flex flex-wrap'>
|
||||
|
||||
{hasCreatePermission && <BaseButton className={'mr-3'} href={'/workers_comp_classes/workers_comp_classes-new'} color='info' label='New Item'/>}
|
||||
|
||||
<BaseButton
|
||||
className={'mr-3'}
|
||||
color='info'
|
||||
label='Filter'
|
||||
onClick={addFilter}
|
||||
/>
|
||||
<BaseButton className={'mr-3'} color='info' label='Download CSV' onClick={getWorkers_comp_classesCSV} />
|
||||
|
||||
{hasCreatePermission && (
|
||||
<BaseButton
|
||||
color='info'
|
||||
label='Upload CSV'
|
||||
onClick={() => setIsModalActive(true)}
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className='md:inline-flex items-center ms-auto'>
|
||||
<div id='delete-rows-button'></div>
|
||||
|
||||
<Link href={'/workers_comp_classes/workers_comp_classes-list'}>
|
||||
Back to <span className='capitalize'>table</span>
|
||||
</Link>
|
||||
|
||||
</div>
|
||||
</CardBox>
|
||||
<CardBox className="mb-6" hasTable>
|
||||
<TableWorkers_comp_classes
|
||||
filterItems={filterItems}
|
||||
setFilterItems={setFilterItems}
|
||||
filters={filters}
|
||||
showGrid={true}
|
||||
/>
|
||||
</CardBox>
|
||||
</SectionMain>
|
||||
<CardBoxModal
|
||||
title='Upload CSV'
|
||||
buttonColor='info'
|
||||
buttonLabel={'Confirm'}
|
||||
// buttonLabel={false ? 'Deleting...' : 'Confirm'}
|
||||
isActive={isModalActive}
|
||||
onConfirm={onModalConfirm}
|
||||
onCancel={onModalCancel}
|
||||
>
|
||||
<DragDropFilePicker
|
||||
file={csvFile}
|
||||
setFile={setCsvFile}
|
||||
formats={'.csv'}
|
||||
/>
|
||||
</CardBoxModal>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
Workers_comp_classesTablesPage.getLayout = function getLayout(page: ReactElement) {
|
||||
return (
|
||||
<LayoutAuthenticated
|
||||
|
||||
permission={'READ_PAY_TYPES'}
|
||||
|
||||
>
|
||||
{page}
|
||||
</LayoutAuthenticated>
|
||||
)
|
||||
}
|
||||
|
||||
export default Workers_comp_classesTablesPage
|
||||
@ -0,0 +1,489 @@
|
||||
import React, { ReactElement, useEffect } from 'react';
|
||||
import Head from 'next/head'
|
||||
import DatePicker from "react-datepicker";
|
||||
import "react-datepicker/dist/react-datepicker.css";
|
||||
import dayjs from "dayjs";
|
||||
import {useAppDispatch, useAppSelector} from "../../stores/hooks";
|
||||
import {useRouter} from "next/router";
|
||||
import { fetch } from '../../stores/workers_comp_classes/workers_comp_classesSlice'
|
||||
import {saveFile} from "../../helpers/fileSaver";
|
||||
import dataFormatter from '../../helpers/dataFormatter';
|
||||
import ImageField from "../../components/ImageField";
|
||||
import LayoutAuthenticated from "../../layouts/Authenticated";
|
||||
import {getPageTitle} from "../../config";
|
||||
import SectionTitleLineWithButton from "../../components/SectionTitleLineWithButton";
|
||||
import SectionMain from "../../components/SectionMain";
|
||||
import CardBox from "../../components/CardBox";
|
||||
import BaseButton from "../../components/BaseButton";
|
||||
import BaseDivider from "../../components/BaseDivider";
|
||||
import {mdiChartTimelineVariant} from "@mdi/js";
|
||||
import {SwitchField} from "../../components/SwitchField";
|
||||
import FormField from "../../components/FormField";
|
||||
|
||||
|
||||
const Workers_comp_classesView = () => {
|
||||
const router = useRouter()
|
||||
const dispatch = useAppDispatch()
|
||||
const { workers_comp_classes } = useAppSelector((state) => state.workers_comp_classes)
|
||||
|
||||
|
||||
const { id } = router.query;
|
||||
|
||||
function removeLastCharacter(str) {
|
||||
console.log(str,`str`)
|
||||
return str.slice(0, -1);
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
dispatch(fetch({ id }));
|
||||
}, [dispatch, id]);
|
||||
|
||||
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<title>{getPageTitle('View workers_comp_classes')}</title>
|
||||
</Head>
|
||||
<SectionMain>
|
||||
<SectionTitleLineWithButton icon={mdiChartTimelineVariant} title={removeLastCharacter('View workers_comp_classes')} main>
|
||||
<BaseButton
|
||||
color='info'
|
||||
label='Edit'
|
||||
href={`/workers_comp_classes/workers_comp_classes-edit/?id=${id}`}
|
||||
/>
|
||||
</SectionTitleLineWithButton>
|
||||
<CardBox>
|
||||
|
||||
|
||||
|
||||
<div className={'mb-4'}>
|
||||
<p className={'block font-bold mb-2'}>WorkersCompClassName</p>
|
||||
<p>{workers_comp_classes?.name}</p>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<div className={'mb-4'}>
|
||||
<p className={'block font-bold mb-2'}>PayMethod</p>
|
||||
<p>{workers_comp_classes?.pay_method ?? 'No data'}</p>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<div className={'mb-4'}>
|
||||
<p className={'block font-bold mb-2'}>HourlyRate</p>
|
||||
<p>{workers_comp_classes?.hourly_rate || 'No data'}</p>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<div className={'mb-4'}>
|
||||
<p className={'block font-bold mb-2'}>CommissionRate</p>
|
||||
<p>{workers_comp_classes?.commission_rate || 'No data'}</p>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<FormField label='Active'>
|
||||
<SwitchField
|
||||
field={{name: 'active', value: workers_comp_classes?.active}}
|
||||
form={{setFieldValue: () => null}}
|
||||
disabled
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<FormField label='Multi Text' hasTextareaHeight>
|
||||
<textarea className={'w-full'} disabled value={workers_comp_classes?.description} />
|
||||
</FormField>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<>
|
||||
<p className={'block font-bold mb-2'}>Employee_workers_comp_classes WorkersCompClass</p>
|
||||
<CardBox
|
||||
className='mb-6 border border-gray-300 rounded overflow-hidden'
|
||||
hasTable
|
||||
>
|
||||
<div className='overflow-x-auto'>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<th>Active</th>
|
||||
|
||||
|
||||
|
||||
<th>EffectiveStart</th>
|
||||
|
||||
|
||||
|
||||
<th>EffectiveEnd</th>
|
||||
|
||||
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{workers_comp_classes.employee_workers_comp_classes_workers_comp_class && Array.isArray(workers_comp_classes.employee_workers_comp_classes_workers_comp_class) &&
|
||||
workers_comp_classes.employee_workers_comp_classes_workers_comp_class.map((item: any) => (
|
||||
<tr key={item.id} onClick={() => router.push(`/employee_workers_comp_classes/employee_workers_comp_classes-view/?id=${item.id}`)}>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<td data-label="active">
|
||||
{ dataFormatter.booleanFormatter(item.active) }
|
||||
</td>
|
||||
|
||||
|
||||
|
||||
<td data-label="effective_start">
|
||||
{ dataFormatter.dateTimeFormatter(item.effective_start) }
|
||||
</td>
|
||||
|
||||
|
||||
|
||||
<td data-label="effective_end">
|
||||
{ dataFormatter.dateTimeFormatter(item.effective_end) }
|
||||
</td>
|
||||
|
||||
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{!workers_comp_classes?.employee_workers_comp_classes_workers_comp_class?.length && <div className={'text-center py-4'}>No data</div>}
|
||||
</CardBox>
|
||||
</>
|
||||
|
||||
|
||||
|
||||
<>
|
||||
<p className={'block font-bold mb-2'}>Job_logs WorkersCompClass</p>
|
||||
<CardBox
|
||||
className='mb-6 border border-gray-300 rounded overflow-hidden'
|
||||
hasTable
|
||||
>
|
||||
<div className='overflow-x-auto'>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
|
||||
|
||||
<th>WorkDate</th>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<th>HoursConducted</th>
|
||||
|
||||
|
||||
|
||||
<th>ClientPaid</th>
|
||||
|
||||
|
||||
|
||||
<th>WorkmansCompensationClass</th>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<th>OdometerStart</th>
|
||||
|
||||
|
||||
|
||||
<th>OdometerEnd</th>
|
||||
|
||||
|
||||
|
||||
<th>JobAddress</th>
|
||||
|
||||
|
||||
|
||||
<th>Status</th>
|
||||
|
||||
|
||||
|
||||
<th>NotesToAdmin</th>
|
||||
|
||||
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{workers_comp_classes.job_logs_workers_comp_class && Array.isArray(workers_comp_classes.job_logs_workers_comp_class) &&
|
||||
workers_comp_classes.job_logs_workers_comp_class.map((item: any) => (
|
||||
<tr key={item.id} onClick={() => router.push(`/job_logs/job_logs-view/?id=${item.id}`)}>
|
||||
|
||||
|
||||
<td data-label="work_date">
|
||||
{ dataFormatter.dateTimeFormatter(item.work_date) }
|
||||
</td>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<td data-label="hours_conducted">
|
||||
{ item.hours_conducted }
|
||||
</td>
|
||||
|
||||
|
||||
|
||||
<td data-label="client_paid">
|
||||
{ item.client_paid }
|
||||
</td>
|
||||
|
||||
|
||||
|
||||
<td data-label="workers_comp_class">
|
||||
{ item.workers_comp_class }
|
||||
</td>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<td data-label="odometer_start">
|
||||
{ item.odometer_start }
|
||||
</td>
|
||||
|
||||
|
||||
|
||||
<td data-label="odometer_end">
|
||||
{ item.odometer_end }
|
||||
</td>
|
||||
|
||||
|
||||
|
||||
<td data-label="job_address">
|
||||
{ item.job_address }
|
||||
</td>
|
||||
|
||||
|
||||
|
||||
<td data-label="status">
|
||||
{ item.status }
|
||||
</td>
|
||||
|
||||
|
||||
|
||||
<td data-label="notes_to_admin">
|
||||
{ item.notes_to_admin }
|
||||
</td>
|
||||
|
||||
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{!workers_comp_classes?.job_logs_workers_comp_class?.length && <div className={'text-center py-4'}>No data</div>}
|
||||
</CardBox>
|
||||
</>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<BaseDivider />
|
||||
|
||||
<BaseButton
|
||||
color='info'
|
||||
label='Back'
|
||||
onClick={() => router.push('/workers_comp_classes/workers_comp_classes-list')}
|
||||
/>
|
||||
</CardBox>
|
||||
</SectionMain>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
Workers_comp_classesView.getLayout = function getLayout(page: ReactElement) {
|
||||
return (
|
||||
<LayoutAuthenticated
|
||||
|
||||
permission={'READ_PAY_TYPES'}
|
||||
|
||||
>
|
||||
{page}
|
||||
</LayoutAuthenticated>
|
||||
)
|
||||
}
|
||||
|
||||
export default Workers_comp_classesView;
|
||||
@ -16,6 +16,7 @@ import job_logsSlice from "./job_logs/job_logsSlice";
|
||||
import job_chemical_usagesSlice from "./job_chemical_usages/job_chemical_usagesSlice";
|
||||
import payroll_runsSlice from "./payroll_runs/payroll_runsSlice";
|
||||
import payroll_line_itemsSlice from "./payroll_line_items/payroll_line_itemsSlice";
|
||||
import workers_comp_classesSlice from "./workers_comp_classes/workers_comp_classesSlice";
|
||||
|
||||
export const store = configureStore({
|
||||
reducer: {
|
||||
@ -36,6 +37,7 @@ job_logs: job_logsSlice,
|
||||
job_chemical_usages: job_chemical_usagesSlice,
|
||||
payroll_runs: payroll_runsSlice,
|
||||
payroll_line_items: payroll_line_itemsSlice,
|
||||
workers_comp_classes: workers_comp_classesSlice,
|
||||
},
|
||||
})
|
||||
|
||||
|
||||
@ -0,0 +1,231 @@
|
||||
import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit'
|
||||
import axios from 'axios'
|
||||
import {fulfilledNotify, rejectNotify, resetNotify} from "../../helpers/notifyStateHandler";
|
||||
|
||||
interface MainState {
|
||||
workers_comp_classes: any
|
||||
loading: boolean
|
||||
count: number
|
||||
refetch: boolean;
|
||||
rolesWidgets: any[];
|
||||
notify: {
|
||||
showNotification: boolean
|
||||
textNotification: string
|
||||
typeNotification: string
|
||||
}
|
||||
}
|
||||
|
||||
const initialState: MainState = {
|
||||
workers_comp_classes: [],
|
||||
loading: false,
|
||||
count: 0,
|
||||
refetch: false,
|
||||
rolesWidgets: [],
|
||||
notify: {
|
||||
showNotification: false,
|
||||
textNotification: '',
|
||||
typeNotification: 'warn',
|
||||
},
|
||||
}
|
||||
|
||||
export const fetch = createAsyncThunk('workers_comp_classes/fetch', async (data: any) => {
|
||||
const { id, query } = data
|
||||
const result = await axios.get(
|
||||
`workers_comp_classes${
|
||||
query || (id ? `/${id}` : '')
|
||||
}`
|
||||
)
|
||||
return id ? result.data : {rows: result.data.rows, count: result.data.count};
|
||||
})
|
||||
|
||||
export const deleteItemsByIds = createAsyncThunk(
|
||||
'workers_comp_classes/deleteByIds',
|
||||
async (data: any, { rejectWithValue }) => {
|
||||
try {
|
||||
await axios.post('workers_comp_classes/deleteByIds', { data });
|
||||
} catch (error) {
|
||||
if (!error.response) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
return rejectWithValue(error.response.data);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
export const deleteItem = createAsyncThunk('workers_comp_classes/deleteWorkers_comp_classes', async (id: string, { rejectWithValue }) => {
|
||||
try {
|
||||
await axios.delete(`workers_comp_classes/${id}`)
|
||||
} catch (error) {
|
||||
if (!error.response) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
return rejectWithValue(error.response.data);
|
||||
}
|
||||
})
|
||||
|
||||
export const create = createAsyncThunk('workers_comp_classes/createWorkers_comp_classes', async (data: any, { rejectWithValue }) => {
|
||||
try {
|
||||
const result = await axios.post(
|
||||
'workers_comp_classes',
|
||||
{ data }
|
||||
)
|
||||
return result.data
|
||||
} catch (error) {
|
||||
if (!error.response) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
return rejectWithValue(error.response.data);
|
||||
}
|
||||
})
|
||||
|
||||
export const uploadCsv = createAsyncThunk(
|
||||
'workers_comp_classes/uploadCsv',
|
||||
async (file: File, { rejectWithValue }) => {
|
||||
try {
|
||||
const data = new FormData();
|
||||
data.append('file', file);
|
||||
data.append('filename', file.name);
|
||||
|
||||
const result = await axios.post('workers_comp_classes/bulk-import', data, {
|
||||
headers: {
|
||||
'Content-Type': 'multipart/form-data',
|
||||
},
|
||||
});
|
||||
|
||||
return result.data;
|
||||
} catch (error) {
|
||||
if (!error.response) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
return rejectWithValue(error.response.data);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
export const update = createAsyncThunk('workers_comp_classes/updateWorkers_comp_classes', async (payload: any, { rejectWithValue }) => {
|
||||
try {
|
||||
const result = await axios.put(
|
||||
`workers_comp_classes/${payload.id}`,
|
||||
{ id: payload.id, data: payload.data }
|
||||
)
|
||||
return result.data
|
||||
} catch (error) {
|
||||
if (!error.response) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
return rejectWithValue(error.response.data);
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
export const workers_comp_classesSlice = createSlice({
|
||||
name: 'workers_comp_classes',
|
||||
initialState,
|
||||
reducers: {
|
||||
setRefetch: (state, action: PayloadAction<boolean>) => {
|
||||
state.refetch = action.payload;
|
||||
},
|
||||
},
|
||||
extraReducers: (builder) => {
|
||||
builder.addCase(fetch.pending, (state) => {
|
||||
state.loading = true
|
||||
resetNotify(state);
|
||||
})
|
||||
builder.addCase(fetch.rejected, (state, action) => {
|
||||
state.loading = false
|
||||
rejectNotify(state, action);
|
||||
})
|
||||
|
||||
builder.addCase(fetch.fulfilled, (state, action) => {
|
||||
if (action.payload.rows && action.payload.count >= 0) {
|
||||
state.workers_comp_classes = action.payload.rows;
|
||||
state.count = action.payload.count;
|
||||
} else {
|
||||
state.workers_comp_classes = action.payload;
|
||||
}
|
||||
state.loading = false
|
||||
})
|
||||
|
||||
builder.addCase(deleteItemsByIds.pending, (state) => {
|
||||
state.loading = true;
|
||||
resetNotify(state);
|
||||
});
|
||||
|
||||
builder.addCase(deleteItemsByIds.fulfilled, (state) => {
|
||||
state.loading = false;
|
||||
fulfilledNotify(state, 'Workers_comp_classes has been deleted');
|
||||
});
|
||||
|
||||
builder.addCase(deleteItemsByIds.rejected, (state, action) => {
|
||||
state.loading = false;
|
||||
rejectNotify(state, action);
|
||||
});
|
||||
|
||||
builder.addCase(deleteItem.pending, (state) => {
|
||||
state.loading = true
|
||||
resetNotify(state);
|
||||
})
|
||||
|
||||
builder.addCase(deleteItem.fulfilled, (state) => {
|
||||
state.loading = false
|
||||
fulfilledNotify(state, `${'Workers_comp_classes'.slice(0, -1)} has been deleted`);
|
||||
})
|
||||
|
||||
builder.addCase(deleteItem.rejected, (state, action) => {
|
||||
state.loading = false
|
||||
rejectNotify(state, action);
|
||||
})
|
||||
|
||||
builder.addCase(create.pending, (state) => {
|
||||
state.loading = true
|
||||
resetNotify(state);
|
||||
})
|
||||
builder.addCase(create.rejected, (state, action) => {
|
||||
state.loading = false
|
||||
rejectNotify(state, action);
|
||||
})
|
||||
|
||||
builder.addCase(create.fulfilled, (state) => {
|
||||
state.loading = false
|
||||
fulfilledNotify(state, `${'Workers_comp_classes'.slice(0, -1)} has been created`);
|
||||
})
|
||||
|
||||
builder.addCase(update.pending, (state) => {
|
||||
state.loading = true
|
||||
resetNotify(state);
|
||||
})
|
||||
builder.addCase(update.fulfilled, (state) => {
|
||||
state.loading = false
|
||||
fulfilledNotify(state, `${'Workers_comp_classes'.slice(0, -1)} has been updated`);
|
||||
})
|
||||
builder.addCase(update.rejected, (state, action) => {
|
||||
state.loading = false
|
||||
rejectNotify(state, action);
|
||||
})
|
||||
|
||||
builder.addCase(uploadCsv.pending, (state) => {
|
||||
state.loading = true;
|
||||
resetNotify(state);
|
||||
})
|
||||
builder.addCase(uploadCsv.fulfilled, (state) => {
|
||||
state.loading = false;
|
||||
fulfilledNotify(state, 'Workers_comp_classes has been uploaded');
|
||||
})
|
||||
builder.addCase(uploadCsv.rejected, (state, action) => {
|
||||
state.loading = false;
|
||||
rejectNotify(state, action);
|
||||
})
|
||||
|
||||
|
||||
},
|
||||
})
|
||||
|
||||
// Action creators are generated for each case reducer function
|
||||
export const { setRefetch } = workers_comp_classesSlice.actions
|
||||
|
||||
export default workers_comp_classesSlice.reducer
|
||||
26
patch.js
Normal file
26
patch.js
Normal file
@ -0,0 +1,26 @@
|
||||
const fs = require('fs');
|
||||
const file = 'backend/src/db/api/job_logs.js';
|
||||
let content = fs.readFileSync(file, 'utf8');
|
||||
|
||||
if (!content.includes('setWorkersCompClass')) {
|
||||
content = content.replace(
|
||||
/await job_logs.setVehicle(\s*data.vehicle\s*||\s*null,\s*{\s*transaction,\s*})/g,
|
||||
`await job_logs.setVehicle( data.vehicle || null, {\n transaction,\n });\n \n await job_logs.setWorkersCompClass( data.workersCompClass || null, {\n transaction,\n });`
|
||||
);
|
||||
|
||||
content = content.replace(
|
||||
/if\s*\(data.vehicle !== undefined\)\s*{\s*await job_logs.setVehicle\(\s*data.vehicle,\s*{\s*transaction\s*}\s*\);\s*}/g,
|
||||
`if (data.vehicle !== undefined) {\n await job_logs.setVehicle(\n data.vehicle,\n { transaction }\n );\n }\n \n if (data.workersCompClass !== undefined) {\n await job_logs.setWorkersCompClass(\n data.workersCompClass,\n { transaction }\n );\n }`
|
||||
);
|
||||
|
||||
// Also let's update findBy to include workersCompClass
|
||||
content = content.replace(
|
||||
/output.vehicle = await job_logs.getVehicle({\s*transaction\s*})/g,
|
||||
`output.vehicle = await job_logs.getVehicle({\n transaction\n });\n \n output.workersCompClass = await job_logs.getWorkersCompClass({\n transaction\n });`
|
||||
);
|
||||
|
||||
fs.writeFileSync(file, content);
|
||||
console.log("Patched!");
|
||||
} else {
|
||||
console.log("Already patched.");
|
||||
}
|
||||
24
patch.py
Normal file
24
patch.py
Normal file
@ -0,0 +1,24 @@
|
||||
import re
|
||||
|
||||
with open('backend/src/db/api/job_logs.js', 'r') as f:
|
||||
content = f.read()
|
||||
|
||||
content = content.replace(
|
||||
'await job_logs.setVehicle( data.vehicle || null, {\n transaction,\n });',
|
||||
'await job_logs.setVehicle( data.vehicle || null, {\n transaction,\n });\n \n await job_logs.setWorkersCompClass( data.workersCompClass || null, {\n transaction,\n });'
|
||||
)
|
||||
|
||||
content = content.replace(
|
||||
'''if (data.vehicle !== undefined) {\n await job_logs.setVehicle(\n \n data.vehicle,\n \n { transaction }\n );\n }''',
|
||||
'''if (data.vehicle !== undefined) {\n await job_logs.setVehicle(\n \n data.vehicle,\n \n { transaction }\n );\n }\n \n if (data.workersCompClass !== undefined) {\n await job_logs.setWorkersCompClass(\n \n data.workersCompClass,\n \n { transaction }\n );\n }'''
|
||||
)
|
||||
|
||||
content = content.replace(
|
||||
'''output.vehicle = await job_logs.getVehicle({\n transaction\n });''',
|
||||
'''output.vehicle = await job_logs.getVehicle({\n transaction\n });\n \n output.workersCompClass = await job_logs.getWorkersCompClass({\n transaction\n });'''
|
||||
)
|
||||
|
||||
with open('backend/src/db/api/job_logs.js', 'w') as f:
|
||||
f.write(content)
|
||||
|
||||
print("Patched correctly!")
|
||||
61
patch2.py
Normal file
61
patch2.py
Normal file
@ -0,0 +1,61 @@
|
||||
import re
|
||||
|
||||
with open('backend/src/db/api/job_logs.js', 'r') as f:
|
||||
content = f.read()
|
||||
|
||||
replacement = ''' {
|
||||
model: db.vehicles,
|
||||
as: 'vehicle',
|
||||
|
||||
where: filter.vehicle ? {
|
||||
[Op.or]: [
|
||||
{ id: { [Op.in]: filter.vehicle.split('|').map(term => Utils.uuid(term)) } },
|
||||
{
|
||||
name: {
|
||||
[Op.or]: filter.vehicle.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
|
||||
}
|
||||
},
|
||||
]
|
||||
} : {},
|
||||
|
||||
},
|
||||
|
||||
{
|
||||
model: db.workers_comp_classes,
|
||||
as: 'workersCompClass',
|
||||
where: filter.workersCompClass ? {
|
||||
[Op.or]: [
|
||||
{ id: { [Op.in]: filter.workersCompClass.split('|').map(term => Utils.uuid(term)) } },
|
||||
{
|
||||
name: {
|
||||
[Op.or]: filter.workersCompClass.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
|
||||
}
|
||||
},
|
||||
]
|
||||
} : {},
|
||||
},'''
|
||||
|
||||
content = content.replace(
|
||||
''' {
|
||||
model: db.vehicles,
|
||||
as: 'vehicle',
|
||||
|
||||
where: filter.vehicle ? {
|
||||
[Op.or]: [
|
||||
{ id: { [Op.in]: filter.vehicle.split('|').map(term => Utils.uuid(term)) } },
|
||||
{
|
||||
name: {
|
||||
[Op.or]: filter.vehicle.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
|
||||
}
|
||||
},
|
||||
]
|
||||
} : {},
|
||||
|
||||
},''',
|
||||
replacement
|
||||
)
|
||||
|
||||
with open('backend/src/db/api/job_logs.js', 'w') as f:
|
||||
f.write(content)
|
||||
|
||||
print("Patched include!")
|
||||
63
patch_dashboard.js
Normal file
63
patch_dashboard.js
Normal file
@ -0,0 +1,63 @@
|
||||
const fs = require('fs');
|
||||
|
||||
let content = fs.readFileSync('frontend/src/pages/dashboard.tsx', 'utf8');
|
||||
|
||||
const replacement = `
|
||||
const isAdmin = hasPermission(currentUser, 'UPDATE_USERS');
|
||||
|
||||
async function loadData() {
|
||||
if (!currentUser) return;
|
||||
|
||||
if (!isAdmin) {
|
||||
// For regular employees, we just want to load their own logs
|
||||
axios.get('/job_logs/count?employee=' + currentUser.id).then((res) => setJob_logs(res.data.count)).catch(() => setJob_logs(0));
|
||||
return;
|
||||
}
|
||||
|
||||
const entities = ['users','roles','permissions','customers','vehicles','pay_types','employee_pay_types','chemical_products','job_logs','job_chemical_usages','payroll_runs','payroll_line_items',];
|
||||
`;
|
||||
|
||||
content = content.replace(/async function loadData\(\)\{\n\s*const entities = \['users','roles',/g, replacement);
|
||||
|
||||
const replacement2 = `
|
||||
{!!rolesWidgets.length && <hr className='my-6 ' />}
|
||||
|
||||
{isAdmin ? (
|
||||
<div id="dashboard" className='grid grid-cols-1 gap-6 lg:grid-cols-3 mb-6'>
|
||||
`;
|
||||
|
||||
content = content.replace(/\{\!\!rolesWidgets\.length && <hr className='my-6 ' \/>\}\n\s*<div id="dashboard" className='grid grid-cols-1 gap-6 lg:grid-cols-3 mb-6'>/g, replacement2);
|
||||
|
||||
const replacement3 = `
|
||||
</Link>}
|
||||
|
||||
|
||||
</div>
|
||||
) : (
|
||||
<div id="dashboard" className="grid grid-cols-1 gap-6 lg:grid-cols-3 mb-6">
|
||||
<Link href={'/my-logs'}>
|
||||
<div className={"dark:bg-dark-900 dark:border-dark-700 p-6 " + (corners !== 'rounded-full' ? corners : 'rounded-3xl') + " " + cardsStyle}>
|
||||
<div className="flex justify-between align-center">
|
||||
<div>
|
||||
<div className="text-lg leading-tight text-gray-500 dark:text-gray-400">
|
||||
My Logs
|
||||
</div>
|
||||
<div className="text-3xl leading-tight font-semibold">
|
||||
{job_logs}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<BaseIcon className={iconsColor} w="w-16" h="h-16" size={48} path={icon.mdiClipboardTextClock} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
</SectionMain>
|
||||
`;
|
||||
|
||||
content = content.replace(/<\/Link>\}\n\s*<\/div>\n\s*<\/SectionMain>/g, replacement3);
|
||||
|
||||
fs.writeFileSync('frontend/src/pages/dashboard.tsx', content);
|
||||
console.log("Patched dashboard.tsx");
|
||||
27
patch_menuAside.js
Normal file
27
patch_menuAside.js
Normal file
@ -0,0 +1,27 @@
|
||||
const fs = require('fs');
|
||||
|
||||
let content = fs.readFileSync('frontend/src/menuAside.ts', 'utf8');
|
||||
|
||||
// Replace READ_ with UPDATE_ for specific items
|
||||
const itemsToUpdate = [
|
||||
'READ_CUSTOMERS',
|
||||
'READ_VEHICLES',
|
||||
'READ_WORKERS_COMP_CLASSES',
|
||||
'READ_PAY_TYPES',
|
||||
'READ_EMPLOYEE_PAY_TYPES',
|
||||
'READ_CHEMICAL_PRODUCTS',
|
||||
'READ_JOB_CHEMICAL_USAGES',
|
||||
];
|
||||
|
||||
itemsToUpdate.forEach(perm => {
|
||||
content = content.replace(new RegExp(`permissions: '${perm}'`, 'g'), `permissions: '${perm.replace('READ_', 'UPDATE_')}'`);
|
||||
});
|
||||
|
||||
// For All Job Logs, we need to be careful not to replace My Logs which is also READ_JOB_LOGS
|
||||
content = content.replace(/label: 'All Job Logs',\n\s*icon: [^,]+,\n\s*permissions: 'READ_JOB_LOGS'/g, (match) => {
|
||||
return match.replace("permissions: 'READ_JOB_LOGS'", "permissions: 'UPDATE_JOB_LOGS'");
|
||||
});
|
||||
|
||||
fs.writeFileSync('frontend/src/menuAside.ts', content);
|
||||
console.log("Patched menuAside.ts");
|
||||
|
||||
14
patch_menuAside2.js
Normal file
14
patch_menuAside2.js
Normal file
@ -0,0 +1,14 @@
|
||||
const fs = require('fs');
|
||||
let content = fs.readFileSync('frontend/src/menuAside.ts', 'utf8');
|
||||
|
||||
const itemsToUpdate = [
|
||||
'READ_PAYROLL_RUNS',
|
||||
'READ_PAYROLL_LINE_ITEMS',
|
||||
];
|
||||
|
||||
itemsToUpdate.forEach(perm => {
|
||||
content = content.replace(new RegExp(`permissions: '${perm}'`, 'g'), `permissions: '${perm.replace('READ_', 'UPDATE_')}'`);
|
||||
});
|
||||
|
||||
fs.writeFileSync('frontend/src/menuAside.ts', content);
|
||||
console.log("Patched payroll in menuAside.ts");
|
||||
Loading…
x
Reference in New Issue
Block a user