Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

client backend and frontend done #851

Merged
merged 1 commit into from
Nov 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions backend/src/controllers/appControllers/clientController/create.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
const mongoose = require('mongoose');

const Model = mongoose.model('Client');
const People = mongoose.model('People');
const Company = mongoose.model('Company');

const create = async (req, res) => {
// Creating a new document in the collection

if (req.body.type === 'people') {
if (!req.body.people) {
return res.status(403).json({
success: false,
message: 'Please select a person',
});
} else {
let { firstname, lastname } = await People.findOne({
_id: req.body.people,
removed: false,
}).exec();
req.body.name = firstname + ' ' + lastname;
req.body.company = undefined;
}
} else {
if (!req.body.company) {
return res.status(403).json({
success: false,
message: 'Please select a company',
});
} else {
let { name } = await Company.findOne({
_id: req.body.company,
removed: false,
}).exec();
req.body.name = name;
req.body.people = undefined;
}
}

req.body.removed = false;
const result = await new Model(req.body).save();

// Returning successfull response
return res.status(200).json({
success: true,
result,
message: 'Successfully Created the document in Model ',
});
};

module.exports = create;
12 changes: 12 additions & 0 deletions backend/src/controllers/appControllers/clientController/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,22 @@ const createCRUDController = require('@/controllers/middlewaresControllers/creat
const remove = require('./remove');
const summary = require('./summary');

const create = require('./create');
const read = require('./read');
const search = require('./search');

const listAll = require('./listAll');
const paginatedList = require('./paginatedList');

function modelController() {
const methods = createCRUDController('Client');
methods.delete = remove;
methods.summary = summary;
methods.create = create;
methods.read = read;
methods.search = search;
methods.list = paginatedList;
methods.listAll = listAll;
return methods;
}

Expand Down
29 changes: 29 additions & 0 deletions backend/src/controllers/appControllers/clientController/listAll.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
const { migrate } = require('./migrate');

const mongoose = require('mongoose');

const Model = mongoose.model('Client');

const listAll = async (req, res) => {
const sort = parseInt(req.query.sort) || 'desc';

// Query the database for a list of all results
const result = await Model.find({ removed: false }).sort({ created: sort }).populate().exec();

const migratedData = result.map((x) => migrate(x));
if (result.length > 0) {
return res.status(200).json({
success: true,
result: migratedData,
message: 'Successfully found all documents',
});
} else {
return res.status(203).json({
success: false,
result: [],
message: 'Collection is Empty',
});
}
};

module.exports = listAll;
15 changes: 15 additions & 0 deletions backend/src/controllers/appControllers/clientController/migrate.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
exports.migrate = (result) => {
const client = result.type === 'people' ? result.people : result.company;
let newData = {};
newData._id = result._id;
newData.type = result.type;
newData.name = result.name;
newData.phone = client.phone;
newData.email = client.email;
newData.website = client.website;
newData.country = client.country;
newData.address = client.address;
newData.people = result.people;
newData.company = result.company;
return newData;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
const { migrate } = require('./migrate');
const mongoose = require('mongoose');

const Model = mongoose.model('Client');

const paginatedList = async (req, res) => {
const page = req.query.page || 1;

const limit = parseInt(req.query.items) || 10;
const skip = page * limit - limit;

// Query the database for a list of all results
const resultsPromise = Model.find({ removed: false })
.skip(skip)
.limit(limit)
.sort({ created: 'desc' })
.populate()
.exec();

// Counting the total documents
const countPromise = Model.countDocuments({ removed: false });
// Resolving both promises
const [result, count] = await Promise.all([resultsPromise, countPromise]);
// console.log('🚀 ~ file: paginatedList.js:23 ~ paginatedList ~ result:', result);

// Calculating total pages
const pages = Math.ceil(count / limit);

const pagination = { page, pages, count };
if (count > 0) {
const migratedData = result.map((x) => migrate(x));
// console.log('🚀 ~ file: paginatedList.js:23 ~ paginatedList ~ migratedData:', migratedData);
return res.status(200).json({
success: true,
result: migratedData,
pagination,
message: 'Successfully found all documents',
});
} else {
return res.status(203).json({
success: false,
result: [],
pagination,
message: 'Collection is Empty',
});
}
};

module.exports = paginatedList;
29 changes: 29 additions & 0 deletions backend/src/controllers/appControllers/clientController/read.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
const { migrate } = require('./migrate');
const mongoose = require('mongoose');

const Model = mongoose.model('Client');

const read = async (req, res) => {
// Find document by id
let result = await Model.findOne({ _id: req.params.id, removed: false }).exec();
// If no results found, return document not found
if (!result) {
return res.status(404).json({
success: false,
result: null,
message: 'No document found by this id: ' + req.params.id,
});
} else {
// Return success resposne

const migratedData = migrate(result);

return res.status(200).json({
success: true,
result: migratedData,
message: 'we found this document by this id: ' + req.params.id,
});
}
};

module.exports = read;
51 changes: 51 additions & 0 deletions backend/src/controllers/appControllers/clientController/search.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
const { migrate } = require('./migrate');
const mongoose = require('mongoose');

const Model = mongoose.model('Client');

const search = async (req, res) => {
// console.log(req.query.fields)
if (req.query.q === undefined || req.query.q.trim() === '') {
return res
.status(202)
.json({
success: false,
result: [],
message: 'No document found by this request',
})
.end();
}
const fieldsArray = req.query.fields
? req.query.fields.split(',')
: ['name', 'surname', 'birthday'];

const fields = { $or: [] };

for (const field of fieldsArray) {
fields.$or.push({ [field]: { $regex: new RegExp(req.query.q, 'i') } });
}
// console.log(fields)

let results = await Model.find(fields).where('removed', false).limit(10).exec();

const migratedData = results.map((x) => migrate(x));

if (results.length >= 1) {
return res.status(200).json({
success: true,
result: migratedData,
message: 'Successfully found all documents',
});
} else {
return res
.status(202)
.json({
success: false,
result: [],
message: 'No document found by this request',
})
.end();
}
};

module.exports = search;
22 changes: 22 additions & 0 deletions backend/src/controllers/appControllers/companyController/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
const mongoose = require('mongoose');
const { modelsFiles } = require('@/models/utils');
const createCRUDController = require('@/controllers/middlewaresControllers/createCRUDController');

const remove = require('./remove');

function modelController() {
const modelName = 'Company';

if (!modelsFiles.includes(modelName)) {
throw new Error(`Model ${modelName} does not exist`);
} else {
const Model = mongoose.model(modelName);
const methods = createCRUDController(modelName);

methods.delete = (req, res) => remove(Model, req, res);

return methods;
}
}

module.exports = modelController();
52 changes: 52 additions & 0 deletions backend/src/controllers/appControllers/companyController/remove.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
const mongoose = require('mongoose');

const Client = mongoose.model('Client');
const People = mongoose.model('People');

const remove = async (Model, req, res) => {
// cannot delete client it it have one invoice or Client:
// check if client have invoice or quotes:
const { id } = req.params;
console.log('🚀 ~ companyController: remove.js:10 ~ remove ~ id:', id);

// first find if there alt least one quote or invoice exist corresponding to the client
const client = await Client.findOne({ company: id, removed: false }).exec();
if (client) {
return res.status(400).json({
success: false,
result: null,
message: 'Cannot delete company if company attached to any people or she is client',
});
}
const people = await People.findOne({ company: id, removed: false }).exec();
if (people) {
return res.status(400).json({
success: false,
result: null,
message: 'Cannot delete company if company attached to any people or she is client',
});
}

// if no People or quote, delete the client
const result = await Model.findOneAndUpdate(
{ _id: id, removed: false },
{
$set: {
removed: true,
},
}
).exec();
if (!result) {
return res.status(404).json({
success: false,
result: null,
message: 'No people found by this id: ' + id,
});
}
return res.status(200).json({
success: true,
result,
message: 'Successfully Deleted the people by id: ' + id,
});
};
module.exports = remove;
12 changes: 8 additions & 4 deletions backend/src/controllers/appControllers/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,23 @@ const controllerDirectories = globSync(pattern).map((filePath) => {

const appControllers = () => {
const controllers = {};
const hasCustomeControllers = [];
const hasCustomControllers = [];

controllerDirectories.forEach((controllerName) => {
try {
const customController = require('@/controllers/appControllers/' + controllerName);

if (customController) {
hasCustomeControllers.push(controllerName);
hasCustomControllers.push(controllerName);
controllers[controllerName] = customController;
}
} catch (err) {}
} catch (err) {
throw new Error(err.message);
}
});

routesList.forEach(({ modelName, controllerName }) => {
if (!hasCustomeControllers.includes(controllerName)) {
if (!hasCustomControllers.includes(controllerName)) {
controllers[controllerName] = createCRUDController(modelName);
}
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ const paginatedList = async (req, res) => {
.skip(skip)
.limit(limit)
.sort({ created: 'desc' })
.populate('createdBy', 'name');
.populate('createdBy', 'name')
.exec();
// Counting the total documents
const countPromise = Model.countDocuments({ removed: false });
// Resolving both promises
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,9 @@ const Model = mongoose.model('Invoice');

const read = async (req, res) => {
// Find document by id
const result = await Model.findOne({ _id: req.params.id, removed: false }).populate(
'createdBy',
'name'
);
const result = await Model.findOne({ _id: req.params.id, removed: false })
.populate('createdBy', 'name')
.exec();
// If no results found, return document not found
if (!result) {
return res.status(404).json({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ const paginatedList = async (req, res) => {
.skip(skip)
.limit(limit)
.sort({ created: 'desc' })
.populate('createdBy', 'name');
.populate('createdBy', 'name')
.exec();
// Counting the total documents
const countPromise = Model.countDocuments({ removed: false });
// Resolving both promises
Expand Down
Loading