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

Backend: invoice upload #32

Open
wants to merge 32 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
84b6ebd
Lowercase import names & uppercase file name
Apr 30, 2019
16c40e9
Create Company model
Apr 30, 2019
7ce84ab
Create Category model
Apr 30, 2019
af5dc88
Create graphql types Category & Company
Apr 30, 2019
37b3222
Add category & company to Transaction
Apr 30, 2019
f33bc2a
Add InvoiceUpload & CompanyInput
Apr 30, 2019
b10b1cd
Add invoice upload validation & make the validation components more r…
May 2, 2019
fcd5d6b
Implement upload invoice resolver
May 2, 2019
0694119
Test register input validation
May 2, 2019
0d7d107
Better error handling & password test
May 2, 2019
5f882cf
Add env variable to set maximum characters allowed for strings
May 2, 2019
76f509c
Inject validation module
May 2, 2019
78ba2fe
Test max length for strings
May 2, 2019
55f6aee
Test updateProfileValidtion & expenseValidation
May 2, 2019
5bc435e
Test validation of upload invoice inputs
May 2, 2019
720102e
Add more tests for register endpoint
May 3, 2019
e7ea283
Test update profile
May 3, 2019
baf3a88
Test invoice upload
May 3, 2019
6a13af8
Add constants & improve test a bit
May 6, 2019
66a9eb6
Generate an invoice as pdf
May 6, 2019
48fa906
Add ref field
May 7, 2019
773f9b8
Create Counter collection
May 7, 2019
29db764
Create function to retrieve incremented invoice ref
May 7, 2019
c7f5eaf
Fix typo
May 7, 2019
1600ab1
Create types related to invoice generation
May 7, 2019
b67a6d1
Implement generateInvoice resolver & change store function behavior
May 7, 2019
e583b3b
Modify pdf template
May 7, 2019
49eeb34
Add generateInvoiceInputValidation & refine some resolvers
May 7, 2019
1f55baa
Clean Company & Counter test data
May 7, 2019
ed81504
Test generate invoice
May 7, 2019
1511e2c
Test generate invoice validation
May 7, 2019
7650f43
Change filename invoiceGen -> invoiceFactory & import name invoiceGen…
May 7, 2019
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
256 changes: 181 additions & 75 deletions backend/package-lock.json

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
"dotenv": "^7.0.0",
"express": "^4.16.4",
"graphql": "^14.1.1",
"html-pdf": "^2.2.0",
"indicative": "^5.0.8",
"jsonwebtoken": "^8.5.1",
"mongoose": "^5.4.19"
Expand Down
18 changes: 18 additions & 0 deletions backend/src/constants.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
exports.TR_FLOW = {
IN: 'IN',
OUT: 'OUT'
};

exports.TR_TYPE = {
INVOICE: 'INVOICE',
EXPENSE: 'EXPENSE'
};

