Add uploadProofOfPayment and improve file validation

- Implemented uploadProofOfPayment function for per-bill proof of payment
  - Validates file size using MAX_PROOF_OF_PAYMENT_UPLOAD_SIZE_KB env variable
  - Validates PDF file type
  - Prevents duplicate uploads with existence check
  - Uses optimized database projection to minimize data transfer
  - Updates specific bill using MongoDB array filters

- Refactored file validation in updateOrAddBill
  - Moved validation before serialization for fail-fast behavior
  - Added configurable file size limit from environment variable
  - Added PDF type validation
  - Improved error messages with specific validation failures

- Updated serializeAttachment function
  - Changed return type from BillAttachment to FileAttachment
  - Added uploadedAt timestamp to attachment object
  - Removed unsafe type cast

- Code formatting improvements throughout
  - Consistent spacing and indentation
  - Better TypeScript typing

This completes the per-bill proof of payment feature implementation.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Knee Cola
2025-12-07 12:24:52 +01:00
parent a25a97f68b
commit 0facc9c257

View File

@@ -2,13 +2,14 @@
import { z } from 'zod';
import { getDbClient } from '../dbClient';
import { Bill, BilledTo, BillAttachment, BillingLocation, YearMonth } from '../db-types';
import { Bill, BilledTo, FileAttachment, BillingLocation, YearMonth } from '../db-types';
import { ObjectId } from 'mongodb';
import { withUser } from '@/app/lib/auth';
import { AuthenticatedUser } from '../types/next-auth';
import { gotoHome, gotoHomeWithMessage } from './navigationActions';
import { getTranslations, getLocale } from "next-intl/server";
import { IntlTemplateFn } from '@/app/i18n';
import { unstable_noStore } from 'next/cache';
export type State = {
errors?: {
@@ -73,7 +74,7 @@ const FormSchema = (t:IntlTemplateFn) => z.object({
* @param billAttachment
* @returns
*/
const serializeAttachment = async (billAttachment: File | null) => {
const serializeAttachment = async (billAttachment: File | null): Promise<FileAttachment | null> => {
if (!billAttachment) {
return null;
@@ -101,7 +102,8 @@ const serializeAttachment = async (billAttachment: File | null) => {
fileType,
fileLastModified,
fileContentsBase64,
} as BillAttachment);
uploadedAt: new Date()
});
}
/**
@@ -151,7 +153,23 @@ export const updateOrAddBill = withUser(async (user:AuthenticatedUser, locationI
// update the bill in the mongodb
const dbClient = await getDbClient();
const billAttachment = await serializeAttachment(formData.get('billAttachment') as File);
// First validate that the file is acceptable
const attachmentFile = formData.get('billAttachment') as File;
// validate max file size from env variable
const maxFileSizeKB = parseInt(process.env.MAX_PROOF_OF_PAYMENT_UPLOAD_SIZE_KB || '1024', 10);
const maxFileSizeBytes = maxFileSizeKB * 1024;
if (attachmentFile && attachmentFile.size > maxFileSizeBytes) {
return { success: false, error: `File size exceeds the maximum limit of ${maxFileSizeKB} KB` };
}
// Validate file type
if (attachmentFile && attachmentFile.type !== 'application/pdf') {
return { success: false, error: 'Only PDF files are accepted' };
}
const billAttachment = await serializeAttachment(attachmentFile);
if (billId) {
@@ -175,8 +193,8 @@ export const updateOrAddBill = withUser(async (user:AuthenticatedUser, locationI
"bills.$[elem].hub3aText": hub3aText,
};
// find a location with the given locationID
const post = await dbClient.collection<BillingLocation>("lokacije").updateOne(
// update bill in given location with the given locationID
await dbClient.collection<BillingLocation>("lokacije").updateOne(
{
_id: locationId, // find a location with the given locationID
userId // make sure that the location belongs to the user
@@ -462,3 +480,94 @@ export const deleteBillById = withUser(async (user:AuthenticatedUser, locationID
errors: undefined,
};
});
/**
* Uploads proof of payment for the given bill
* @param locationID - The ID of the location
* @param formData - FormData containing the file
* @returns Promise with success status
*/
export const uploadProofOfPayment = async (locationID: string, billID: string, formData: FormData): Promise<{ success: boolean; error?: string }> => {
unstable_noStore();
try {
// First validate that the file is acceptable
const file = formData.get('utilBillsProofOfPayment') as File;
// validate max file size from env variable
const maxFileSizeKB = parseInt(process.env.MAX_PROOF_OF_PAYMENT_UPLOAD_SIZE_KB || '1024', 10);
const maxFileSizeBytes = maxFileSizeKB * 1024;
if (file && file.size > maxFileSizeBytes) {
return { success: false, error: `File size exceeds the maximum limit of ${maxFileSizeKB} KB` };
}
// Validate file type
if (file && file.type !== 'application/pdf') {
return { success: false, error: 'Only PDF files are accepted' };
}
// update the bill in the mongodb
const dbClient = await getDbClient();
const projection = {
"bills.attachment": 0,
// don't include the attachment - save the bandwidth it's not needed here
"bills.proofOfPayment.uploadedAt": 1,
// ommit only the file contents - we need to know if a file was already uploaded
"bills.proofOfPayment.fileContentsBase64": 0,
};
// Checking if proof of payment already exists
// find a location with the given locationID
const billLocation = await dbClient.collection<BillingLocation>("lokacije").findOne(
{
_id: locationID,
},
{
projection
})
if (!billLocation) {
console.log(`Location ${locationID} not found - Proof of payment upload failed`);
return { success: false, error: "Location not found - Proof of payment upload failed" };
}
// find a bill with the given billID
const bill = billLocation?.bills.find(({ _id }) => _id.toString() === billID);
if (bill?.proofOfPayment?.uploadedAt) {
return { success: false, error: 'Proof payment already uploaded for this bill' };
}
const attachment = await serializeAttachment(file);
if (!attachment) {
return { success: false, error: 'Invalid file' };
}
// Add proof of payment to the bill
await dbClient.collection<BillingLocation>("lokacije").updateOne(
{
_id: locationID // find a location with the given locationID
},
{
$set: {
"bills.$[elem].proofOfPayment": {
...attachment
}
}
}, {
arrayFilters: [
{ "elem._id": { $eq: billID } } // find a bill with the given billID
]
});
return { success: true };
} catch (error: any) {
console.error('Error uploading proof of payment for a bill:', error);
return { success: false, error: error.message || 'Upload failed' };
}
}