Untitled
unknown
plain_text
9 months ago
1.9 kB
6
Indexable
router.post('/', auth, async(req, res) => {
const transaction = await sequelize.transaction();
try {
const { client_id, creation_date, due_date, currency, fisical_stamp, items } = req.body;
if (!client_id || !creation_date || !due_date || !currency || !(items && items.length)) {
return res.status(400).json({ error: 'Missing required fields' });
}
const client = await Client.findByPk(client_id);
const userProfile = await UserProfile.findOne({ where: { user_id: req.user.id } });
if (!client || !userProfile) {
return res.status(404).json({ error: 'Client or user profile not found' });
}
const invoice = await Invoice.create({
company_id: client_id,
user_id: req.user.id,
creation_date,
due_date,
currency,
fisical_stamp: fisical_stamp || false
}, { transaction });
const itemsWithInvoiceId = items.map(item => ({
name: item.name,
price: item.price,
type: item.type.toLowerCase(),
quantity: item.quantity,
taxes: item.tax_rate,
invoice_id: invoice.id
}));
await InvoiceItem.bulkCreate(itemsWithInvoiceId, { transaction });
const pdfBuffer = await generatePDF(userProfile, client, invoice, items, currency);
await Invoice.update({ file: pdfBuffer }, { where: { id: invoice.id }, transaction });
await transaction.commit();
res.status(201).json({ message: 'Invoice created successfully', invoice_id: invoice.id });
} catch (error) {
await transaction.rollback();
console.error('Invoice creation error:', error);
res.status(500).json({ error: 'Internal server error', details: error.message });
}
});Editor is loading...
Leave a Comment