add invoices
This commit is contained in:
parent
cdffd9e45f
commit
40a7bb3809
File diff suppressed because one or more lines are too long
444
backend/src/db/api/invoices.js
Normal file
444
backend/src/db/api/invoices.js
Normal file
@ -0,0 +1,444 @@
|
||||
|
||||
const db = require('../models');
|
||||
const crypto = require('crypto');
|
||||
const Utils = require('../utils');
|
||||
|
||||
const Sequelize = db.Sequelize;
|
||||
const Op = Sequelize.Op;
|
||||
|
||||
module.exports = class InvoicesDBApi {
|
||||
|
||||
static async create(data, options) {
|
||||
const currentUser = (options && options.currentUser) || { id: null };
|
||||
const transaction = (options && options.transaction) || undefined;
|
||||
|
||||
const invoices = await db.invoices.create(
|
||||
{
|
||||
id: data.id || undefined,
|
||||
|
||||
amountoriginal: data.amountoriginal
|
||||
||
|
||||
null
|
||||
,
|
||||
|
||||
currency: data.currency
|
||||
||
|
||||
null
|
||||
,
|
||||
|
||||
incomecost: data.incomecost
|
||||
||
|
||||
null
|
||||
,
|
||||
|
||||
amountpln: data.amountpln
|
||||
||
|
||||
null
|
||||
,
|
||||
|
||||
invoicedate: data.invoicedate
|
||||
||
|
||||
null
|
||||
,
|
||||
|
||||
period: data.period
|
||||
||
|
||||
null
|
||||
,
|
||||
|
||||
description: data.description
|
||||
||
|
||||
null
|
||||
,
|
||||
|
||||
importHash: data.importHash || null,
|
||||
createdById: currentUser.id,
|
||||
updatedById: currentUser.id,
|
||||
},
|
||||
{ transaction },
|
||||
);
|
||||
|
||||
return invoices;
|
||||
}
|
||||
|
||||
static async bulkImport(data, options) {
|
||||
const currentUser = (options && options.currentUser) || { id: null };
|
||||
const transaction = (options && options.transaction) || undefined;
|
||||
|
||||
// Prepare data - wrapping individual data transformations in a map() method
|
||||
const invoicesData = data.map((item, index) => ({
|
||||
id: item.id || undefined,
|
||||
|
||||
amountoriginal: item.amountoriginal
|
||||
||
|
||||
null
|
||||
,
|
||||
|
||||
currency: item.currency
|
||||
||
|
||||
null
|
||||
,
|
||||
|
||||
incomecost: item.incomecost
|
||||
||
|
||||
null
|
||||
,
|
||||
|
||||
amountpln: item.amountpln
|
||||
||
|
||||
null
|
||||
,
|
||||
|
||||
invoicedate: item.invoicedate
|
||||
||
|
||||
null
|
||||
,
|
||||
|
||||
period: item.period
|
||||
||
|
||||
null
|
||||
,
|
||||
|
||||
description: item.description
|
||||
||
|
||||
null
|
||||
,
|
||||
|
||||
importHash: item.importHash || null,
|
||||
createdById: currentUser.id,
|
||||
updatedById: currentUser.id,
|
||||
createdAt: new Date(Date.now() + index * 1000),
|
||||
}));
|
||||
|
||||
// Bulk create items
|
||||
const invoices = await db.invoices.bulkCreate(invoicesData, { transaction });
|
||||
|
||||
return invoices;
|
||||
}
|
||||
|
||||
static async update(id, data, options) {
|
||||
const currentUser = (options && options.currentUser) || {id: null};
|
||||
const transaction = (options && options.transaction) || undefined;
|
||||
|
||||
const invoices = await db.invoices.findByPk(id, {}, {transaction});
|
||||
|
||||
const updatePayload = {};
|
||||
|
||||
if (data.amountoriginal !== undefined) updatePayload.amountoriginal = data.amountoriginal;
|
||||
|
||||
if (data.currency !== undefined) updatePayload.currency = data.currency;
|
||||
|
||||
if (data.incomecost !== undefined) updatePayload.incomecost = data.incomecost;
|
||||
|
||||
if (data.amountpln !== undefined) updatePayload.amountpln = data.amountpln;
|
||||
|
||||
if (data.invoicedate !== undefined) updatePayload.invoicedate = data.invoicedate;
|
||||
|
||||
if (data.period !== undefined) updatePayload.period = data.period;
|
||||
|
||||
if (data.description !== undefined) updatePayload.description = data.description;
|
||||
|
||||
updatePayload.updatedById = currentUser.id;
|
||||
|
||||
await invoices.update(updatePayload, {transaction});
|
||||
|
||||
return invoices;
|
||||
}
|
||||
|
||||
static async deleteByIds(ids, options) {
|
||||
const currentUser = (options && options.currentUser) || { id: null };
|
||||
const transaction = (options && options.transaction) || undefined;
|
||||
|
||||
const invoices = await db.invoices.findAll({
|
||||
where: {
|
||||
id: {
|
||||
[Op.in]: ids,
|
||||
},
|
||||
},
|
||||
transaction,
|
||||
});
|
||||
|
||||
await db.sequelize.transaction(async (transaction) => {
|
||||
for (const record of invoices) {
|
||||
await record.update(
|
||||
{deletedBy: currentUser.id},
|
||||
{transaction}
|
||||
);
|
||||
}
|
||||
for (const record of invoices) {
|
||||
await record.destroy({transaction});
|
||||
}
|
||||
});
|
||||
|
||||
return invoices;
|
||||
}
|
||||
|
||||
static async remove(id, options) {
|
||||
const currentUser = (options && options.currentUser) || {id: null};
|
||||
const transaction = (options && options.transaction) || undefined;
|
||||
|
||||
const invoices = await db.invoices.findByPk(id, options);
|
||||
|
||||
await invoices.update({
|
||||
deletedBy: currentUser.id
|
||||
}, {
|
||||
transaction,
|
||||
});
|
||||
|
||||
await invoices.destroy({
|
||||
transaction
|
||||
});
|
||||
|
||||
return invoices;
|
||||
}
|
||||
|
||||
static async findBy(where, options) {
|
||||
const transaction = (options && options.transaction) || undefined;
|
||||
|
||||
const invoices = await db.invoices.findOne(
|
||||
{ where },
|
||||
{ transaction },
|
||||
);
|
||||
|
||||
if (!invoices) {
|
||||
return invoices;
|
||||
}
|
||||
|
||||
const output = invoices.get({plain: true});
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
static async findAll(filter, options) {
|
||||
const limit = filter.limit || 0;
|
||||
let offset = 0;
|
||||
let where = {};
|
||||
const currentPage = +filter.page;
|
||||
|
||||
const user = (options && options.currentUser) || null;
|
||||
|
||||
offset = currentPage * limit;
|
||||
|
||||
const orderBy = null;
|
||||
|
||||
const transaction = (options && options.transaction) || undefined;
|
||||
|
||||
let include = [];
|
||||
|
||||
if (filter) {
|
||||
if (filter.id) {
|
||||
where = {
|
||||
...where,
|
||||
['id']: Utils.uuid(filter.id),
|
||||
};
|
||||
}
|
||||
|
||||
if (filter.currency) {
|
||||
where = {
|
||||
...where,
|
||||
[Op.and]: Utils.ilike(
|
||||
'invoices',
|
||||
'currency',
|
||||
filter.currency,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
if (filter.incomecost) {
|
||||
where = {
|
||||
...where,
|
||||
[Op.and]: Utils.ilike(
|
||||
'invoices',
|
||||
'incomecost',
|
||||
filter.incomecost,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
if (filter.period) {
|
||||
where = {
|
||||
...where,
|
||||
[Op.and]: Utils.ilike(
|
||||
'invoices',
|
||||
'period',
|
||||
filter.period,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
if (filter.description) {
|
||||
where = {
|
||||
...where,
|
||||
[Op.and]: Utils.ilike(
|
||||
'invoices',
|
||||
'description',
|
||||
filter.description,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
if (filter.amountoriginalRange) {
|
||||
const [start, end] = filter.amountoriginalRange;
|
||||
|
||||
if (start !== undefined && start !== null && start !== '') {
|
||||
where = {
|
||||
...where,
|
||||
amountoriginal: {
|
||||
...where.amountoriginal,
|
||||
[Op.gte]: start,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (end !== undefined && end !== null && end !== '') {
|
||||
where = {
|
||||
...where,
|
||||
amountoriginal: {
|
||||
...where.amountoriginal,
|
||||
[Op.lte]: end,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (filter.amountplnRange) {
|
||||
const [start, end] = filter.amountplnRange;
|
||||
|
||||
if (start !== undefined && start !== null && start !== '') {
|
||||
where = {
|
||||
...where,
|
||||
amountpln: {
|
||||
...where.amountpln,
|
||||
[Op.gte]: start,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (end !== undefined && end !== null && end !== '') {
|
||||
where = {
|
||||
...where,
|
||||
amountpln: {
|
||||
...where.amountpln,
|
||||
[Op.lte]: end,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (filter.invoicedateRange) {
|
||||
const [start, end] = filter.invoicedateRange;
|
||||
|
||||
if (start !== undefined && start !== null && start !== '') {
|
||||
where = {
|
||||
...where,
|
||||
invoicedate: {
|
||||
...where.invoicedate,
|
||||
[Op.gte]: start,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (end !== undefined && end !== null && end !== '') {
|
||||
where = {
|
||||
...where,
|
||||
invoicedate: {
|
||||
...where.invoicedate,
|
||||
[Op.lte]: end,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (filter.active !== undefined) {
|
||||
where = {
|
||||
...where,
|
||||
active: filter.active === true || filter.active === 'true'
|
||||
};
|
||||
}
|
||||
|
||||
if (filter.createdAtRange) {
|
||||
const [start, end] = filter.createdAtRange;
|
||||
|
||||
if (start !== undefined && start !== null && start !== '') {
|
||||
where = {
|
||||
...where,
|
||||
['createdAt']: {
|
||||
...where.createdAt,
|
||||
[Op.gte]: start,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (end !== undefined && end !== null && end !== '') {
|
||||
where = {
|
||||
...where,
|
||||
['createdAt']: {
|
||||
...where.createdAt,
|
||||
[Op.lte]: end,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const queryOptions = {
|
||||
where,
|
||||
include,
|
||||
distinct: true,
|
||||
order: filter.field && filter.sort
|
||||
? [[filter.field, filter.sort]]
|
||||
: [['createdAt', 'desc']],
|
||||
transaction: options?.transaction,
|
||||
logging: console.log
|
||||
};
|
||||
|
||||
if (!options?.countOnly) {
|
||||
queryOptions.limit = limit ? Number(limit) : undefined;
|
||||
queryOptions.offset = offset ? Number(offset) : undefined;
|
||||
}
|
||||
|
||||
try {
|
||||
const { rows, count } = await db.invoices.findAndCountAll(queryOptions);
|
||||
|
||||
return {
|
||||
rows: options?.countOnly ? [] : rows,
|
||||
count: count
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Error executing query:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
static async findAllAutocomplete(query, limit, offset) {
|
||||
let where = {};
|
||||
|
||||
if (query) {
|
||||
where = {
|
||||
[Op.or]: [
|
||||
{ ['id']: Utils.uuid(query) },
|
||||
Utils.ilike(
|
||||
'invoices',
|
||||
'id',
|
||||
query,
|
||||
),
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
const records = await db.invoices.findAll({
|
||||
attributes: [ 'id', 'id' ],
|
||||
where,
|
||||
limit: limit ? Number(limit) : undefined,
|
||||
offset: offset ? Number(offset) : undefined,
|
||||
orderBy: [['id', 'ASC']],
|
||||
});
|
||||
|
||||
return records.map((record) => ({
|
||||
id: record.id,
|
||||
label: record.id,
|
||||
}));
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
91
backend/src/db/migrations/1750800185369.js
Normal file
91
backend/src/db/migrations/1750800185369.js
Normal file
@ -0,0 +1,91 @@
|
||||
module.exports = {
|
||||
/**
|
||||
* @param {QueryInterface} queryInterface
|
||||
* @param {Sequelize} Sequelize
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async up(queryInterface, Sequelize) {
|
||||
/**
|
||||
* @type {Transaction}
|
||||
*/
|
||||
const transaction = await queryInterface.sequelize.transaction();
|
||||
try {
|
||||
|
||||
await queryInterface.createTable('invoices', {
|
||||
id: {
|
||||
type: Sequelize.DataTypes.UUID,
|
||||
defaultValue: Sequelize.DataTypes.UUIDV4,
|
||||
primaryKey: true,
|
||||
},
|
||||
createdById: {
|
||||
type: Sequelize.DataTypes.UUID,
|
||||
references: {
|
||||
key: 'id',
|
||||
model: 'users',
|
||||
},
|
||||
},
|
||||
updatedById: {
|
||||
type: Sequelize.DataTypes.UUID,
|
||||
references: {
|
||||
key: 'id',
|
||||
model: 'users',
|
||||
},
|
||||
},
|
||||
createdAt: { type: Sequelize.DataTypes.DATE },
|
||||
updatedAt: { type: Sequelize.DataTypes.DATE },
|
||||
deletedAt: { type: Sequelize.DataTypes.DATE },
|
||||
importHash: {
|
||||
type: Sequelize.DataTypes.STRING(255),
|
||||
allowNull: true,
|
||||
unique: true,
|
||||
},
|
||||
}, { transaction });
|
||||
|
||||
await queryInterface.addColumn(
|
||||
'invoices',
|
||||
'organizationsId',
|
||||
{
|
||||
type: Sequelize.DataTypes.UUID,
|
||||
|
||||
references: {
|
||||
model: 'organizations',
|
||||
key: 'id',
|
||||
},
|
||||
|
||||
},
|
||||
{ transaction }
|
||||
);
|
||||
|
||||
await transaction.commit();
|
||||
} catch (err) {
|
||||
await transaction.rollback();
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
/**
|
||||
* @param {QueryInterface} queryInterface
|
||||
* @param {Sequelize} Sequelize
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async down(queryInterface, Sequelize) {
|
||||
/**
|
||||
* @type {Transaction}
|
||||
*/
|
||||
const transaction = await queryInterface.sequelize.transaction();
|
||||
try {
|
||||
|
||||
await queryInterface.removeColumn(
|
||||
'invoices',
|
||||
'organizationsId',
|
||||
{ transaction }
|
||||
);
|
||||
|
||||
await queryInterface.dropTable('invoices', { transaction });
|
||||
|
||||
await transaction.commit();
|
||||
} catch (err) {
|
||||
await transaction.rollback();
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
};
|
||||
54
backend/src/db/migrations/1750800194394.js
Normal file
54
backend/src/db/migrations/1750800194394.js
Normal file
@ -0,0 +1,54 @@
|
||||
module.exports = {
|
||||
/**
|
||||
* @param {QueryInterface} queryInterface
|
||||
* @param {Sequelize} Sequelize
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async up(queryInterface, Sequelize) {
|
||||
/**
|
||||
* @type {Transaction}
|
||||
*/
|
||||
const transaction = await queryInterface.sequelize.transaction();
|
||||
try {
|
||||
|
||||
await queryInterface.addColumn(
|
||||
'invoices',
|
||||
'amountoriginal',
|
||||
{
|
||||
type: Sequelize.DataTypes.DECIMAL,
|
||||
|
||||
},
|
||||
{ transaction }
|
||||
);
|
||||
|
||||
await transaction.commit();
|
||||
} catch (err) {
|
||||
await transaction.rollback();
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
/**
|
||||
* @param {QueryInterface} queryInterface
|
||||
* @param {Sequelize} Sequelize
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async down(queryInterface, Sequelize) {
|
||||
/**
|
||||
* @type {Transaction}
|
||||
*/
|
||||
const transaction = await queryInterface.sequelize.transaction();
|
||||
try {
|
||||
|
||||
await queryInterface.removeColumn(
|
||||
'invoices',
|
||||
'amountoriginal',
|
||||
{ transaction }
|
||||
);
|
||||
|
||||
await transaction.commit();
|
||||
} catch (err) {
|
||||
await transaction.rollback();
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
};
|
||||
54
backend/src/db/migrations/1750800210259.js
Normal file
54
backend/src/db/migrations/1750800210259.js
Normal file
@ -0,0 +1,54 @@
|
||||
module.exports = {
|
||||
/**
|
||||
* @param {QueryInterface} queryInterface
|
||||
* @param {Sequelize} Sequelize
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async up(queryInterface, Sequelize) {
|
||||
/**
|
||||
* @type {Transaction}
|
||||
*/
|
||||
const transaction = await queryInterface.sequelize.transaction();
|
||||
try {
|
||||
|
||||
await queryInterface.addColumn(
|
||||
'invoices',
|
||||
'currency',
|
||||
{
|
||||
type: Sequelize.DataTypes.TEXT,
|
||||
|
||||
},
|
||||
{ transaction }
|
||||
);
|
||||
|
||||
await transaction.commit();
|
||||
} catch (err) {
|
||||
await transaction.rollback();
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
/**
|
||||
* @param {QueryInterface} queryInterface
|
||||
* @param {Sequelize} Sequelize
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async down(queryInterface, Sequelize) {
|
||||
/**
|
||||
* @type {Transaction}
|
||||
*/
|
||||
const transaction = await queryInterface.sequelize.transaction();
|
||||
try {
|
||||
|
||||
await queryInterface.removeColumn(
|
||||
'invoices',
|
||||
'currency',
|
||||
{ transaction }
|
||||
);
|
||||
|
||||
await transaction.commit();
|
||||
} catch (err) {
|
||||
await transaction.rollback();
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
};
|
||||
54
backend/src/db/migrations/1750800216064.js
Normal file
54
backend/src/db/migrations/1750800216064.js
Normal file
@ -0,0 +1,54 @@
|
||||
module.exports = {
|
||||
/**
|
||||
* @param {QueryInterface} queryInterface
|
||||
* @param {Sequelize} Sequelize
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async up(queryInterface, Sequelize) {
|
||||
/**
|
||||
* @type {Transaction}
|
||||
*/
|
||||
const transaction = await queryInterface.sequelize.transaction();
|
||||
try {
|
||||
|
||||
await queryInterface.addColumn(
|
||||
'invoices',
|
||||
'incomecost',
|
||||
{
|
||||
type: Sequelize.DataTypes.TEXT,
|
||||
|
||||
},
|
||||
{ transaction }
|
||||
);
|
||||
|
||||
await transaction.commit();
|
||||
} catch (err) {
|
||||
await transaction.rollback();
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
/**
|
||||
* @param {QueryInterface} queryInterface
|
||||
* @param {Sequelize} Sequelize
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async down(queryInterface, Sequelize) {
|
||||
/**
|
||||
* @type {Transaction}
|
||||
*/
|
||||
const transaction = await queryInterface.sequelize.transaction();
|
||||
try {
|
||||
|
||||
await queryInterface.removeColumn(
|
||||
'invoices',
|
||||
'incomecost',
|
||||
{ transaction }
|
||||
);
|
||||
|
||||
await transaction.commit();
|
||||
} catch (err) {
|
||||
await transaction.rollback();
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
};
|
||||
54
backend/src/db/migrations/1750800221746.js
Normal file
54
backend/src/db/migrations/1750800221746.js
Normal file
@ -0,0 +1,54 @@
|
||||
module.exports = {
|
||||
/**
|
||||
* @param {QueryInterface} queryInterface
|
||||
* @param {Sequelize} Sequelize
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async up(queryInterface, Sequelize) {
|
||||
/**
|
||||
* @type {Transaction}
|
||||
*/
|
||||
const transaction = await queryInterface.sequelize.transaction();
|
||||
try {
|
||||
|
||||
await queryInterface.addColumn(
|
||||
'invoices',
|
||||
'amountpln',
|
||||
{
|
||||
type: Sequelize.DataTypes.DECIMAL,
|
||||
|
||||
},
|
||||
{ transaction }
|
||||
);
|
||||
|
||||
await transaction.commit();
|
||||
} catch (err) {
|
||||
await transaction.rollback();
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
/**
|
||||
* @param {QueryInterface} queryInterface
|
||||
* @param {Sequelize} Sequelize
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async down(queryInterface, Sequelize) {
|
||||
/**
|
||||
* @type {Transaction}
|
||||
*/
|
||||
const transaction = await queryInterface.sequelize.transaction();
|
||||
try {
|
||||
|
||||
await queryInterface.removeColumn(
|
||||
'invoices',
|
||||
'amountpln',
|
||||
{ transaction }
|
||||
);
|
||||
|
||||
await transaction.commit();
|
||||
} catch (err) {
|
||||
await transaction.rollback();
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
};
|
||||
54
backend/src/db/migrations/1750800228412.js
Normal file
54
backend/src/db/migrations/1750800228412.js
Normal file
@ -0,0 +1,54 @@
|
||||
module.exports = {
|
||||
/**
|
||||
* @param {QueryInterface} queryInterface
|
||||
* @param {Sequelize} Sequelize
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async up(queryInterface, Sequelize) {
|
||||
/**
|
||||
* @type {Transaction}
|
||||
*/
|
||||
const transaction = await queryInterface.sequelize.transaction();
|
||||
try {
|
||||
|
||||
await queryInterface.addColumn(
|
||||
'invoices',
|
||||
'invoicedate',
|
||||
{
|
||||
type: Sequelize.DataTypes.DATEONLY,
|
||||
|
||||
},
|
||||
{ transaction }
|
||||
);
|
||||
|
||||
await transaction.commit();
|
||||
} catch (err) {
|
||||
await transaction.rollback();
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
/**
|
||||
* @param {QueryInterface} queryInterface
|
||||
* @param {Sequelize} Sequelize
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async down(queryInterface, Sequelize) {
|
||||
/**
|
||||
* @type {Transaction}
|
||||
*/
|
||||
const transaction = await queryInterface.sequelize.transaction();
|
||||
try {
|
||||
|
||||
await queryInterface.removeColumn(
|
||||
'invoices',
|
||||
'invoicedate',
|
||||
{ transaction }
|
||||
);
|
||||
|
||||
await transaction.commit();
|
||||
} catch (err) {
|
||||
await transaction.rollback();
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
};
|
||||
54
backend/src/db/migrations/1750800233922.js
Normal file
54
backend/src/db/migrations/1750800233922.js
Normal file
@ -0,0 +1,54 @@
|
||||
module.exports = {
|
||||
/**
|
||||
* @param {QueryInterface} queryInterface
|
||||
* @param {Sequelize} Sequelize
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async up(queryInterface, Sequelize) {
|
||||
/**
|
||||
* @type {Transaction}
|
||||
*/
|
||||
const transaction = await queryInterface.sequelize.transaction();
|
||||
try {
|
||||
|
||||
await queryInterface.addColumn(
|
||||
'invoices',
|
||||
'period',
|
||||
{
|
||||
type: Sequelize.DataTypes.TEXT,
|
||||
|
||||
},
|
||||
{ transaction }
|
||||
);
|
||||
|
||||
await transaction.commit();
|
||||
} catch (err) {
|
||||
await transaction.rollback();
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
/**
|
||||
* @param {QueryInterface} queryInterface
|
||||
* @param {Sequelize} Sequelize
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async down(queryInterface, Sequelize) {
|
||||
/**
|
||||
* @type {Transaction}
|
||||
*/
|
||||
const transaction = await queryInterface.sequelize.transaction();
|
||||
try {
|
||||
|
||||
await queryInterface.removeColumn(
|
||||
'invoices',
|
||||
'period',
|
||||
{ transaction }
|
||||
);
|
||||
|
||||
await transaction.commit();
|
||||
} catch (err) {
|
||||
await transaction.rollback();
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
};
|
||||
54
backend/src/db/migrations/1750800241661.js
Normal file
54
backend/src/db/migrations/1750800241661.js
Normal file
@ -0,0 +1,54 @@
|
||||
module.exports = {
|
||||
/**
|
||||
* @param {QueryInterface} queryInterface
|
||||
* @param {Sequelize} Sequelize
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async up(queryInterface, Sequelize) {
|
||||
/**
|
||||
* @type {Transaction}
|
||||
*/
|
||||
const transaction = await queryInterface.sequelize.transaction();
|
||||
try {
|
||||
|
||||
await queryInterface.addColumn(
|
||||
'invoices',
|
||||
'description',
|
||||
{
|
||||
type: Sequelize.DataTypes.TEXT,
|
||||
|
||||
},
|
||||
{ transaction }
|
||||
);
|
||||
|
||||
await transaction.commit();
|
||||
} catch (err) {
|
||||
await transaction.rollback();
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
/**
|
||||
* @param {QueryInterface} queryInterface
|
||||
* @param {Sequelize} Sequelize
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async down(queryInterface, Sequelize) {
|
||||
/**
|
||||
* @type {Transaction}
|
||||
*/
|
||||
const transaction = await queryInterface.sequelize.transaction();
|
||||
try {
|
||||
|
||||
await queryInterface.removeColumn(
|
||||
'invoices',
|
||||
'description',
|
||||
{ transaction }
|
||||
);
|
||||
|
||||
await transaction.commit();
|
||||
} catch (err) {
|
||||
await transaction.rollback();
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
};
|
||||
38
backend/src/db/migrations/1750800248668.js
Normal file
38
backend/src/db/migrations/1750800248668.js
Normal file
@ -0,0 +1,38 @@
|
||||
module.exports = {
|
||||
/**
|
||||
* @param {QueryInterface} queryInterface
|
||||
* @param {Sequelize} Sequelize
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async up(queryInterface, Sequelize) {
|
||||
/**
|
||||
* @type {Transaction}
|
||||
*/
|
||||
const transaction = await queryInterface.sequelize.transaction();
|
||||
try {
|
||||
|
||||
await transaction.commit();
|
||||
} catch (err) {
|
||||
await transaction.rollback();
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
/**
|
||||
* @param {QueryInterface} queryInterface
|
||||
* @param {Sequelize} Sequelize
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async down(queryInterface, Sequelize) {
|
||||
/**
|
||||
* @type {Transaction}
|
||||
*/
|
||||
const transaction = await queryInterface.sequelize.transaction();
|
||||
try {
|
||||
|
||||
await transaction.commit();
|
||||
} catch (err) {
|
||||
await transaction.rollback();
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
};
|
||||
86
backend/src/db/models/invoices.js
Normal file
86
backend/src/db/models/invoices.js
Normal file
@ -0,0 +1,86 @@
|
||||
const config = require('../../config');
|
||||
const providers = config.providers;
|
||||
const crypto = require('crypto');
|
||||
const bcrypt = require('bcrypt');
|
||||
const moment = require('moment');
|
||||
|
||||
module.exports = function(sequelize, DataTypes) {
|
||||
const invoices = sequelize.define(
|
||||
'invoices',
|
||||
{
|
||||
id: {
|
||||
type: DataTypes.UUID,
|
||||
defaultValue: DataTypes.UUIDV4,
|
||||
primaryKey: true,
|
||||
},
|
||||
|
||||
amountoriginal: {
|
||||
type: DataTypes.DECIMAL,
|
||||
|
||||
},
|
||||
|
||||
currency: {
|
||||
type: DataTypes.TEXT,
|
||||
|
||||
},
|
||||
|
||||
incomecost: {
|
||||
type: DataTypes.TEXT,
|
||||
|
||||
},
|
||||
|
||||
amountpln: {
|
||||
type: DataTypes.DECIMAL,
|
||||
|
||||
},
|
||||
|
||||
invoicedate: {
|
||||
type: DataTypes.DATEONLY,
|
||||
|
||||
get: function() {
|
||||
return this.getDataValue('invoicedate')
|
||||
? moment
|
||||
.utc(this.getDataValue('invoicedate'))
|
||||
.format('YYYY-MM-DD')
|
||||
: null;
|
||||
},
|
||||
|
||||
},
|
||||
|
||||
period: {
|
||||
type: DataTypes.TEXT,
|
||||
|
||||
},
|
||||
|
||||
description: {
|
||||
type: DataTypes.TEXT,
|
||||
|
||||
},
|
||||
|
||||
importHash: {
|
||||
type: DataTypes.STRING(255),
|
||||
allowNull: true,
|
||||
unique: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
timestamps: true,
|
||||
paranoid: true,
|
||||
freezeTableName: true,
|
||||
},
|
||||
);
|
||||
|
||||
invoices.associate = (db) => {
|
||||
|
||||
db.invoices.belongsTo(db.users, {
|
||||
as: 'createdBy',
|
||||
});
|
||||
|
||||
db.invoices.belongsTo(db.users, {
|
||||
as: 'updatedBy',
|
||||
});
|
||||
};
|
||||
|
||||
return invoices;
|
||||
};
|
||||
|
||||
71
backend/src/db/seeders/20250624212305.js
Normal file
71
backend/src/db/seeders/20250624212305.js
Normal file
@ -0,0 +1,71 @@
|
||||
|
||||
const { v4: uuid } = require("uuid");
|
||||
const db = require('../models');
|
||||
const Sequelize = require('sequelize');
|
||||
const config = require("../../config");
|
||||
|
||||
module.exports = {
|
||||
/**
|
||||
* @param{import("sequelize").QueryInterface} queryInterface
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
async up(queryInterface) {
|
||||
const createdAt = new Date();
|
||||
const updatedAt = new Date();
|
||||
|
||||
/** @type {Map<string, string>} */
|
||||
const idMap = new Map();
|
||||
|
||||
/**
|
||||
* @param {string} key
|
||||
* @return {string}
|
||||
*/
|
||||
function getId(key) {
|
||||
if (idMap.has(key)) {
|
||||
return idMap.get(key);
|
||||
}
|
||||
const id = uuid();
|
||||
idMap.set(key, id);
|
||||
return id;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} name
|
||||
*/
|
||||
function createPermissions(name) {
|
||||
return [
|
||||
{ id: getId(`CREATE_${name.toUpperCase()}`), createdAt, updatedAt, name: `CREATE_${name.toUpperCase()}` },
|
||||
{ id: getId(`READ_${name.toUpperCase()}`), createdAt, updatedAt, name: `READ_${name.toUpperCase()}` },
|
||||
{ id: getId(`UPDATE_${name.toUpperCase()}`), createdAt, updatedAt, name: `UPDATE_${name.toUpperCase()}` },
|
||||
{ id: getId(`DELETE_${name.toUpperCase()}`), createdAt, updatedAt, name: `DELETE_${name.toUpperCase()}` }
|
||||
];
|
||||
}
|
||||
|
||||
const entities = [
|
||||
|
||||
"invoices",
|
||||
|
||||
];
|
||||
|
||||
const createdPermissions = entities.flatMap(createPermissions);
|
||||
|
||||
// Add permissions to database
|
||||
await queryInterface.bulkInsert("permissions", createdPermissions);
|
||||
// Get permissions ids
|
||||
const permissionsIds = createdPermissions.map((p) => p.id);
|
||||
// Get admin role
|
||||
const adminRole = await db.roles.findOne({
|
||||
where: {name: config.roles.super_admin}
|
||||
});
|
||||
|
||||
if (adminRole) {
|
||||
// Add permissions to admin role if it exists
|
||||
await adminRole.addPermissions(permissionsIds);
|
||||
}
|
||||
|
||||
},
|
||||
down: async (queryInterface, Sequelize) => {
|
||||
await queryInterface.bulkDelete("permissions", entities.flatMap(createPermissions));
|
||||
}
|
||||
};
|
||||
|
||||
@ -38,6 +38,8 @@ const permissionsRoutes = require('./routes/permissions');
|
||||
|
||||
const organizationsRoutes = require('./routes/organizations');
|
||||
|
||||
const invoicesRoutes = require('./routes/invoices');
|
||||
|
||||
const getBaseUrl = (url) => {
|
||||
if (!url) return '';
|
||||
return url.endsWith('/api') ? url.slice(0, -4) : url;
|
||||
@ -114,6 +116,8 @@ app.use('/api/permissions', passport.authenticate('jwt', {session: false}), perm
|
||||
|
||||
app.use('/api/organizations', passport.authenticate('jwt', {session: false}), organizationsRoutes);
|
||||
|
||||
app.use('/api/invoices', passport.authenticate('jwt', {session: false}), invoicesRoutes);
|
||||
|
||||
app.use('/api/contact-form', contactFormRoutes);
|
||||
|
||||
app.use(
|
||||
|
||||
428
backend/src/routes/invoices.js
Normal file
428
backend/src/routes/invoices.js
Normal file
@ -0,0 +1,428 @@
|
||||
|
||||
const express = require('express');
|
||||
|
||||
const InvoicesService = require('../services/invoices');
|
||||
const InvoicesDBApi = require('../db/api/invoices');
|
||||
const wrapAsync = require('../helpers').wrapAsync;
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
const { parse } = require('json2csv');
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* components:
|
||||
* schemas:
|
||||
* Invoices:
|
||||
* type: object
|
||||
* properties:
|
||||
|
||||
* currency:
|
||||
* type: string
|
||||
* default: currency
|
||||
* incomecost:
|
||||
* type: string
|
||||
* default: incomecost
|
||||
* period:
|
||||
* type: string
|
||||
* default: period
|
||||
* description:
|
||||
* type: string
|
||||
* default: description
|
||||
|
||||
* amountoriginal:
|
||||
* type: integer
|
||||
* format: int64
|
||||
* amountpln:
|
||||
* type: integer
|
||||
* format: int64
|
||||
|
||||
*/
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* tags:
|
||||
* name: Invoices
|
||||
* description: The Invoices managing API
|
||||
*/
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /api/invoices:
|
||||
* post:
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* tags: [Invoices]
|
||||
* 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/Invoices"
|
||||
* responses:
|
||||
* 200:
|
||||
* description: The item was successfully added
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: "#/components/schemas/Invoices"
|
||||
* 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 InvoicesService.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: [Invoices]
|
||||
* 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/Invoices"
|
||||
* responses:
|
||||
* 200:
|
||||
* description: The items were successfully imported
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: "#/components/schemas/Invoices"
|
||||
* 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 InvoicesService.bulkImport(req, res, true, link.host);
|
||||
const payload = true;
|
||||
res.status(200).send(payload);
|
||||
}));
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /api/invoices/{id}:
|
||||
* put:
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* tags: [Invoices]
|
||||
* 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/Invoices"
|
||||
* required:
|
||||
* - id
|
||||
* responses:
|
||||
* 200:
|
||||
* description: The item data was successfully updated
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* $ref: "#/components/schemas/Invoices"
|
||||
* 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 InvoicesService.update(req.body.data, req.body.id, req.currentUser);
|
||||
const payload = true;
|
||||
res.status(200).send(payload);
|
||||
}));
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /api/invoices/{id}:
|
||||
* delete:
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* tags: [Invoices]
|
||||
* 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/Invoices"
|
||||
* 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 InvoicesService.remove(req.params.id, req.currentUser);
|
||||
const payload = true;
|
||||
res.status(200).send(payload);
|
||||
}));
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /api/invoices/deleteByIds:
|
||||
* post:
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* tags: [Invoices]
|
||||
* 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/Invoices"
|
||||
* 401:
|
||||
* $ref: "#/components/responses/UnauthorizedError"
|
||||
* 404:
|
||||
* description: Items not found
|
||||
* 500:
|
||||
* description: Some server error
|
||||
*/
|
||||
router.post('/deleteByIds', wrapAsync(async (req, res) => {
|
||||
await InvoicesService.deleteByIds(req.body.data, req.currentUser);
|
||||
const payload = true;
|
||||
res.status(200).send(payload);
|
||||
}));
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /api/invoices:
|
||||
* get:
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* tags: [Invoices]
|
||||
* summary: Get all invoices
|
||||
* description: Get all invoices
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Invoices list successfully received
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: array
|
||||
* items:
|
||||
* $ref: "#/components/schemas/Invoices"
|
||||
* 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 InvoicesDBApi.findAll(
|
||||
req.query, { currentUser }
|
||||
);
|
||||
if (filetype && filetype === 'csv') {
|
||||
const fields = ['id','currency','incomecost','period','description',
|
||||
|
||||
'amountoriginal','amountpln',
|
||||
|
||||
'invoicedate',];
|
||||
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/invoices/count:
|
||||
* get:
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* tags: [Invoices]
|
||||
* summary: Count all invoices
|
||||
* description: Count all invoices
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Invoices count successfully received
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: array
|
||||
* items:
|
||||
* $ref: "#/components/schemas/Invoices"
|
||||
* 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 InvoicesDBApi.findAll(
|
||||
req.query,
|
||||
null,
|
||||
{ countOnly: true, currentUser }
|
||||
);
|
||||
|
||||
res.status(200).send(payload);
|
||||
}));
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /api/invoices/autocomplete:
|
||||
* get:
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* tags: [Invoices]
|
||||
* summary: Find all invoices that match search criteria
|
||||
* description: Find all invoices that match search criteria
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Invoices list successfully received
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: array
|
||||
* items:
|
||||
* $ref: "#/components/schemas/Invoices"
|
||||
* 401:
|
||||
* $ref: "#/components/responses/UnauthorizedError"
|
||||
* 404:
|
||||
* description: Data not found
|
||||
* 500:
|
||||
* description: Some server error
|
||||
*/
|
||||
router.get('/autocomplete', async (req, res) => {
|
||||
const payload = await InvoicesDBApi.findAllAutocomplete(
|
||||
req.query.query,
|
||||
req.query.limit,
|
||||
req.query.offset,
|
||||
);
|
||||
|
||||
res.status(200).send(payload);
|
||||
});
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /api/invoices/{id}:
|
||||
* get:
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* tags: [Invoices]
|
||||
* 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/Invoices"
|
||||
* 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 InvoicesDBApi.findBy(
|
||||
{ id: req.params.id },
|
||||
);
|
||||
|
||||
res.status(200).send(payload);
|
||||
}));
|
||||
|
||||
router.use('/', require('../helpers').commonErrorHandler);
|
||||
|
||||
module.exports = router;
|
||||
131
backend/src/services/invoices.js
Normal file
131
backend/src/services/invoices.js
Normal file
@ -0,0 +1,131 @@
|
||||
const db = require('../db/models');
|
||||
const InvoicesDBApi = require('../db/api/invoices');
|
||||
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 InvoicesService {
|
||||
static async create(data, currentUser) {
|
||||
const transaction = await db.sequelize.transaction();
|
||||
try {
|
||||
await InvoicesDBApi.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 InvoicesDBApi.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 invoices = await InvoicesDBApi.findBy(
|
||||
{id},
|
||||
{transaction},
|
||||
);
|
||||
|
||||
if (!invoices) {
|
||||
throw new ValidationError(
|
||||
'invoicesNotFound',
|
||||
);
|
||||
}
|
||||
|
||||
const updatedInvoices = await InvoicesDBApi.update(
|
||||
id,
|
||||
data,
|
||||
{
|
||||
currentUser,
|
||||
transaction,
|
||||
},
|
||||
);
|
||||
|
||||
await transaction.commit();
|
||||
return updatedInvoices;
|
||||
|
||||
} catch (error) {
|
||||
await transaction.rollback();
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
static async deleteByIds(ids, currentUser) {
|
||||
const transaction = await db.sequelize.transaction();
|
||||
|
||||
try {
|
||||
await InvoicesDBApi.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 InvoicesDBApi.remove(
|
||||
id,
|
||||
{
|
||||
currentUser,
|
||||
transaction,
|
||||
},
|
||||
);
|
||||
|
||||
await transaction.commit();
|
||||
} catch (error) {
|
||||
await transaction.rollback();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@ -109,6 +109,18 @@ module.exports = class SearchService {
|
||||
|
||||
],
|
||||
|
||||
"invoices": [
|
||||
|
||||
"currency",
|
||||
|
||||
"incomecost",
|
||||
|
||||
"period",
|
||||
|
||||
"description",
|
||||
|
||||
],
|
||||
|
||||
};
|
||||
const columnsInt = {
|
||||
|
||||
@ -142,6 +154,14 @@ module.exports = class SearchService {
|
||||
|
||||
],
|
||||
|
||||
"invoices": [
|
||||
|
||||
"amountoriginal",
|
||||
|
||||
"amountpln",
|
||||
|
||||
],
|
||||
|
||||
};
|
||||
|
||||
let allFoundRecords = [];
|
||||
|
||||
156
frontend/src/components/Invoices/CardInvoices.tsx
Normal file
156
frontend/src/components/Invoices/CardInvoices.tsx
Normal file
@ -0,0 +1,156 @@
|
||||
import React from 'react';
|
||||
import ListActionsPopover from '../ListActionsPopover';
|
||||
import { useAppSelector } from '../../stores/hooks';
|
||||
import dataFormatter from '../../helpers/dataFormatter';
|
||||
import { Pagination } from '../Pagination';
|
||||
import LoadingSpinner from "../LoadingSpinner";
|
||||
import Link from 'next/link';
|
||||
|
||||
type Props = {
|
||||
invoices: any[];
|
||||
loading: boolean;
|
||||
onDelete: (id: string) => void;
|
||||
currentPage: number;
|
||||
numPages: number;
|
||||
onPageChange: (page: number) => void;
|
||||
};
|
||||
|
||||
const CardInvoices = ({
|
||||
invoices,
|
||||
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);
|
||||
|
||||
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 && invoices.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
|
||||
}`}
|
||||
>
|
||||
<Link href={`/invoices/invoices-view/?id=${item.id}`} className='text-lg font-bold leading-6 line-clamp-1'>
|
||||
{item.id}
|
||||
</Link>
|
||||
|
||||
<div className='ml-auto'>
|
||||
<ListActionsPopover
|
||||
onDelete={onDelete}
|
||||
itemId={item.id}
|
||||
pathEdit={`/invoices/invoices-edit/?id=${item.id}`}
|
||||
pathView={`/invoices/invoices-view/?id=${item.id}`}
|
||||
hasUpdatePermission={true}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<dl className='divide-y 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'>Amountoriginal</dt>
|
||||
<dd className='flex items-start gap-x-2'>
|
||||
<div className='font-medium line-clamp-4'>
|
||||
{ item.amountoriginal }
|
||||
</div>
|
||||
</dd>
|
||||
</div>
|
||||
|
||||
<div className='flex justify-between gap-x-4 py-3'>
|
||||
<dt className='text-gray-500 dark:text-dark-600'>Currency</dt>
|
||||
<dd className='flex items-start gap-x-2'>
|
||||
<div className='font-medium line-clamp-4'>
|
||||
{ item.currency }
|
||||
</div>
|
||||
</dd>
|
||||
</div>
|
||||
|
||||
<div className='flex justify-between gap-x-4 py-3'>
|
||||
<dt className='text-gray-500 dark:text-dark-600'>Incomecost</dt>
|
||||
<dd className='flex items-start gap-x-2'>
|
||||
<div className='font-medium line-clamp-4'>
|
||||
{ item.incomecost }
|
||||
</div>
|
||||
</dd>
|
||||
</div>
|
||||
|
||||
<div className='flex justify-between gap-x-4 py-3'>
|
||||
<dt className='text-gray-500 dark:text-dark-600'>Amountpln</dt>
|
||||
<dd className='flex items-start gap-x-2'>
|
||||
<div className='font-medium line-clamp-4'>
|
||||
{ item.amountpln }
|
||||
</div>
|
||||
</dd>
|
||||
</div>
|
||||
|
||||
<div className='flex justify-between gap-x-4 py-3'>
|
||||
<dt className='text-gray-500 dark:text-dark-600'>Invoicedate</dt>
|
||||
<dd className='flex items-start gap-x-2'>
|
||||
<div className='font-medium line-clamp-4'>
|
||||
{ dataFormatter.dateFormatter(item.invoicedate) }
|
||||
</div>
|
||||
</dd>
|
||||
</div>
|
||||
|
||||
<div className='flex justify-between gap-x-4 py-3'>
|
||||
<dt className='text-gray-500 dark:text-dark-600'>Period</dt>
|
||||
<dd className='flex items-start gap-x-2'>
|
||||
<div className='font-medium line-clamp-4'>
|
||||
{ item.period }
|
||||
</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>
|
||||
|
||||
<div className='flex justify-between gap-x-4 py-3'>
|
||||
<dt className='text-gray-500 dark:text-dark-600'>Attachment</dt>
|
||||
<dd className='flex items-start gap-x-2'>
|
||||
<div className='font-medium line-clamp-4'>
|
||||
{ item.attachment }
|
||||
</div>
|
||||
</dd>
|
||||
</div>
|
||||
|
||||
</dl>
|
||||
</li>
|
||||
))}
|
||||
{!loading && invoices.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 CardInvoices;
|
||||
107
frontend/src/components/Invoices/ListInvoices.tsx
Normal file
107
frontend/src/components/Invoices/ListInvoices.tsx
Normal file
@ -0,0 +1,107 @@
|
||||
import React from 'react';
|
||||
import CardBox from '../CardBox';
|
||||
import dataFormatter from '../../helpers/dataFormatter';
|
||||
import ListActionsPopover from "../ListActionsPopover";
|
||||
import {useAppSelector} from "../../stores/hooks";
|
||||
import {Pagination} from "../Pagination";
|
||||
import LoadingSpinner from "../LoadingSpinner";
|
||||
import Link from 'next/link';
|
||||
|
||||
type Props = {
|
||||
invoices: any[];
|
||||
loading: boolean;
|
||||
onDelete: (id: string) => void;
|
||||
currentPage: number;
|
||||
numPages: number;
|
||||
onPageChange: (page: number) => void;
|
||||
};
|
||||
|
||||
const ListInvoices = ({ invoices, loading, onDelete, currentPage, numPages, onPageChange }: Props) => {
|
||||
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 && invoices.map((item) => (
|
||||
<div key={item.id}>
|
||||
<CardBox hasTable isList className={'rounded shadow-none'}>
|
||||
<div className={`flex rounded dark:bg-dark-900 border items-center overflow-hidden`}>
|
||||
<Link
|
||||
href={`/invoices/invoices-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'}>Amountoriginal</p>
|
||||
<p className={'line-clamp-2'}>{ item.amountoriginal }</p>
|
||||
</div>
|
||||
|
||||
<div className={'flex-1 px-3'}>
|
||||
<p className={'text-xs text-gray-500'}>Currency</p>
|
||||
<p className={'line-clamp-2'}>{ item.currency }</p>
|
||||
</div>
|
||||
|
||||
<div className={'flex-1 px-3'}>
|
||||
<p className={'text-xs text-gray-500'}>Incomecost</p>
|
||||
<p className={'line-clamp-2'}>{ item.incomecost }</p>
|
||||
</div>
|
||||
|
||||
<div className={'flex-1 px-3'}>
|
||||
<p className={'text-xs text-gray-500'}>Amountpln</p>
|
||||
<p className={'line-clamp-2'}>{ item.amountpln }</p>
|
||||
</div>
|
||||
|
||||
<div className={'flex-1 px-3'}>
|
||||
<p className={'text-xs text-gray-500'}>Invoicedate</p>
|
||||
<p className={'line-clamp-2'}>{ dataFormatter.dateFormatter(item.invoicedate) }</p>
|
||||
</div>
|
||||
|
||||
<div className={'flex-1 px-3'}>
|
||||
<p className={'text-xs text-gray-500'}>Period</p>
|
||||
<p className={'line-clamp-2'}>{ item.period }</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>
|
||||
|
||||
<div className={'flex-1 px-3'}>
|
||||
<p className={'text-xs text-gray-500'}>Attachment</p>
|
||||
<p className={'line-clamp-2'}>{ item.attachment }</p>
|
||||
</div>
|
||||
|
||||
</Link>
|
||||
<ListActionsPopover
|
||||
onDelete={onDelete}
|
||||
itemId={item.id}
|
||||
pathEdit={`/invoices/invoices-edit/?id=${item.id}`}
|
||||
pathView={`/invoices/invoices-view/?id=${item.id}`}
|
||||
hasUpdatePermission={true}
|
||||
/>
|
||||
</div>
|
||||
</CardBox>
|
||||
</div>
|
||||
))}
|
||||
{!loading && invoices.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 ListInvoices
|
||||
441
frontend/src/components/Invoices/TableInvoices.tsx
Normal file
441
frontend/src/components/Invoices/TableInvoices.tsx
Normal file
@ -0,0 +1,441 @@
|
||||
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/invoices/invoicesSlice'
|
||||
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 "./configureInvoicesCols";
|
||||
import _ from 'lodash';
|
||||
import dataFormatter from '../../helpers/dataFormatter'
|
||||
import {dataGridStyles} from "../../styles";
|
||||
import axios from 'axios';
|
||||
|
||||
const perPage = 10;
|
||||
|
||||
const TableSampleInvoices = ({ 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 { invoices, loading, count, notify: invoicesNotify, refetch } = useAppSelector((state) => state.invoices)
|
||||
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 (invoicesNotify.showNotification) {
|
||||
notify(invoicesNotify.typeNotification, invoicesNotify.textNotification);
|
||||
}
|
||||
}, [invoicesNotify.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(() => {
|
||||
loadColumns(handleDeleteModalAction, `invoices`).then((newCols) =>
|
||||
setColumns(newCols),
|
||||
);
|
||||
}, []);
|
||||
|
||||
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 border-gray-700 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={invoices ?? []}
|
||||
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 TableSampleInvoices
|
||||
161
frontend/src/components/Invoices/configureInvoicesCols.tsx
Normal file
161
frontend/src/components/Invoices/configureInvoicesCols.tsx
Normal file
@ -0,0 +1,161 @@
|
||||
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 dataFormatter from '../../helpers/dataFormatter'
|
||||
import DataGridMultiSelect from "../DataGridMultiSelect";
|
||||
import ListActionsPopover from '../ListActionsPopover';
|
||||
type Params = (id: string) => void;
|
||||
|
||||
export const loadColumns = async (
|
||||
onDelete: Params,
|
||||
entityName: string,
|
||||
) => {
|
||||
async function callOptionsApi(entityName: string) {
|
||||
try {
|
||||
const data = await axios(`/${entityName}/autocomplete?limit=100`);
|
||||
return data.data;
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
return [
|
||||
|
||||
{
|
||||
field: 'amountoriginal',
|
||||
headerName: 'Amountoriginal',
|
||||
flex: 1,
|
||||
minWidth: 120,
|
||||
filterable: false,
|
||||
headerClassName: 'datagrid--header',
|
||||
cellClassName: 'datagrid--cell',
|
||||
|
||||
editable: true,
|
||||
type: 'number',
|
||||
|
||||
},
|
||||
|
||||
{
|
||||
field: 'currency',
|
||||
headerName: 'Currency',
|
||||
flex: 1,
|
||||
minWidth: 120,
|
||||
filterable: false,
|
||||
headerClassName: 'datagrid--header',
|
||||
cellClassName: 'datagrid--cell',
|
||||
|
||||
editable: true,
|
||||
|
||||
},
|
||||
|
||||
{
|
||||
field: 'incomecost',
|
||||
headerName: 'Incomecost',
|
||||
flex: 1,
|
||||
minWidth: 120,
|
||||
filterable: false,
|
||||
headerClassName: 'datagrid--header',
|
||||
cellClassName: 'datagrid--cell',
|
||||
|
||||
editable: true,
|
||||
|
||||
},
|
||||
|
||||
{
|
||||
field: 'amountpln',
|
||||
headerName: 'Amountpln',
|
||||
flex: 1,
|
||||
minWidth: 120,
|
||||
filterable: false,
|
||||
headerClassName: 'datagrid--header',
|
||||
cellClassName: 'datagrid--cell',
|
||||
|
||||
editable: true,
|
||||
type: 'number',
|
||||
|
||||
},
|
||||
|
||||
{
|
||||
field: 'invoicedate',
|
||||
headerName: 'Invoicedate',
|
||||
flex: 1,
|
||||
minWidth: 120,
|
||||
filterable: false,
|
||||
headerClassName: 'datagrid--header',
|
||||
cellClassName: 'datagrid--cell',
|
||||
|
||||
editable: true,
|
||||
type: 'date',
|
||||
valueGetter: (params: GridValueGetterParams) =>
|
||||
new Date(params.row.invoicedate),
|
||||
|
||||
},
|
||||
|
||||
{
|
||||
field: 'period',
|
||||
headerName: 'Period',
|
||||
flex: 1,
|
||||
minWidth: 120,
|
||||
filterable: false,
|
||||
headerClassName: 'datagrid--header',
|
||||
cellClassName: 'datagrid--cell',
|
||||
|
||||
editable: true,
|
||||
|
||||
},
|
||||
|
||||
{
|
||||
field: 'description',
|
||||
headerName: 'Description',
|
||||
flex: 1,
|
||||
minWidth: 120,
|
||||
filterable: false,
|
||||
headerClassName: 'datagrid--header',
|
||||
cellClassName: 'datagrid--cell',
|
||||
|
||||
editable: true,
|
||||
|
||||
},
|
||||
|
||||
{
|
||||
field: 'attachment',
|
||||
headerName: 'Attachment',
|
||||
flex: 1,
|
||||
minWidth: 120,
|
||||
filterable: false,
|
||||
headerClassName: 'datagrid--header',
|
||||
cellClassName: 'datagrid--cell',
|
||||
|
||||
editable: true,
|
||||
|
||||
},
|
||||
|
||||
{
|
||||
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={`/invoices/invoices-edit/?id=${params?.row?.id}`}
|
||||
pathView={`/invoices/invoices-view/?id=${params?.row?.id}`}
|
||||
hasUpdatePermission={true}
|
||||
/>
|
||||
</div>,
|
||||
]
|
||||
},
|
||||
},
|
||||
];
|
||||
};
|
||||
@ -80,6 +80,14 @@ const menuAside: MenuAsideItem[] = [
|
||||
icon: icon.mdiTable ?? icon.mdiTable,
|
||||
permissions: 'READ_ORGANIZATIONS'
|
||||
},
|
||||
{
|
||||
href: '/invoices/invoices-list',
|
||||
label: 'Invoices',
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
icon: icon.mdiTable ?? icon.mdiTable,
|
||||
permissions: 'READ_INVOICES'
|
||||
},
|
||||
{
|
||||
href: '/profile',
|
||||
label: 'Profile',
|
||||
@ -93,14 +101,6 @@ const menuAside: MenuAsideItem[] = [
|
||||
icon: icon.mdiFileCode,
|
||||
permissions: 'READ_API_DOCS'
|
||||
},
|
||||
{
|
||||
href: '/whats-up',
|
||||
label: "What's Up?",
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
icon: icon.mdiCommentQuestion ?? icon.mdiTable,
|
||||
},
|
||||
|
||||
]
|
||||
|
||||
export default menuAside
|
||||
|
||||
@ -28,10 +28,11 @@ const Dashboard = () => {
|
||||
const [roles, setRoles] = React.useState(loadingMessage);
|
||||
const [permissions, setPermissions] = React.useState(loadingMessage);
|
||||
const [organizations, setOrganizations] = React.useState(loadingMessage);
|
||||
const [invoices, setInvoices] = React.useState(loadingMessage);
|
||||
|
||||
async function loadData() {
|
||||
const entities = ['users','human_resources','inventory','machinery','quality_control','raw_materials','suppliers','work_orders','roles','permissions','organizations',];
|
||||
const fns = [setUsers,setHuman_resources,setInventory,setMachinery,setQuality_control,setRaw_materials,setSuppliers,setWork_orders,setRoles,setPermissions,setOrganizations,];
|
||||
const entities = ['users','human_resources','inventory','machinery','quality_control','raw_materials','suppliers','work_orders','roles','permissions','organizations','invoices',];
|
||||
const fns = [setUsers,setHuman_resources,setInventory,setMachinery,setQuality_control,setRaw_materials,setSuppliers,setWork_orders,setRoles,setPermissions,setOrganizations,setInvoices,];
|
||||
|
||||
const requests = entities.map((entity, index) => {
|
||||
return axios.get(`/${entity.toLowerCase()}/count`);
|
||||
@ -321,6 +322,34 @@ const Dashboard = () => {
|
||||
</div>
|
||||
</Link>
|
||||
|
||||
<Link href={'/invoices/invoices-list'}>
|
||||
<div
|
||||
className={`${corners !== 'rounded-full'? corners : 'rounded-3xl'} dark:bg-dark-900 ${cardsStyle} dark:border-dark-700 p-6`}
|
||||
>
|
||||
<div className="flex justify-between align-center">
|
||||
<div>
|
||||
<div className="text-lg leading-tight text-gray-500 dark:text-gray-400">
|
||||
Invoices
|
||||
</div>
|
||||
<div className="text-3xl leading-tight font-semibold">
|
||||
{invoices}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<BaseIcon
|
||||
className={`${iconsColor}`}
|
||||
w="w-16"
|
||||
h="h-16"
|
||||
size={48}
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
path={icon.mdiTable || icon.mdiTable}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
|
||||
</div>
|
||||
</SectionMain>
|
||||
</>
|
||||
|
||||
206
frontend/src/pages/invoices/[invoicesId].tsx
Normal file
206
frontend/src/pages/invoices/[invoicesId].tsx
Normal file
@ -0,0 +1,206 @@
|
||||
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 { SelectField } from "../../components/SelectField";
|
||||
import { SelectFieldMany } from "../../components/SelectFieldMany";
|
||||
import { SwitchField } from '../../components/SwitchField'
|
||||
import {RichTextField} from "../../components/RichTextField";
|
||||
|
||||
import { update, fetch } from '../../stores/invoices/invoicesSlice'
|
||||
import { useAppDispatch, useAppSelector } from '../../stores/hooks'
|
||||
import { useRouter } from 'next/router'
|
||||
|
||||
const EditInvoices = () => {
|
||||
const router = useRouter()
|
||||
const dispatch = useAppDispatch()
|
||||
const initVals = {
|
||||
|
||||
organizations: null,
|
||||
|
||||
'amountoriginal': '',
|
||||
|
||||
'currency': '',
|
||||
|
||||
'incomecost': '',
|
||||
|
||||
'amountpln': '',
|
||||
|
||||
invoicedate: new Date(),
|
||||
|
||||
'period': '',
|
||||
|
||||
'description': '',
|
||||
|
||||
}
|
||||
const [initialValues, setInitialValues] = useState(initVals)
|
||||
|
||||
const { invoices } = useAppSelector((state) => state.invoices)
|
||||
|
||||
const { invoicesId } = router.query
|
||||
|
||||
useEffect(() => {
|
||||
dispatch(fetch({ id: invoicesId }))
|
||||
}, [invoicesId])
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof invoices === 'object') {
|
||||
setInitialValues(invoices)
|
||||
}
|
||||
}, [invoices])
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof invoices === 'object') {
|
||||
|
||||
const newInitialVal = {...initVals};
|
||||
|
||||
Object.keys(initVals).forEach(el => newInitialVal[el] = (invoices)[el])
|
||||
|
||||
setInitialValues(newInitialVal);
|
||||
}
|
||||
}, [invoices])
|
||||
|
||||
const handleSubmit = async (data) => {
|
||||
await dispatch(update({ id: invoicesId, data }))
|
||||
await router.push('/invoices/invoices-list')
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<title>{getPageTitle('Edit invoices')}</title>
|
||||
</Head>
|
||||
<SectionMain>
|
||||
<SectionTitleLineWithButton icon={mdiChartTimelineVariant} title={'Edit invoices'} main>
|
||||
{''}
|
||||
</SectionTitleLineWithButton>
|
||||
<CardBox>
|
||||
<Formik
|
||||
enableReinitialize
|
||||
initialValues={initialValues}
|
||||
onSubmit={(values) => handleSubmit(values)}
|
||||
>
|
||||
<Form>
|
||||
|
||||
<FormField label='organizations' labelFor='organizations'>
|
||||
<Field
|
||||
name='organizations'
|
||||
id='organizations'
|
||||
component={SelectField}
|
||||
options={initialValues.organizations}
|
||||
itemRef={'organizations'}
|
||||
|
||||
showField={'name'}
|
||||
|
||||
></Field>
|
||||
</FormField>
|
||||
|
||||
<FormField
|
||||
label="Amountoriginal"
|
||||
>
|
||||
<Field
|
||||
type="number"
|
||||
name="amountoriginal"
|
||||
placeholder="Amountoriginal"
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<FormField
|
||||
label="Currency"
|
||||
>
|
||||
<Field
|
||||
name="currency"
|
||||
placeholder="Currency"
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<FormField
|
||||
label="Incomecost"
|
||||
>
|
||||
<Field
|
||||
name="incomecost"
|
||||
placeholder="Incomecost"
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<FormField
|
||||
label="Amountpln"
|
||||
>
|
||||
<Field
|
||||
type="number"
|
||||
name="amountpln"
|
||||
placeholder="Amountpln"
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<FormField
|
||||
label="Invoicedate"
|
||||
>
|
||||
<DatePicker
|
||||
dateFormat="yyyy-MM-dd"
|
||||
selected={initialValues.invoicedate ?
|
||||
new Date(
|
||||
dayjs(initialValues.invoicedate).format('YYYY-MM-DD hh:mm'),
|
||||
) : null
|
||||
}
|
||||
onChange={(date) => setInitialValues({...initialValues, 'invoicedate': date})}
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<FormField
|
||||
label="Period"
|
||||
>
|
||||
<Field
|
||||
name="period"
|
||||
placeholder="Period"
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<FormField
|
||||
label="Description"
|
||||
>
|
||||
<Field
|
||||
name="description"
|
||||
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('/invoices/invoices-list')}/>
|
||||
</BaseButtons>
|
||||
</Form>
|
||||
</Formik>
|
||||
</CardBox>
|
||||
</SectionMain>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
EditInvoices.getLayout = function getLayout(page: ReactElement) {
|
||||
return (
|
||||
<LayoutAuthenticated>
|
||||
{page}
|
||||
</LayoutAuthenticated>
|
||||
)
|
||||
}
|
||||
|
||||
export default EditInvoices
|
||||
204
frontend/src/pages/invoices/invoices-edit.tsx
Normal file
204
frontend/src/pages/invoices/invoices-edit.tsx
Normal file
@ -0,0 +1,204 @@
|
||||
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 { SelectField } from "../../components/SelectField";
|
||||
import { SelectFieldMany } from "../../components/SelectFieldMany";
|
||||
import { SwitchField } from '../../components/SwitchField'
|
||||
import {RichTextField} from "../../components/RichTextField";
|
||||
|
||||
import { update, fetch } from '../../stores/invoices/invoicesSlice'
|
||||
import { useAppDispatch, useAppSelector } from '../../stores/hooks'
|
||||
import { useRouter } from 'next/router'
|
||||
import dataFormatter from '../../helpers/dataFormatter';
|
||||
|
||||
const EditInvoicesPage = () => {
|
||||
const router = useRouter()
|
||||
const dispatch = useAppDispatch()
|
||||
const initVals = {
|
||||
|
||||
organizations: null,
|
||||
|
||||
'amountoriginal': '',
|
||||
|
||||
'currency': '',
|
||||
|
||||
'incomecost': '',
|
||||
|
||||
'amountpln': '',
|
||||
|
||||
invoicedate: new Date(),
|
||||
|
||||
'period': '',
|
||||
|
||||
'description': '',
|
||||
|
||||
}
|
||||
const [initialValues, setInitialValues] = useState(initVals)
|
||||
|
||||
const { invoices } = useAppSelector((state) => state.invoices)
|
||||
|
||||
const { id } = router.query
|
||||
|
||||
useEffect(() => {
|
||||
dispatch(fetch({ id: id }))
|
||||
}, [id])
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof invoices === 'object') {
|
||||
setInitialValues(invoices)
|
||||
}
|
||||
}, [invoices])
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof invoices === 'object') {
|
||||
const newInitialVal = {...initVals};
|
||||
Object.keys(initVals).forEach(el => newInitialVal[el] = (invoices)[el])
|
||||
setInitialValues(newInitialVal);
|
||||
}
|
||||
}, [invoices])
|
||||
|
||||
const handleSubmit = async (data) => {
|
||||
await dispatch(update({ id: id, data }))
|
||||
await router.push('/invoices/invoices-list')
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<title>{getPageTitle('Edit invoices')}</title>
|
||||
</Head>
|
||||
<SectionMain>
|
||||
<SectionTitleLineWithButton icon={mdiChartTimelineVariant} title={'Edit invoices'} main>
|
||||
{''}
|
||||
</SectionTitleLineWithButton>
|
||||
<CardBox>
|
||||
<Formik
|
||||
enableReinitialize
|
||||
initialValues={initialValues}
|
||||
onSubmit={(values) => handleSubmit(values)}
|
||||
>
|
||||
<Form>
|
||||
|
||||
<FormField label='organizations' labelFor='organizations'>
|
||||
<Field
|
||||
name='organizations'
|
||||
id='organizations'
|
||||
component={SelectField}
|
||||
options={initialValues.organizations}
|
||||
itemRef={'organizations'}
|
||||
|
||||
showField={'name'}
|
||||
|
||||
></Field>
|
||||
</FormField>
|
||||
|
||||
<FormField
|
||||
label="Amountoriginal"
|
||||
>
|
||||
<Field
|
||||
type="number"
|
||||
name="amountoriginal"
|
||||
placeholder="Amountoriginal"
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<FormField
|
||||
label="Currency"
|
||||
>
|
||||
<Field
|
||||
name="currency"
|
||||
placeholder="Currency"
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<FormField
|
||||
label="Incomecost"
|
||||
>
|
||||
<Field
|
||||
name="incomecost"
|
||||
placeholder="Incomecost"
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<FormField
|
||||
label="Amountpln"
|
||||
>
|
||||
<Field
|
||||
type="number"
|
||||
name="amountpln"
|
||||
placeholder="Amountpln"
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<FormField
|
||||
label="Invoicedate"
|
||||
>
|
||||
<DatePicker
|
||||
dateFormat="yyyy-MM-dd"
|
||||
selected={initialValues.invoicedate ?
|
||||
new Date(
|
||||
dayjs(initialValues.invoicedate).format('YYYY-MM-DD hh:mm'),
|
||||
) : null
|
||||
}
|
||||
onChange={(date) => setInitialValues({...initialValues, 'invoicedate': date})}
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<FormField
|
||||
label="Period"
|
||||
>
|
||||
<Field
|
||||
name="period"
|
||||
placeholder="Period"
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<FormField
|
||||
label="Description"
|
||||
>
|
||||
<Field
|
||||
name="description"
|
||||
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('/invoices/invoices-list')}/>
|
||||
</BaseButtons>
|
||||
</Form>
|
||||
</Formik>
|
||||
</CardBox>
|
||||
</SectionMain>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
EditInvoicesPage.getLayout = function getLayout(page: ReactElement) {
|
||||
return (
|
||||
<LayoutAuthenticated>
|
||||
{page}
|
||||
</LayoutAuthenticated>
|
||||
)
|
||||
}
|
||||
|
||||
export default EditInvoicesPage
|
||||
130
frontend/src/pages/invoices/invoices-list.tsx
Normal file
130
frontend/src/pages/invoices/invoices-list.tsx
Normal file
@ -0,0 +1,130 @@
|
||||
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 TableInvoices from '../../components/Invoices/TableInvoices'
|
||||
import BaseButton from '../../components/BaseButton'
|
||||
import axios from "axios";
|
||||
import {useAppDispatch, useAppSelector} from "../../stores/hooks";
|
||||
import CardBoxModal from "../../components/CardBoxModal";
|
||||
import DragDropFilePicker from "../../components/DragDropFilePicker";
|
||||
import {setRefetch, uploadCsv} from '../../stores/invoices/invoicesSlice';
|
||||
|
||||
const InvoicesTablesPage = () => {
|
||||
const [filterItems, setFilterItems] = useState([]);
|
||||
const [csvFile, setCsvFile] = useState<File | null>(null);
|
||||
const [isModalActive, setIsModalActive] = useState(false);
|
||||
|
||||
const dispatch = useAppDispatch();
|
||||
|
||||
const [filters] = useState([{label: 'Currency', title: 'currency'},{label: 'Incomecost', title: 'incomecost'},{label: 'Period', title: 'period'},{label: 'Description', title: 'description'},
|
||||
|
||||
{label: 'Amountoriginal', title: 'amountoriginal', number: 'true'},{label: 'Amountpln', title: 'amountpln', number: 'true'},
|
||||
|
||||
]);
|
||||
const addFilter = () => {
|
||||
const newItem = {
|
||||
id: uniqueId(),
|
||||
fields: {
|
||||
filterValue: '',
|
||||
filterValueFrom: '',
|
||||
filterValueTo: '',
|
||||
selectedField: '',
|
||||
},
|
||||
};
|
||||
newItem.fields.selectedField = filters[0].title;
|
||||
setFilterItems([...filterItems, newItem]);
|
||||
};
|
||||
|
||||
const getInvoicesCSV = async () => {
|
||||
const response = await axios({url: '/invoices?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 = 'invoicesCSV.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('Invoices')}</title>
|
||||
</Head>
|
||||
<SectionMain>
|
||||
<SectionTitleLineWithButton icon={mdiChartTimelineVariant} title="Invoices" main>
|
||||
{''}
|
||||
</SectionTitleLineWithButton>
|
||||
<CardBox className='mb-6' cardBoxClassName='flex flex-wrap'>
|
||||
<BaseButton className={'mr-3'} href={'/invoices/invoices-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={getInvoicesCSV} />
|
||||
<BaseButton
|
||||
color='info'
|
||||
label='Upload CSV'
|
||||
onClick={() => setIsModalActive(true)}
|
||||
/>
|
||||
<div className='md:inline-flex items-center ms-auto'>
|
||||
<div id='delete-rows-button'></div>
|
||||
</div>
|
||||
</CardBox>
|
||||
<CardBox className="mb-6" hasTable>
|
||||
<TableInvoices
|
||||
filterItems={filterItems}
|
||||
setFilterItems={setFilterItems}
|
||||
filters={filters}
|
||||
showGrid={false}
|
||||
/>
|
||||
</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>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
InvoicesTablesPage.getLayout = function getLayout(page: ReactElement) {
|
||||
return (
|
||||
<LayoutAuthenticated>
|
||||
{page}
|
||||
</LayoutAuthenticated>
|
||||
)
|
||||
}
|
||||
|
||||
export default InvoicesTablesPage
|
||||
165
frontend/src/pages/invoices/invoices-new.tsx
Normal file
165
frontend/src/pages/invoices/invoices-new.tsx
Normal file
@ -0,0 +1,165 @@
|
||||
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 FormCheckRadio from '../../components/FormCheckRadio'
|
||||
import FormCheckRadioGroup from '../../components/FormCheckRadioGroup'
|
||||
import { SwitchField } from '../../components/SwitchField'
|
||||
|
||||
import { SelectField } from '../../components/SelectField'
|
||||
import {RichTextField} from "../../components/RichTextField";
|
||||
|
||||
import { create } from '../../stores/invoices/invoicesSlice'
|
||||
import { useAppDispatch } from '../../stores/hooks'
|
||||
import { useRouter } from 'next/router'
|
||||
|
||||
const initialValues = {
|
||||
|
||||
organizations: '',
|
||||
|
||||
amountoriginal: '',
|
||||
|
||||
currency: '',
|
||||
|
||||
incomecost: '',
|
||||
|
||||
amountpln: '',
|
||||
|
||||
invoicedate: '',
|
||||
dateInvoicedate: '',
|
||||
|
||||
period: '',
|
||||
|
||||
description: '',
|
||||
|
||||
}
|
||||
|
||||
const InvoicesNew = () => {
|
||||
const router = useRouter()
|
||||
const dispatch = useAppDispatch()
|
||||
|
||||
const handleSubmit = async (data) => {
|
||||
await dispatch(create(data))
|
||||
await router.push('/invoices/invoices-list')
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<title>{getPageTitle('New Item')}</title>
|
||||
</Head>
|
||||
<SectionMain>
|
||||
<SectionTitleLineWithButton icon={mdiChartTimelineVariant} title="New Item" main>
|
||||
{''}
|
||||
</SectionTitleLineWithButton>
|
||||
<CardBox>
|
||||
<Formik
|
||||
initialValues={
|
||||
initialValues
|
||||
}
|
||||
onSubmit={(values) => handleSubmit(values)}
|
||||
>
|
||||
<Form>
|
||||
|
||||
<FormField label="organizations" labelFor="organizations">
|
||||
<Field name="organizations" id="organizations" component={SelectField} options={[]} itemRef={'organizations'}></Field>
|
||||
</FormField>
|
||||
|
||||
<FormField
|
||||
label="Amountoriginal"
|
||||
>
|
||||
<Field
|
||||
type="number"
|
||||
name="amountoriginal"
|
||||
placeholder="Amountoriginal"
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<FormField
|
||||
label="Currency"
|
||||
>
|
||||
<Field
|
||||
name="currency"
|
||||
placeholder="Currency"
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<FormField
|
||||
label="Incomecost"
|
||||
>
|
||||
<Field
|
||||
name="incomecost"
|
||||
placeholder="Incomecost"
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<FormField
|
||||
label="Amountpln"
|
||||
>
|
||||
<Field
|
||||
type="number"
|
||||
name="amountpln"
|
||||
placeholder="Amountpln"
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<FormField
|
||||
label="Invoicedate"
|
||||
>
|
||||
<Field
|
||||
type="date"
|
||||
name="invoicedate"
|
||||
placeholder="Invoicedate"
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<FormField
|
||||
label="Period"
|
||||
>
|
||||
<Field
|
||||
name="period"
|
||||
placeholder="Period"
|
||||
/>
|
||||
</FormField>
|
||||
|
||||
<FormField
|
||||
label="Description"
|
||||
>
|
||||
<Field
|
||||
name="description"
|
||||
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('/invoices/invoices-list')}/>
|
||||
</BaseButtons>
|
||||
</Form>
|
||||
</Formik>
|
||||
</CardBox>
|
||||
</SectionMain>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
InvoicesNew.getLayout = function getLayout(page: ReactElement) {
|
||||
return (
|
||||
<LayoutAuthenticated>
|
||||
{page}
|
||||
</LayoutAuthenticated>
|
||||
)
|
||||
}
|
||||
|
||||
export default InvoicesNew
|
||||
131
frontend/src/pages/invoices/invoices-table.tsx
Normal file
131
frontend/src/pages/invoices/invoices-table.tsx
Normal file
@ -0,0 +1,131 @@
|
||||
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 TableInvoices from '../../components/Invoices/TableInvoices'
|
||||
import BaseButton from '../../components/BaseButton'
|
||||
import axios from "axios";
|
||||
import {useAppDispatch, useAppSelector} from "../../stores/hooks";
|
||||
import CardBoxModal from "../../components/CardBoxModal";
|
||||
import DragDropFilePicker from "../../components/DragDropFilePicker";
|
||||
import {setRefetch, uploadCsv} from '../../stores/invoices/invoicesSlice';
|
||||
|
||||
const InvoicesTablesPage = () => {
|
||||
const [filterItems, setFilterItems] = useState([]);
|
||||
const [csvFile, setCsvFile] = useState<File | null>(null);
|
||||
const [isModalActive, setIsModalActive] = useState(false);
|
||||
|
||||
const dispatch = useAppDispatch();
|
||||
|
||||
const [filters] = useState([{label: 'Currency', title: 'currency'},{label: 'Incomecost', title: 'incomecost'},{label: 'Period', title: 'period'},{label: 'Description', title: 'description'},
|
||||
|
||||
{label: 'Amountoriginal', title: 'amountoriginal', number: 'true'},{label: 'Amountpln', title: 'amountpln', number: 'true'},
|
||||
|
||||
]);
|
||||
const addFilter = () => {
|
||||
const newItem = {
|
||||
id: uniqueId(),
|
||||
fields: {
|
||||
filterValue: '',
|
||||
filterValueFrom: '',
|
||||
filterValueTo: '',
|
||||
selectedField: '',
|
||||
},
|
||||
};
|
||||
newItem.fields.selectedField = filters[0].title;
|
||||
setFilterItems([...filterItems, newItem]);
|
||||
};
|
||||
|
||||
const getInvoicesCSV = async () => {
|
||||
const response = await axios({url: '/invoices?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 = 'invoicesCSV.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('Invoices')}</title>
|
||||
</Head>
|
||||
<SectionMain>
|
||||
<SectionTitleLineWithButton icon={mdiChartTimelineVariant} title="Invoices" main>
|
||||
{''}
|
||||
</SectionTitleLineWithButton>
|
||||
<CardBox className='mb-6' cardBoxClassName='flex flex-wrap'>
|
||||
<BaseButton className={'mr-3'} href={'/invoices/invoices-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={getInvoicesCSV} />
|
||||
<BaseButton
|
||||
color='info'
|
||||
label='Upload CSV'
|
||||
onClick={() => setIsModalActive(true)}
|
||||
/>
|
||||
<div className='md:inline-flex items-center ms-auto'>
|
||||
<div id='delete-rows-button'></div>
|
||||
</div>
|
||||
</CardBox>
|
||||
<CardBox className="mb-6" hasTable>
|
||||
<TableInvoices
|
||||
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>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
InvoicesTablesPage.getLayout = function getLayout(page: ReactElement) {
|
||||
return (
|
||||
<LayoutAuthenticated>
|
||||
{page}
|
||||
</LayoutAuthenticated>
|
||||
)
|
||||
}
|
||||
|
||||
export default InvoicesTablesPage
|
||||
125
frontend/src/pages/invoices/invoices-view.tsx
Normal file
125
frontend/src/pages/invoices/invoices-view.tsx
Normal file
@ -0,0 +1,125 @@
|
||||
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/invoices/invoicesSlice'
|
||||
import dataFormatter from '../../helpers/dataFormatter';
|
||||
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 InvoicesView = () => {
|
||||
const router = useRouter()
|
||||
const dispatch = useAppDispatch()
|
||||
const { invoices } = useAppSelector((state) => state.invoices)
|
||||
|
||||
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 invoices')}</title>
|
||||
</Head>
|
||||
<SectionMain>
|
||||
<SectionTitleLineWithButton icon={mdiChartTimelineVariant} title={removeLastCharacter('View invoices')} main>
|
||||
<BaseButton
|
||||
color='info'
|
||||
label='Edit'
|
||||
href={`/invoices/invoices-edit/?id=${id}`}
|
||||
/>
|
||||
</SectionTitleLineWithButton>
|
||||
<CardBox>
|
||||
|
||||
<div className={'mb-4'}>
|
||||
<p className={'block font-bold mb-2'}>organizations</p>
|
||||
|
||||
<p>{invoices?.organizations?.name ?? 'No data'}</p>
|
||||
|
||||
</div>
|
||||
|
||||
<div className={'mb-4'}>
|
||||
<p className={'block font-bold mb-2'}>Amountoriginal</p>
|
||||
<p>{invoices?.amountoriginal || 'No data'}</p>
|
||||
</div>
|
||||
|
||||
<div className={'mb-4'}>
|
||||
<p className={'block font-bold mb-2'}>Currency</p>
|
||||
<p>{invoices?.currency}</p>
|
||||
</div>
|
||||
|
||||
<div className={'mb-4'}>
|
||||
<p className={'block font-bold mb-2'}>Incomecost</p>
|
||||
<p>{invoices?.incomecost}</p>
|
||||
</div>
|
||||
|
||||
<div className={'mb-4'}>
|
||||
<p className={'block font-bold mb-2'}>Amountpln</p>
|
||||
<p>{invoices?.amountpln || 'No data'}</p>
|
||||
</div>
|
||||
|
||||
<FormField label='Invoicedate'>
|
||||
{invoices.invoicedate ? (
|
||||
<DatePicker
|
||||
dateFormat="yyyy-MM-dd"
|
||||
showTimeSelect
|
||||
selected={invoices.invoicedate ?
|
||||
new Date(
|
||||
dayjs(invoices.invoicedate).format('YYYY-MM-DD hh:mm'),
|
||||
) : null
|
||||
}
|
||||
disabled
|
||||
/>
|
||||
) : <p>No Invoicedate</p>}
|
||||
</FormField>
|
||||
|
||||
<div className={'mb-4'}>
|
||||
<p className={'block font-bold mb-2'}>Period</p>
|
||||
<p>{invoices?.period}</p>
|
||||
</div>
|
||||
|
||||
<div className={'mb-4'}>
|
||||
<p className={'block font-bold mb-2'}>Description</p>
|
||||
<p>{invoices?.description}</p>
|
||||
</div>
|
||||
|
||||
<BaseDivider />
|
||||
|
||||
<BaseButton
|
||||
color='info'
|
||||
label='Back'
|
||||
onClick={() => router.push('/invoices/invoices-list')}
|
||||
/>
|
||||
</CardBox>
|
||||
</SectionMain>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
InvoicesView.getLayout = function getLayout(page: ReactElement) {
|
||||
return (
|
||||
<LayoutAuthenticated>
|
||||
{page}
|
||||
</LayoutAuthenticated>
|
||||
)
|
||||
}
|
||||
|
||||
export default InvoicesView;
|
||||
@ -444,6 +444,75 @@ const OrganizationsView = () => {
|
||||
</CardBox>
|
||||
</>
|
||||
|
||||
<>
|
||||
<p className={'block font-bold mb-2'}>Invoices organizations</p>
|
||||
<CardBox
|
||||
className='mb-6 border border-gray-300 rounded overflow-hidden'
|
||||
hasTable
|
||||
>
|
||||
<div className='overflow-x-auto'>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
|
||||
<th>Amountoriginal</th>
|
||||
|
||||
<th>Currency</th>
|
||||
|
||||
<th>Incomecost</th>
|
||||
|
||||
<th>Amountpln</th>
|
||||
|
||||
<th>Invoicedate</th>
|
||||
|
||||
<th>Period</th>
|
||||
|
||||
<th>Description</th>
|
||||
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{organizations.invoices_organizations && Array.isArray(organizations.invoices_organizations) &&
|
||||
organizations.invoices_organizations.map((item: any) => (
|
||||
<tr key={item.id} onClick={() => router.push(`/invoices/invoices-view/?id=${item.id}`)}>
|
||||
|
||||
<td data-label="amountoriginal">
|
||||
{ item.amountoriginal }
|
||||
</td>
|
||||
|
||||
<td data-label="currency">
|
||||
{ item.currency }
|
||||
</td>
|
||||
|
||||
<td data-label="incomecost">
|
||||
{ item.incomecost }
|
||||
</td>
|
||||
|
||||
<td data-label="amountpln">
|
||||
{ item.amountpln }
|
||||
</td>
|
||||
|
||||
<td data-label="invoicedate">
|
||||
{ dataFormatter.dateFormatter(item.invoicedate) }
|
||||
</td>
|
||||
|
||||
<td data-label="period">
|
||||
{ item.period }
|
||||
</td>
|
||||
|
||||
<td data-label="description">
|
||||
{ item.description }
|
||||
</td>
|
||||
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{!organizations?.invoices_organizations?.length && <div className={'text-center py-4'}>No data</div>}
|
||||
</CardBox>
|
||||
</>
|
||||
|
||||
<BaseDivider />
|
||||
|
||||
<BaseButton
|
||||
|
||||
229
frontend/src/stores/invoices/invoicesSlice.ts
Normal file
229
frontend/src/stores/invoices/invoicesSlice.ts
Normal file
@ -0,0 +1,229 @@
|
||||
import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit'
|
||||
import axios from 'axios'
|
||||
import {fulfilledNotify, rejectNotify, resetNotify} from "../../helpers/notifyStateHandler";
|
||||
|
||||
interface MainState {
|
||||
invoices: any
|
||||
loading: boolean
|
||||
count: number
|
||||
refetch: boolean;
|
||||
rolesWidgets: any[];
|
||||
notify: {
|
||||
showNotification: boolean
|
||||
textNotification: string
|
||||
typeNotification: string
|
||||
}
|
||||
}
|
||||
|
||||
const initialState: MainState = {
|
||||
invoices: [],
|
||||
loading: false,
|
||||
count: 0,
|
||||
refetch: false,
|
||||
rolesWidgets: [],
|
||||
notify: {
|
||||
showNotification: false,
|
||||
textNotification: '',
|
||||
typeNotification: 'warn',
|
||||
},
|
||||
}
|
||||
|
||||
export const fetch = createAsyncThunk('invoices/fetch', async (data: any) => {
|
||||
const { id, query } = data
|
||||
const result = await axios.get(
|
||||
`invoices${
|
||||
query || (id ? `/${id}` : '')
|
||||
}`
|
||||
)
|
||||
return id ? result.data : {rows: result.data.rows, count: result.data.count};
|
||||
})
|
||||
|
||||
export const deleteItemsByIds = createAsyncThunk(
|
||||
'invoices/deleteByIds',
|
||||
async (data: any, { rejectWithValue }) => {
|
||||
try {
|
||||
await axios.post('invoices/deleteByIds', { data });
|
||||
} catch (error) {
|
||||
if (!error.response) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
return rejectWithValue(error.response.data);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
export const deleteItem = createAsyncThunk('invoices/deleteInvoices', async (id: string, { rejectWithValue }) => {
|
||||
try {
|
||||
await axios.delete(`invoices/${id}`)
|
||||
} catch (error) {
|
||||
if (!error.response) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
return rejectWithValue(error.response.data);
|
||||
}
|
||||
})
|
||||
|
||||
export const create = createAsyncThunk('invoices/createInvoices', async (data: any, { rejectWithValue }) => {
|
||||
try {
|
||||
const result = await axios.post(
|
||||
'invoices',
|
||||
{ data }
|
||||
)
|
||||
return result.data
|
||||
} catch (error) {
|
||||
if (!error.response) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
return rejectWithValue(error.response.data);
|
||||
}
|
||||
})
|
||||
|
||||
export const uploadCsv = createAsyncThunk(
|
||||
'invoices/uploadCsv',
|
||||
async (file: File, { rejectWithValue }) => {
|
||||
try {
|
||||
const data = new FormData();
|
||||
data.append('file', file);
|
||||
data.append('filename', file.name);
|
||||
|
||||
const result = await axios.post('invoices/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('invoices/updateInvoices', async (payload: any, { rejectWithValue }) => {
|
||||
try {
|
||||
const result = await axios.put(
|
||||
`invoices/${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 invoicesSlice = createSlice({
|
||||
name: 'invoices',
|
||||
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.invoices = action.payload.rows;
|
||||
state.count = action.payload.count;
|
||||
} else {
|
||||
state.invoices = 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, 'Invoices 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, `${'Invoices'.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, `${'Invoices'.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, `${'Invoices'.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, 'Invoices 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 } = invoicesSlice.actions
|
||||
|
||||
export default invoicesSlice.reducer
|
||||
@ -14,6 +14,7 @@ import work_ordersSlice from "./work_orders/work_ordersSlice";
|
||||
import rolesSlice from "./roles/rolesSlice";
|
||||
import permissionsSlice from "./permissions/permissionsSlice";
|
||||
import organizationsSlice from "./organizations/organizationsSlice";
|
||||
import invoicesSlice from "./invoices/invoicesSlice";
|
||||
|
||||
export const store = configureStore({
|
||||
reducer: {
|
||||
@ -32,6 +33,7 @@ work_orders: work_ordersSlice,
|
||||
roles: rolesSlice,
|
||||
permissions: permissionsSlice,
|
||||
organizations: organizationsSlice,
|
||||
invoices: invoicesSlice,
|
||||
},
|
||||
})
|
||||
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user