exports.STORAGE_PATH = {
INVOICE_PENDING: '/invoices/pending',
INVOICE_PAID: '/invoices/paid',
INVOICE_REJECTED: '/invoices/rejected',
EXPENSE_PENDING: '/expenses/pending',
EXPENSE_PAID: '/expenses/paid',
EXPENSE_REJECTED: '/expenses/rejected'
};
2 changes: 2 additions & 0 deletions backend/src/db.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ module.exports.connect = async () => {
await mongoose.connection.createCollection('users');
await mongoose.connection.createCollection('transactions');
await mongoose.connection.createCollection('categories');
await mongoose.connection.createCollection('companies');
await mongoose.connection.createCollection('counters');
console.log('Collections created successfully!');
})
.catch(err => {
Expand Down
154 changes: 129 additions & 25 deletions backend/src/graphql/resolvers/mutations.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,45 @@
const {
validate,
registerValidation,
updateProfileValidation,
expenseValidation
} = require('../../lib/validation');

const store = (file, tags, folder, cloudinary) =>
const saveOrRetrieveCompany = async (company, Company, upsert) => {
if (!company) return null;
const { name, id } = company;
if (!name && !id) return null;
if (company.id) {
return Company.findById(id);
}
if (company) {
return Company.findOneAndUpdate({ name }, company, { new: true, upsert });
}
return null;
};

const getInvoiceRef = async (id, Counter) => {
const counter = await Counter.findByIdAndUpdate(
id,
{ $inc: { sequence: 1 } },
{ new: true, upsert: true }
);
const INVOICE_REF_SIZE = process.env.INVOICE_REF_SIZE || 4;
const z = '0';
return `${id}/${`${z.repeat(INVOICE_REF_SIZE)}${counter.sequence}`.slice(-INVOICE_REF_SIZE)}`;
};

const store = (file, tags, folder, cloudinary, generated) =>
new Promise((resolve, reject) => {
const uploadStream = cloudinary.uploader.upload_stream({ tags, folder }, (err, image) => {
if (image) {
return resolve(image);
}
return reject(err);
});
file.createReadStream().pipe(uploadStream);
if (!generated) file.createReadStream().pipe(uploadStream);
else file.pipe(uploadStream);
});

module.exports = {
register: async (_, { user }, { models: { User } }) => {
register: async (
_,
{ user },
{ models: { User }, validation: { registerValidation, validate } }
) => {
const { formatData, rules, messages } = registerValidation;
await validate(formatData({ ...user }), rules, messages);

Expand All @@ -32,23 +54,35 @@ module.exports = {
expenseClaim: async (
unused,
{ expense },
{ user, models: { Transaction, User }, cloudinary, db }
{
user,
models: { Transaction, User },
cloudinary,
db,
constants: { TR_TYPE, TR_FLOW, STORAGE_PATH },
validation: { expenseValidation, validate }
}
) => {
expense.date = expense.date || Date.now();

const { formatData, rules, messages } = expenseValidation;
await validate(formatData({ ...expense }), rules, messages);

expense.user = user.id;
expense.flow = 'IN';
expense.type = 'EXPENSE';
expense.flow = TR_FLOW.IN;
expense.type = TR_TYPE.EXPENSE;
const receipt = await expense.receipt;

const session = await db.startSession();
let tr;
try {
// upload the file to cloudinary
const file = await store(receipt, 'expense receipt', '/expenses/pending/', cloudinary);
const file = await store(
receipt,
'expense receipt',
STORAGE_PATH.EXPENSE_PENDING,
cloudinary
);
expense.file = file.secure_url;

const opts = { session };
Expand Down Expand Up @@ -76,7 +110,11 @@ module.exports = {
}
return tr;
},
updateProfile: async (_, args, { user, models: { User } }) => {
updateProfile: async (
_,
args,
{ user, models: { User }, validation: { updateProfileValidation, validate } }
) => {
const { formatData, rules, messages } = updateProfileValidation;
await validate(formatData({ ...args.user }), rules, messages);
const { email } = args.user;
Expand All @@ -87,15 +125,81 @@ module.exports = {
}
}
return User.findOneAndUpdate({ _id: user.id }, args.user, { new: true });
},
uploadInvoice: async (
root,
{ invoice },
{
models: { Transaction, Company, Category },
cloudinary,
constants: { TR_TYPE, TR_FLOW, STORAGE_PATH },
validation: { uploadInvoiceValidation, validate }
}
) => {
const { formatData, rules, messages } = uploadInvoiceValidation;
await validate(formatData({ ...invoice }), rules, messages);

// look for a company (by id or name), if name is provided: update it or save it if doesn't exist
const company = await saveOrRetrieveCompany(invoice.company, Company, true);
invoice.company = company;
if (invoice.category && (invoice.category.name || invoice.category.id)) {
const category = Category.findOne({
$or: [{ _id: company.category.id }, { name: company.category.id }]
});
if (!category) {
throw new Error('Category not found.');
}
invoice.category = category;
}
invoice.flow = TR_FLOW.IN;
invoice.type = TR_TYPE.INVOICE;
invoice.date = invoice.date || Date.now();
invoice.invoice = await invoice.invoice;

const file = await store(invoice.invoice, 'invoice', STORAGE_PATH.INVOICE_PENDING, cloudinary);
invoice.file = file.secure_url;

return new Transaction(invoice).save();
},
generateInvoice: async (
root,
{ invoice },
{
models: { Transaction, Company, Counter },
cloudinary,
constants: { TR_TYPE, TR_FLOW, STORAGE_PATH },
validation: { generateInvoiceValidation, validate },
generateInvoicePDF
}
) => {
const { formatData, rules, messages } = generateInvoiceValidation;

// look for a company (by id or name), if name is provided: update it or save it if doesn't exist
const company = await saveOrRetrieveCompany(invoice.company, Company, true);
invoice.company = company;

// validate the inputs with the retrieved company, will throw if any required element is missing
await validate(formatData(invoice), rules, messages);
invoice.type = TR_TYPE.INVOICE;
invoice.flow = TR_FLOW.OUT;
invoice.date = Date.now();

const noInvoice = await getInvoiceRef(new Date(invoice.date).getFullYear(), Counter);
invoice.ref = noInvoice;

let file = await generateInvoicePDF(
invoice.details,
{
date: invoice.date,
VAT: invoice.VAT,
noInvoice
},
invoice.company
);

file = await store(file, 'invoice', STORAGE_PATH.INVOICE_PENDING, cloudinary, true);
invoice.file = file.secure_url;

return new Transaction(invoice).save();
}
};

// TODO REMOVE EXAMPLE
// {
// "query": "mutation ($amount: Float!, $description: String!, $receipt: Upload!) {expenseClaim(expense: {amount: $amount, description: $description, receipt: $receipt}) {id}}",
// "variables": {
// "amount": 10,
// "description": "Hello World!",
// "receipt": null
// }
// }
51 changes: 50 additions & 1 deletion backend/src/graphql/types.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ module.exports = gql`
login(email: String!, password: String!): User! @guest
expenseClaim(expense: Expense!): Transaction! @auth
updateProfile(user: UserUpdateInput!): User! @auth
uploadInvoice(invoice: InvoiceUpload!): Transaction! @auth
generateInvoice(invoice: GenerateInvoiceInput!): Transaction! @auth
}
type Success {
status: Boolean!
Expand Down Expand Up @@ -45,6 +47,8 @@ module.exports = gql`

type Transaction {
id: ID!
category: Category
company: Company
flow: Flow!
state: State!
user: User!
Expand All @@ -55,6 +59,21 @@ module.exports = gql`
file: String
VAT: Int
type: TransactionType!
ref: String
}

type Category {
id: ID!
name: String!
}

type Company {
name: String!
email: String
phone: String
VAT: String
bankDetails: BankDetails
address: Address
}

#inputs
Expand Down Expand Up @@ -89,12 +108,42 @@ module.exports = gql`
input Expense {
amount: Float!
date: String
expDate: String
description: String!
receipt: Upload!
VAT: Int
}

input InvoiceUpload {
amount: Float!
date: String
category: String
company: CompanyInput
expDate: String
invoice: Upload!
VAT: Int
}

input CompanyInput {
id: ID
name: String
email: String
phone: String
VAT: String
bankDetails: BankDetailsInput
address: AdressInput
}

input GenerateInvoiceInput {
company: CompanyInput!
details: [GenerateInvoiceDetailsInput!]!
VAT: Int!
}

input GenerateInvoiceDetailsInput {
description: String!
amount: Float!
}

#enums
enum Flow {
IN
Expand Down
22 changes: 20 additions & 2 deletions backend/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ const models = require('./models');
const db = require('./db');
const auth = require('./auth');

const validation = require('./lib/validation');
const constants = require('./constants');
const generateInvoicePDF = require('./invoiceFactory');

const PORT = process.env.PORT || 4000;

const app = express();
Expand All @@ -29,7 +33,18 @@ app.use(
const context = async ({ req, res }) => {
const user = await auth.loggedUser(req.cookies, models);
// adopting injection pattern to ease mocking
return { req, res, user, auth, models, cloudinary, db };
return {
req,
res,
user,
auth,
models,
cloudinary,
db,
validation,
constants,
generateInvoicePDF
};
};

const server = new ApolloServer({
Expand Down Expand Up @@ -69,5 +84,8 @@ module.exports = {
auth,
server,
app,
cloudinary
cloudinary,
validation,
constants,
generateInvoicePDF
};
Loading