Support #12361
openIssues & gaps in vendor invoices as well as Purchase Order
0%
Description
Bug 1: Anyone can approve a PO, including their own
Where: purchaseOrder.controller.js:33-42 and updatePurchaseOrderStatus (line 508)
What goes wrong: Any logged-in staff member can create a PO and approve it straight from draft, so nobody else checks it.
Fix steps:
In VALID_TRANSITIONS, change draft: ["sent", "approved", "cancelled"] to draft: ["sent", "cancelled"].
In updatePurchaseOrderStatus, before saving, add:
if status === "approved" or "rejected" and the user isn't an admin or manager → return 403
if status === "approved" and String(po.createdBy) === String(userId) → return 403 "You can't approve your own PO"
Reuse the existing isAdminOrManager from Vector.service.js:78 rather than writing a new role check.
🔴 Bug 2: Editing an invoice drops tax, shipping and discount
Where: vendorInvoiceController.js:2493: const totalAmount = subtotal;
What goes wrong: An invoice of $1,000 + $80 tax + $50 shipping becomes $1,000 after any edit, so the vendor balance comes out wrong.
Fix steps:
Add shippingCharges, discount, discountType and extraTax to the edit service's parameters (default them to the invoice's current values).
Calculate the total the same way invoice creation does: subtotal + tax + shipping − discount (percentage or flat).
Save invoice.shippingCharges and invoice.discount too.
Test: edit an invoice that has tax and shipping, and check the total doesn't change.
🔴 Bug 3: Editing an invoice doesn't update the PO's received quantities
Where: the edit service (line 2071) loads PurchaseOrder at line 2089 but never uses it.
What goes wrong: If you change an invoice line from 10 to 6, the PO still shows 10 received, so its status stays wrong (for example "completed" when it should be partial).
Fix steps:
Find the linked PO (by poNumber or by linkedInvoiceIds).
Subtract the old invoice line quantities from receivedQuantity, then add the new quantities.
Recalculate the PO status. Move the status logic from create (lines 637-655) into one shared helper and call it from create, edit and delete.
Add a "invoice_linked" entry to the PO's history noting the change.
🔴 Bug 4: If linking to the PO fails, the error is hidden
Where: vendorInvoiceController.js:581-679. The catch only does console.error.
What goes wrong: The invoice and stock are saved, but the PO isn't updated, and the user sees "success".
Fix steps:
Start a session with the existing tryStartTransaction.
Pass { session } to the invoice create, the stock batch creates and po.save().
If linking the PO fails, abort the transaction and return an error. Don't just log it.
If transactions aren't available (a standalone MongoDB), at least return a warning in the response so the user knows.
🔴 Bug 5: Invoices can be linked to POs that aren't approved
Where: getVendorActivePOs, line 777, includes draft and sent.
Fix steps:
Change the filter to ["approved", "partially_received"].
In invoice create (around line 584), also check po.status and po.vendor_id === vendor_id. Reject the request otherwise. Never rely only on the dropdown.
🟠 Bug 6: The PO approval email always shows the vendor as "N/A"
Where: line 551: Vendor.findById(po.vendor_id)
Why: vendor_id is a custom code (like VEN_0001), not a Mongo _id.
Fix: Change it to Vendor.findOne({ vendor_id: po.vendor_id }).lean(). That's the whole fix.
🟠 Bug 7: The /dashboard and /batches routes are never reached
Where: vendorInvoice-route.js:84-92
Why: GET /:invoiceId comes first, so Express treats "dashboard" as an invoice ID.
Fix steps:
Move router.get('/dashboard', …) and router.get('/batches', …) above router.get("/:invoiceId", …).
Test: GET /dashboard should return dashboard data, not "not found".
🟠 Bug 8: Unauthenticated file uploads on AI preview
Where: vendorInvoice-route.js:123
Fix: Swap the order so the login check runs first: router.post("/ai-preview", verifyToken, upload.single('file'), aiInvoicePreview);
🟠 Bug 9: Invoice fields are silently lost, and the vendor's own invoice number isn't stored
Where: create saves invoiceDate, paidAmount, totalAmountBeforeAdjustment and adjustmentAmount (lines 548-559), but vendorInvoiceSchema.js doesn't define them, so Mongoose drops them.
What goes wrong: The same vendor bill can be entered twice, and nothing catches it.
Fix steps:
Add these to the schema: supplierInvoiceNo (String), invoiceDate (Date), paidAmount, totalAmountBeforeAdjustment, adjustmentAmount (Number).
Add an index: { vendor_id: 1, supplierInvoiceNo: 1 }, unique, with partialFilterExpression: { isDeleted: false, supplierInvoiceNo: { $type: "string", $gt: "" } } so old invoices without a number don't clash.
Add a "Vendor Invoice #" field to the invoice form, and fill it in from the AI extraction.
🟡 Bug 10: PO search crashes on special characters
Where: line 188: new RegExp(search, "i")
What goes wrong: Searching for PO_(1 throws an error, and a crafted pattern can hang the server.
Fix: Escape the input first: search.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").
🟡 Bug 11: Free or sample items (cost 0) can't be added to a PO
Where: lines 74 and 433: !item.unitCost treats 0 as missing.
Fix: Replace it with item.unitCost null || Number(item.unitCost) < 0, in both create and update.
🟡 Bug 12: A PO can be changed while it's waiting for approval
Where: line 419
What goes wrong: The approver reviews a $500 PO, someone edits it to $5,000, and the approver approves the new amount without knowing it changed.
Fix steps:
If an edit happens while po.status = "sent", set po.status = "draft".
Add a history note: "Edited during approval; resubmission needed".
The user then has to send it again, which notifies the approver again.
🟡 Risk 13: Deleting an invoice might not undo its PO quantities
Where: Create links the PO by purchaseOrderId (line 584), but delete looks it up by purchaseOrderNumber (line 4475). The number is only saved if the frontend sends it too.
Fix steps:
In create, after loading the PO, always set vendorInvoice.purchaseOrderNumber = po.poNumber and save.
In delete, find the PO by either the number or linkedInvoiceIds: invoice._id. The code at line 9674 already does this.
Files
Subtasks
Related issues