refactor: convert repository to monorepo with npm workspaces
Restructured the repository into a monorepo to better organize application code and maintenance scripts. ## Workspace Structure - web-app: Next.js application (all app code moved from root) - housekeeping: Database backup and maintenance scripts ## Key Changes - Moved all application code to web-app/ using git mv - Moved database scripts to housekeeping/ workspace - Updated Dockerfile for monorepo build process - Updated docker-compose files (volume paths: ./web-app/etc/hosts/) - Updated .gitignore for workspace-level node_modules - Updated documentation (README.md, CLAUDE.md, CHANGELOG.md) ## Migration Impact - Root package.json now manages workspaces - Build commands delegate to web-app workspace - All file history preserved via git mv - Docker build process updated for workspace structure 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
620
web-app/app/lib/actions/billActions.ts
Normal file
620
web-app/app/lib/actions/billActions.ts
Normal file
@@ -0,0 +1,620 @@
|
||||
'use server';
|
||||
|
||||
import { z } from 'zod';
|
||||
import { getDbClient } from '../dbClient';
|
||||
import { Bill, BilledTo, FileAttachment, BillingLocation } from '../db-types';
|
||||
import { ObjectId } from 'mongodb';
|
||||
import { withUser } from '@/app/lib/auth';
|
||||
import { AuthenticatedUser } from '../types/next-auth';
|
||||
import { gotoHomeWithMessage } from './navigationActions';
|
||||
import { getTranslations, getLocale } from "next-intl/server";
|
||||
import { IntlTemplateFn } from '@/app/i18n';
|
||||
import { unstable_noStore, revalidatePath } from 'next/cache';
|
||||
import { extractShareId, validateShareChecksum } from '../shareChecksum';
|
||||
import { validatePdfFile } from '../validators/pdfValidator';
|
||||
import { checkUploadRateLimit } from '../uploadRateLimiter';
|
||||
|
||||
export type State = {
|
||||
errors?: {
|
||||
billName?: string[];
|
||||
billAttachment?: string[],
|
||||
billNotes?: string[],
|
||||
payedAmount?: string[],
|
||||
};
|
||||
message?: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Schema for validating bill form fields
|
||||
* @description this is defined as factory function so that it can be used with the next-intl library
|
||||
*/
|
||||
const FormSchema = (t: IntlTemplateFn) => z.object({
|
||||
_id: z.string(),
|
||||
billName: z.coerce.string().min(1, t("bill-name-required")),
|
||||
billNotes: z.string(),
|
||||
addToSubsequentMonths: z.boolean().optional(),
|
||||
payedAmount: z.string().nullable().transform((val, ctx) => {
|
||||
|
||||
if (!val || val === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
const parsed = parseFloat(val.replace(',', '.'));
|
||||
|
||||
if (isNaN(parsed)) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: t("not-a-number"),
|
||||
});
|
||||
|
||||
// This is a special symbol you can use to
|
||||
// return early from the transform function.
|
||||
// It has type `never` so it does not affect the
|
||||
// inferred return type.
|
||||
return z.NEVER;
|
||||
}
|
||||
|
||||
if (parsed < 0) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: t("negative-number")
|
||||
});
|
||||
|
||||
// This is a special symbol you can use to
|
||||
// return early from the transform function.
|
||||
// It has type `never` so it does not affect the
|
||||
// inferred return type.
|
||||
return z.NEVER;
|
||||
}
|
||||
|
||||
return Math.floor(parsed * 100); // value is stored in cents
|
||||
|
||||
}),
|
||||
});
|
||||
|
||||
/**
|
||||
* converts the file to a format stored in the database
|
||||
* @param billAttachment
|
||||
* @returns
|
||||
*/
|
||||
const serializeAttachment = async (billAttachment: File | null): Promise<FileAttachment | null> => {
|
||||
|
||||
if (!billAttachment) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const {
|
||||
name: fileName,
|
||||
size: fileSize,
|
||||
type: fileType,
|
||||
lastModified: fileLastModified,
|
||||
} = billAttachment;
|
||||
|
||||
if (!fileName || fileName === 'undefined' || fileSize === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// convert the billAttachment file contents to format that can be stored in the database
|
||||
const fileContents = await billAttachment.arrayBuffer();
|
||||
const fileContentsBase64 = Buffer.from(fileContents).toString('base64');
|
||||
|
||||
// create an object to store the file in the database
|
||||
return ({
|
||||
fileName,
|
||||
fileSize,
|
||||
fileType,
|
||||
fileLastModified,
|
||||
fileContentsBase64,
|
||||
uploadedAt: new Date()
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Server-side action which adds or updates a bill
|
||||
* @param locationId location of the bill
|
||||
* @param billId ID of the bill
|
||||
* @param prevState previous state of the form
|
||||
* @param formData form data
|
||||
* @returns
|
||||
*/
|
||||
export const updateOrAddBill = withUser(async (user: AuthenticatedUser, locationId: string, billId: string | undefined, billYear: number | undefined, billMonth: number | undefined, prevState: State, formData: FormData) => {
|
||||
|
||||
unstable_noStore();
|
||||
|
||||
const { id: userId } = user;
|
||||
|
||||
const t = await getTranslations("bill-edit-form.validation");
|
||||
|
||||
// FormSchema
|
||||
const validatedFields = FormSchema(t)
|
||||
.omit({ _id: true })
|
||||
.safeParse({
|
||||
billName: formData.get('billName'),
|
||||
billNotes: formData.get('billNotes'),
|
||||
addToSubsequentMonths: formData.get('addToSubsequentMonths') === 'on',
|
||||
payedAmount: formData.get('payedAmount'),
|
||||
});
|
||||
|
||||
// If form validation fails, return errors early. Otherwise, continue...
|
||||
if (!validatedFields.success) {
|
||||
console.log("updateBill.validation-error");
|
||||
return ({
|
||||
errors: validatedFields.error.flatten().fieldErrors,
|
||||
message: t("form-error-message"),
|
||||
});
|
||||
}
|
||||
|
||||
const {
|
||||
billName,
|
||||
billNotes,
|
||||
addToSubsequentMonths,
|
||||
payedAmount,
|
||||
} = validatedFields.data;
|
||||
|
||||
const billPaid = formData.get('billPaid') === 'on';
|
||||
const billedTo = (formData.get('billedTo') as BilledTo) ?? BilledTo.Tenant;
|
||||
const hub3aTextEncoded = formData.get('hub3aText')?.valueOf() as string;
|
||||
const hub3aText = hub3aTextEncoded ? decodeURIComponent(hub3aTextEncoded) : undefined;
|
||||
|
||||
// update the bill in the mongodb
|
||||
const dbClient = await getDbClient();
|
||||
|
||||
// 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.size > 0 && attachmentFile.type !== 'application/pdf') {
|
||||
return { success: false, error: 'Only PDF files are accepted' };
|
||||
}
|
||||
|
||||
const billAttachment = await serializeAttachment(attachmentFile);
|
||||
|
||||
if (billId) {
|
||||
|
||||
// if there is an attachment, update the attachment field
|
||||
// otherwise, do not update the attachment field
|
||||
const mongoDbSet = billAttachment ? {
|
||||
"bills.$[elem].name": billName,
|
||||
"bills.$[elem].paid": billPaid,
|
||||
"bills.$[elem].billedTo": billedTo,
|
||||
"bills.$[elem].attachment": billAttachment,
|
||||
"bills.$[elem].notes": billNotes,
|
||||
"bills.$[elem].payedAmount": payedAmount,
|
||||
"bills.$[elem].hub3aText": hub3aText,
|
||||
|
||||
} : {
|
||||
"bills.$[elem].name": billName,
|
||||
"bills.$[elem].paid": billPaid,
|
||||
"bills.$[elem].billedTo": billedTo,
|
||||
"bills.$[elem].notes": billNotes,
|
||||
"bills.$[elem].payedAmount": payedAmount,
|
||||
"bills.$[elem].hub3aText": hub3aText,
|
||||
};
|
||||
|
||||
// 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
|
||||
},
|
||||
{
|
||||
$set: mongoDbSet
|
||||
}, {
|
||||
arrayFilters: [
|
||||
{ "elem._id": { $eq: billId } } // find a bill with the given billID
|
||||
]
|
||||
});
|
||||
} else {
|
||||
// Create new bill - add to current location first
|
||||
const newBill = {
|
||||
_id: (new ObjectId()).toHexString(),
|
||||
name: billName,
|
||||
paid: billPaid,
|
||||
billedTo: billedTo,
|
||||
attachment: billAttachment,
|
||||
notes: billNotes,
|
||||
payedAmount,
|
||||
hub3aText,
|
||||
};
|
||||
|
||||
// Add to current location
|
||||
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
|
||||
},
|
||||
{
|
||||
$push: {
|
||||
bills: newBill
|
||||
}
|
||||
});
|
||||
|
||||
// If addToSubsequentMonths is enabled, add to subsequent months
|
||||
if (addToSubsequentMonths && billYear && billMonth) {
|
||||
// Get the current location to find its name
|
||||
const currentLocation = await dbClient.collection<BillingLocation>("lokacije")
|
||||
.findOne({ _id: locationId, userId }, { projection: { name: 1 } });
|
||||
|
||||
if (currentLocation) {
|
||||
// Find all subsequent months that have the same location name
|
||||
const subsequentLocations = await dbClient.collection<BillingLocation>("lokacije")
|
||||
.find({
|
||||
userId,
|
||||
name: currentLocation.name,
|
||||
$or: [
|
||||
{ "yearMonth.year": { $gt: billYear } },
|
||||
{
|
||||
"yearMonth.year": billYear,
|
||||
"yearMonth.month": { $gt: billMonth }
|
||||
}
|
||||
]
|
||||
}, { projection: { _id: 1 } })
|
||||
.toArray();
|
||||
|
||||
// For each subsequent location, check if bill with same name already exists
|
||||
const updateOperations = [];
|
||||
for (const location of subsequentLocations) {
|
||||
const existingBill = await dbClient.collection<BillingLocation>("lokacije")
|
||||
.findOne({
|
||||
_id: location._id,
|
||||
"bills.name": billName
|
||||
}, {
|
||||
// We only need to know if a matching bill exists; avoid conflicting projections
|
||||
projection: { _id: 1 }
|
||||
});
|
||||
|
||||
// Only add if bill with same name doesn't already exist
|
||||
if (!existingBill) {
|
||||
updateOperations.push({
|
||||
updateOne: {
|
||||
filter: { _id: location._id, userId },
|
||||
update: {
|
||||
$push: {
|
||||
bills: {
|
||||
_id: (new ObjectId()).toHexString(),
|
||||
name: billName,
|
||||
paid: false, // New bills in subsequent months are unpaid
|
||||
billedTo: BilledTo.Tenant, // Default to tenant for subsequent months
|
||||
attachment: null, // No attachment for subsequent months
|
||||
notes: billNotes,
|
||||
payedAmount: null,
|
||||
hub3aText: undefined,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Execute all update operations at once if any
|
||||
if (updateOperations.length > 0) {
|
||||
await dbClient.collection<BillingLocation>("lokacije").bulkWrite(updateOperations);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (billYear && billMonth) {
|
||||
const locale = await getLocale();
|
||||
await gotoHomeWithMessage(locale, 'billSaved', { year: billYear, month: billMonth });
|
||||
}
|
||||
|
||||
// This return is needed for TypeScript, but won't be reached due to redirect
|
||||
return {
|
||||
message: null,
|
||||
errors: undefined,
|
||||
};
|
||||
})
|
||||
/*
|
||||
Funkcija zamijenjena sa `fetchBillByUserAndId`, koja brže radi i ne treba korisnika
|
||||
|
||||
export const fetchBillByUserAndId = withUser(async (user:AuthenticatedUser, locationID:string, billID:string, includeAttachmentBinary:boolean = false) => {
|
||||
|
||||
const { id: userId } = user;
|
||||
|
||||
const dbClient = await getDbClient();
|
||||
|
||||
// don't include the attachment binary data in the response
|
||||
// if the attachment binary data is not needed
|
||||
const projection = includeAttachmentBinary ? {} : {
|
||||
"bills.attachment.fileContentsBase64": 0,
|
||||
};
|
||||
|
||||
// find a location with the given locationID
|
||||
const billLocation = await dbClient.collection<BillingLocation>("lokacije").findOne(
|
||||
{
|
||||
_id: locationID,
|
||||
userId
|
||||
},
|
||||
{
|
||||
projection
|
||||
})
|
||||
|
||||
if(!billLocation) {
|
||||
console.log(`Location ${locationID} not found`);
|
||||
return(null);
|
||||
}
|
||||
|
||||
// find a bill with the given billID
|
||||
const bill = billLocation?.bills.find(({ _id }) => _id.toString() === billID);
|
||||
|
||||
if(!bill) {
|
||||
console.log('Bill not found');
|
||||
return(null);
|
||||
}
|
||||
|
||||
return([billLocation, bill] as [BillingLocation, Bill]);
|
||||
})
|
||||
*/
|
||||
|
||||
export const fetchBillById = async (locationID: string, billID: string, includeAttachmentBinary: boolean = false) => {
|
||||
|
||||
unstable_noStore();
|
||||
|
||||
const dbClient = await getDbClient();
|
||||
|
||||
// don't include the attachment binary data in the response
|
||||
// if the attachment binary data is not needed
|
||||
const projection = includeAttachmentBinary ? {} : {
|
||||
"bills.attachment.fileContentsBase64": 0,
|
||||
};
|
||||
|
||||
// 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`);
|
||||
return (null);
|
||||
}
|
||||
|
||||
// find a bill with the given billID
|
||||
const bill = billLocation?.bills.find(({ _id }) => _id.toString() === billID);
|
||||
|
||||
if (!bill) {
|
||||
console.log('Bill not found');
|
||||
return (null);
|
||||
}
|
||||
|
||||
return ([billLocation, bill] as [BillingLocation, Bill]);
|
||||
};
|
||||
|
||||
export const deleteBillById = withUser(async (user: AuthenticatedUser, locationID: string, billID: string, year: number, month: number, _prevState: any, formData?: FormData) => {
|
||||
|
||||
unstable_noStore();
|
||||
|
||||
const { id: userId } = user;
|
||||
|
||||
const dbClient = await getDbClient();
|
||||
|
||||
const deleteInSubsequentMonths = formData?.get('deleteInSubsequentMonths') === 'on';
|
||||
|
||||
if (deleteInSubsequentMonths) {
|
||||
// Get the current location and bill to find the bill name and location name
|
||||
const location = await dbClient.collection<BillingLocation>("lokacije")
|
||||
.findOne({ _id: locationID, userId }, {
|
||||
projection: {
|
||||
"name": 1,
|
||||
"bills._id": 1,
|
||||
"bills.name": 1
|
||||
}
|
||||
});
|
||||
|
||||
if (location) {
|
||||
const bill = location.bills.find(b => b._id === billID);
|
||||
|
||||
if (bill) {
|
||||
// Find all subsequent locations with the same name that have the same bill
|
||||
const subsequentLocations = await dbClient.collection<BillingLocation>("lokacije")
|
||||
.find({
|
||||
userId,
|
||||
name: location.name,
|
||||
$or: [
|
||||
{ "yearMonth.year": { $gt: year } },
|
||||
{
|
||||
"yearMonth.year": year,
|
||||
"yearMonth.month": { $gt: month }
|
||||
}
|
||||
],
|
||||
"bills.name": bill.name
|
||||
}, { projection: { _id: 1 } })
|
||||
.toArray();
|
||||
|
||||
// Delete the bill from all subsequent locations (by name)
|
||||
const updateOperations = subsequentLocations.map(loc => ({
|
||||
updateOne: {
|
||||
filter: { _id: loc._id, userId },
|
||||
update: {
|
||||
$pull: {
|
||||
bills: { name: bill.name } as Partial<Bill>
|
||||
}
|
||||
}
|
||||
}
|
||||
}));
|
||||
|
||||
// Also delete from current location (by ID for precision)
|
||||
updateOperations.push({
|
||||
updateOne: {
|
||||
filter: { _id: locationID, userId },
|
||||
update: {
|
||||
$pull: {
|
||||
bills: { _id: billID }
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Execute all delete operations
|
||||
if (updateOperations.length > 0) {
|
||||
await dbClient.collection<BillingLocation>("lokacije").bulkWrite(updateOperations);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Delete only from current location (original behavior)
|
||||
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
|
||||
},
|
||||
{
|
||||
// remove the bill with the given billID
|
||||
$pull: {
|
||||
bills: {
|
||||
_id: billID
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const locale = await getLocale();
|
||||
await gotoHomeWithMessage(locale, 'billDeleted');
|
||||
|
||||
// This return is needed for TypeScript, but won't be reached due to redirect
|
||||
return {
|
||||
message: null,
|
||||
errors: undefined,
|
||||
};
|
||||
});
|
||||
|
||||
/**
|
||||
* Uploads proof of payment for the given bill
|
||||
* SECURITY: Validates checksum, TTL, PDF content, and rate limits by IP
|
||||
*
|
||||
* @param shareId - Combined location ID + checksum (40 chars)
|
||||
* @param billID - The bill ID to attach proof of payment to
|
||||
* @param formData - Form data containing the PDF file
|
||||
* @param ipAddress - Optional IP address for rate limiting
|
||||
*/
|
||||
export const uploadProofOfPayment = async (
|
||||
shareId: string,
|
||||
billID: string,
|
||||
formData: FormData,
|
||||
ipAddress?: string
|
||||
): Promise<{ success: boolean; error?: string }> => {
|
||||
|
||||
unstable_noStore();
|
||||
|
||||
try {
|
||||
// 1. EXTRACT AND VALIDATE CHECKSUM (stateless, fast)
|
||||
const extracted = extractShareId(shareId);
|
||||
if (!extracted) {
|
||||
return { success: false, error: 'Invalid share link' };
|
||||
}
|
||||
|
||||
const { locationId: locationID, checksum } = extracted;
|
||||
|
||||
if (!validateShareChecksum(locationID, checksum)) {
|
||||
return { success: false, error: 'Invalid share link' };
|
||||
}
|
||||
|
||||
// 2. RATE LIMITING (per IP)
|
||||
if (ipAddress) {
|
||||
const rateLimit = checkUploadRateLimit(ipAddress);
|
||||
if (!rateLimit.allowed) {
|
||||
return {
|
||||
success: false,
|
||||
error: `Too many uploads. Try again in ${Math.ceil(rateLimit.resetIn / 60)} minutes.`
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// 3. DATABASE VALIDATION
|
||||
const dbClient = await getDbClient();
|
||||
|
||||
const location = await dbClient.collection<BillingLocation>("lokacije").findOne(
|
||||
{ _id: locationID },
|
||||
{ projection: { userId: 1, bills: 1, shareTTL: 1 } }
|
||||
);
|
||||
|
||||
if (!location || !location.userId) {
|
||||
return { success: false, error: 'Invalid request' };
|
||||
}
|
||||
|
||||
// Check sharing is active and not expired
|
||||
if (!location.shareTTL || new Date() > location.shareTTL) {
|
||||
return { success: false, error: 'This content is no longer shared' };
|
||||
}
|
||||
|
||||
// Verify bill exists in location
|
||||
const bill = location.bills.find(b => b._id === billID);
|
||||
if (!bill) {
|
||||
return { success: false, error: 'Invalid request' };
|
||||
}
|
||||
|
||||
// Check if proof of payment already uploaded
|
||||
if (bill.proofOfPayment?.uploadedAt) {
|
||||
return { success: false, error: 'Proof of payment already uploaded for this bill' };
|
||||
}
|
||||
|
||||
// 4. FILE VALIDATION
|
||||
const file = formData.get('proofOfPayment') as File;
|
||||
|
||||
if (!file || file.size === 0) {
|
||||
return { success: false, error: 'No file provided' };
|
||||
}
|
||||
|
||||
// Validate PDF content (magic bytes, not just MIME type)
|
||||
const pdfValidation = await validatePdfFile(file);
|
||||
if (!pdfValidation.valid) {
|
||||
return { success: false, error: pdfValidation.error };
|
||||
}
|
||||
|
||||
// 5. SERIALIZE & STORE FILE
|
||||
const attachment = await serializeAttachment(file);
|
||||
if (!attachment) {
|
||||
return { success: false, error: 'Failed to process file' };
|
||||
}
|
||||
|
||||
// 6. UPDATE DATABASE
|
||||
await dbClient.collection<BillingLocation>("lokacije").updateOne(
|
||||
{ _id: locationID },
|
||||
{
|
||||
$set: {
|
||||
"bills.$[elem].proofOfPayment": attachment
|
||||
}
|
||||
},
|
||||
{
|
||||
arrayFilters: [{ "elem._id": { $eq: billID } }]
|
||||
}
|
||||
);
|
||||
|
||||
// 7. CLEANUP EXPIRED SHARES (integrated, no cron needed)
|
||||
await cleanupExpiredShares(dbClient);
|
||||
|
||||
// 8. REVALIDATE CACHE
|
||||
revalidatePath(`/share/location/${shareId}`, 'page');
|
||||
|
||||
return { success: true };
|
||||
|
||||
} catch (error: any) {
|
||||
console.error('Upload error:', error);
|
||||
return { success: false, error: 'Upload failed. Please try again.' };
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Clean up expired shares during upload processing
|
||||
* Removes shareTTL and shareFirstVisitedAt from expired locations
|
||||
*/
|
||||
async function cleanupExpiredShares(dbClient: any) {
|
||||
const now = new Date();
|
||||
|
||||
await dbClient.collection("lokacije").updateMany(
|
||||
{ shareTTL: { $lt: now } },
|
||||
{ $unset: { shareTTL: "", shareFirstVisitedAt: "" } }
|
||||
);
|
||||
}
|
||||
869
web-app/app/lib/actions/locationActions.ts
Normal file
869
web-app/app/lib/actions/locationActions.ts
Normal file
@@ -0,0 +1,869 @@
|
||||
'use server';
|
||||
|
||||
import { z } from 'zod';
|
||||
import { getDbClient } from '../dbClient';
|
||||
import { BillingLocation, FileAttachment, YearMonth } from '../db-types';
|
||||
import { ObjectId } from 'mongodb';
|
||||
import { withUser } from '@/app/lib/auth';
|
||||
import { AuthenticatedUser } from '../types/next-auth';
|
||||
import { gotoHomeWithMessage } from './navigationActions';
|
||||
import { unstable_noStore, revalidatePath } from 'next/cache';
|
||||
import { IntlTemplateFn } from '@/app/i18n';
|
||||
import { getTranslations, getLocale } from "next-intl/server";
|
||||
import { generateShareId, extractShareId, validateShareChecksum } from '../shareChecksum';
|
||||
import { validatePdfFile } from '../validators/pdfValidator';
|
||||
import { checkUploadRateLimit } from '../uploadRateLimiter';
|
||||
|
||||
export type State = {
|
||||
errors?: {
|
||||
locationName?: string[];
|
||||
tenantName?: string[];
|
||||
tenantStreet?: string[];
|
||||
tenantTown?: string[];
|
||||
autoBillFwd?: string[];
|
||||
tenantEmail?: string[];
|
||||
billFwdStrategy?: string[];
|
||||
rentDueNotification?: string[];
|
||||
rentDueDay?: string[];
|
||||
rentAmount?: string[];
|
||||
};
|
||||
message?:string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Schema for validating location form fields
|
||||
* @description this is defined as factory function so that it can be used with the next-intl library
|
||||
*/
|
||||
const FormSchema = (t:IntlTemplateFn) => z.object({
|
||||
_id: z.string(),
|
||||
locationName: z.coerce.string().min(1, t("location-name-required")),
|
||||
tenantPaymentMethod: z.enum(["none", "iban", "revolut"]).optional().nullable(),
|
||||
proofOfPaymentType: z.enum(["none", "combined", "per-bill"]).optional().nullable(),
|
||||
tenantName: z.string().max(30).optional().nullable(),
|
||||
tenantStreet: z.string().max(27).optional().nullable(),
|
||||
tenantTown: z.string().max(27).optional().nullable(),
|
||||
autoBillFwd: z.boolean().optional().nullable(),
|
||||
tenantEmail: z.string().email(t("tenant-email-invalid")).optional().or(z.literal("")).nullable(),
|
||||
billFwdStrategy: z.enum(["when-payed", "when-attached"]).optional().nullable(),
|
||||
rentDueNotification: z.boolean().optional().nullable(),
|
||||
rentDueDay: z.coerce.number().min(1).max(31).optional().nullable(),
|
||||
rentAmount: z.coerce.number().int(t("rent-amount-integer")).positive(t("rent-amount-positive")).optional().nullable(),
|
||||
addToSubsequentMonths: z.boolean().optional().nullable(),
|
||||
updateScope: z.enum(["current", "subsequent", "all"]).optional().nullable(),
|
||||
})
|
||||
// dont include the _id field in the response
|
||||
.omit({ _id: true })
|
||||
// Add conditional validation: if `tenantPaymentMethod` is "iban", tenant fields are required
|
||||
.refine((data) => {
|
||||
if (data.tenantPaymentMethod === "iban") {
|
||||
return !!data.tenantName && data.tenantName.trim().length > 0;
|
||||
}
|
||||
return true;
|
||||
}, {
|
||||
message: t("tenant-name-required"),
|
||||
path: ["tenantName"],
|
||||
})
|
||||
.refine((data) => {
|
||||
if (data.tenantPaymentMethod === "iban") {
|
||||
return !!data.tenantStreet && data.tenantStreet.trim().length > 0;
|
||||
}
|
||||
return true;
|
||||
}, {
|
||||
message: t("tenant-street-required"),
|
||||
path: ["tenantStreet"],
|
||||
})
|
||||
.refine((data) => {
|
||||
if (data.tenantPaymentMethod === "iban") {
|
||||
return !!data.tenantTown && data.tenantTown.trim().length > 0;
|
||||
}
|
||||
return true;
|
||||
}, {
|
||||
message: t("tenant-town-required"),
|
||||
path: ["tenantTown"],
|
||||
})
|
||||
.refine((data) => {
|
||||
if (data.autoBillFwd || data.rentDueNotification) {
|
||||
return !!data.tenantEmail && data.tenantEmail.trim().length > 0;
|
||||
}
|
||||
return true;
|
||||
}, {
|
||||
message: t("tenant-email-required"),
|
||||
path: ["tenantEmail"],
|
||||
})
|
||||
.refine((data) => {
|
||||
if (data.rentDueNotification) {
|
||||
return !!data.rentAmount && data.rentAmount > 0;
|
||||
}
|
||||
return true;
|
||||
}, {
|
||||
message: t("rent-amount-required"),
|
||||
path: ["rentAmount"],
|
||||
});
|
||||
|
||||
/**
|
||||
* Server-side action which adds or updates a bill
|
||||
* @param locationId location of the bill
|
||||
* @param prevState previous state of the form
|
||||
* @param formData form data
|
||||
* @returns
|
||||
*/
|
||||
export const updateOrAddLocation = withUser(async (user:AuthenticatedUser, locationId: string | undefined, yearMonth: YearMonth | undefined, prevState:State, formData: FormData) => {
|
||||
|
||||
unstable_noStore();
|
||||
|
||||
const t = await getTranslations("location-edit-form.validation");
|
||||
|
||||
const validatedFields = FormSchema(t).safeParse({
|
||||
locationName: formData.get('locationName'),
|
||||
tenantPaymentMethod: formData.get('tenantPaymentMethod') as "none" | "iban" | "revolut" | undefined,
|
||||
proofOfPaymentType: formData.get('proofOfPaymentType') as "none" | "combined" | "per-bill" | undefined,
|
||||
tenantName: formData.get('tenantName') || null,
|
||||
tenantStreet: formData.get('tenantStreet') || null,
|
||||
tenantTown: formData.get('tenantTown') || null,
|
||||
autoBillFwd: formData.get('autoBillFwd') === 'on',
|
||||
tenantEmail: formData.get('tenantEmail') || null,
|
||||
billFwdStrategy: formData.get('billFwdStrategy') as "when-payed" | "when-attached" | undefined,
|
||||
rentDueNotification: formData.get('rentDueNotification') === 'on',
|
||||
rentDueDay: formData.get('rentDueDay') || null,
|
||||
rentAmount: formData.get('rentAmount') || null,
|
||||
addToSubsequentMonths: formData.get('addToSubsequentMonths') === 'on',
|
||||
updateScope: formData.get('updateScope') as "current" | "subsequent" | "all" | undefined,
|
||||
});
|
||||
|
||||
// If form validation fails, return errors early. Otherwise, continue...
|
||||
if(!validatedFields.success) {
|
||||
return({
|
||||
errors: validatedFields.error.flatten().fieldErrors,
|
||||
message: t("validation-failed"),
|
||||
});
|
||||
}
|
||||
|
||||
const {
|
||||
locationName,
|
||||
tenantPaymentMethod,
|
||||
proofOfPaymentType,
|
||||
tenantName,
|
||||
tenantStreet,
|
||||
tenantTown,
|
||||
autoBillFwd,
|
||||
tenantEmail,
|
||||
billFwdStrategy,
|
||||
rentDueNotification,
|
||||
rentDueDay,
|
||||
rentAmount,
|
||||
addToSubsequentMonths,
|
||||
updateScope,
|
||||
} = validatedFields.data;
|
||||
|
||||
// update the bill in the mongodb
|
||||
const dbClient = await getDbClient();
|
||||
|
||||
const { id: userId, email: userEmail } = user;
|
||||
|
||||
if(locationId) {
|
||||
// Get the current location first to find its name
|
||||
const currentLocation = await dbClient.collection<BillingLocation>("lokacije")
|
||||
.findOne({ _id: locationId, userId }, { projection: { bills: 0 } });
|
||||
|
||||
if (!currentLocation) {
|
||||
return {
|
||||
message: "Location not found",
|
||||
errors: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
// Handle different update scopes
|
||||
if (updateScope === "current" || !updateScope) {
|
||||
// Update only the current location (default behavior)
|
||||
await dbClient.collection<BillingLocation>("lokacije").updateOne(
|
||||
{
|
||||
_id: locationId,
|
||||
userId
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
name: locationName,
|
||||
tenantPaymentMethod: tenantPaymentMethod || "none",
|
||||
proofOfPaymentType: proofOfPaymentType || "none",
|
||||
tenantName: tenantName || null,
|
||||
tenantStreet: tenantStreet || null,
|
||||
tenantTown: tenantTown || null,
|
||||
autoBillFwd: autoBillFwd || false,
|
||||
tenantEmail: tenantEmail || null,
|
||||
billFwdStrategy: billFwdStrategy || "when-payed",
|
||||
rentDueNotification: rentDueNotification || false,
|
||||
rentDueDay: rentDueDay || null,
|
||||
rentAmount: rentAmount || null,
|
||||
}
|
||||
}
|
||||
);
|
||||
} else if (updateScope === "subsequent") {
|
||||
// Update current and all subsequent months
|
||||
await dbClient.collection<BillingLocation>("lokacije").updateMany(
|
||||
{
|
||||
userId,
|
||||
name: currentLocation.name,
|
||||
$or: [
|
||||
{ "yearMonth.year": { $gt: currentLocation.yearMonth.year } },
|
||||
{
|
||||
"yearMonth.year": currentLocation.yearMonth.year,
|
||||
"yearMonth.month": { $gte: currentLocation.yearMonth.month }
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
name: locationName,
|
||||
tenantPaymentMethod: tenantPaymentMethod || "none",
|
||||
proofOfPaymentType: proofOfPaymentType || "none",
|
||||
tenantName: tenantName || null,
|
||||
tenantStreet: tenantStreet || null,
|
||||
tenantTown: tenantTown || null,
|
||||
autoBillFwd: autoBillFwd || false,
|
||||
tenantEmail: tenantEmail || null,
|
||||
billFwdStrategy: billFwdStrategy || "when-payed",
|
||||
rentDueNotification: rentDueNotification || false,
|
||||
rentDueDay: rentDueDay || null,
|
||||
rentAmount: rentAmount || null,
|
||||
}
|
||||
}
|
||||
);
|
||||
} else if (updateScope === "all") {
|
||||
// Update all locations with the same name across all months
|
||||
await dbClient.collection<BillingLocation>("lokacije").updateMany(
|
||||
{
|
||||
userId,
|
||||
name: currentLocation.name
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
name: locationName,
|
||||
tenantPaymentMethod: tenantPaymentMethod || "none",
|
||||
proofOfPaymentType: proofOfPaymentType || "none",
|
||||
tenantName: tenantName || null,
|
||||
tenantStreet: tenantStreet || null,
|
||||
tenantTown: tenantTown || null,
|
||||
autoBillFwd: autoBillFwd || false,
|
||||
tenantEmail: tenantEmail || null,
|
||||
billFwdStrategy: billFwdStrategy || "when-payed",
|
||||
rentDueNotification: rentDueNotification || false,
|
||||
rentDueDay: rentDueDay || null,
|
||||
rentAmount: rentAmount || null,
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
} else if(yearMonth) {
|
||||
// Always add location to the specified month
|
||||
await dbClient.collection<BillingLocation>("lokacije").insertOne({
|
||||
_id: (new ObjectId()).toHexString(),
|
||||
userId,
|
||||
userEmail,
|
||||
name: locationName,
|
||||
notes: null,
|
||||
tenantPaymentMethod: tenantPaymentMethod || "none",
|
||||
proofOfPaymentType: proofOfPaymentType || "none",
|
||||
tenantName: tenantName || null,
|
||||
tenantStreet: tenantStreet || null,
|
||||
tenantTown: tenantTown || null,
|
||||
autoBillFwd: autoBillFwd || false,
|
||||
tenantEmail: tenantEmail || null,
|
||||
billFwdStrategy: billFwdStrategy || "when-payed",
|
||||
rentDueNotification: rentDueNotification || false,
|
||||
rentDueDay: rentDueDay || null,
|
||||
rentAmount: rentAmount || null,
|
||||
yearMonth: yearMonth,
|
||||
bills: [],
|
||||
});
|
||||
|
||||
// If addToSubsequentMonths is enabled, add to all subsequent months
|
||||
if (addToSubsequentMonths) {
|
||||
// Find all subsequent months that exist in the database
|
||||
const subsequentMonths = await dbClient.collection<BillingLocation>("lokacije")
|
||||
.aggregate([
|
||||
{
|
||||
$match: {
|
||||
userId,
|
||||
$or: [
|
||||
{ "yearMonth.year": { $gt: yearMonth.year } },
|
||||
{
|
||||
"yearMonth.year": yearMonth.year,
|
||||
"yearMonth.month": { $gt: yearMonth.month }
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
$group: {
|
||||
_id: {
|
||||
year: "$yearMonth.year",
|
||||
month: "$yearMonth.month"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
$project: {
|
||||
_id: 0,
|
||||
year: "$_id.year",
|
||||
month: "$_id.month"
|
||||
}
|
||||
},
|
||||
{
|
||||
$sort: {
|
||||
year: 1,
|
||||
month: 1
|
||||
}
|
||||
}
|
||||
])
|
||||
.toArray();
|
||||
|
||||
// For each subsequent month, check if location with same name already exists
|
||||
const locationsToInsert = [];
|
||||
for (const monthData of subsequentMonths) {
|
||||
const existingLocation = await dbClient.collection<BillingLocation>("lokacije")
|
||||
.findOne({
|
||||
userId,
|
||||
name: locationName,
|
||||
"yearMonth.year": monthData.year,
|
||||
"yearMonth.month": monthData.month
|
||||
}, { projection: { bills: 0 } });
|
||||
|
||||
// Only add if location with same name doesn't already exist in that month
|
||||
if (!existingLocation) {
|
||||
locationsToInsert.push({
|
||||
_id: (new ObjectId()).toHexString(),
|
||||
userId,
|
||||
userEmail,
|
||||
name: locationName,
|
||||
notes: null,
|
||||
tenantPaymentMethod: tenantPaymentMethod || "none",
|
||||
proofOfPaymentType: proofOfPaymentType || "none",
|
||||
tenantName: tenantName || null,
|
||||
tenantStreet: tenantStreet || null,
|
||||
tenantTown: tenantTown || null,
|
||||
autoBillFwd: autoBillFwd || false,
|
||||
tenantEmail: tenantEmail || null,
|
||||
billFwdStrategy: billFwdStrategy || "when-payed",
|
||||
rentDueNotification: rentDueNotification || false,
|
||||
rentDueDay: rentDueDay || null,
|
||||
rentAmount: rentAmount || null,
|
||||
yearMonth: { year: monthData.year, month: monthData.month },
|
||||
bills: [],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Insert all new locations at once if any
|
||||
if (locationsToInsert.length > 0) {
|
||||
await dbClient.collection<BillingLocation>("lokacije").insertMany(locationsToInsert);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Redirect to home page with year and month parameters, including success message
|
||||
if (yearMonth) {
|
||||
const locale = await getLocale();
|
||||
await gotoHomeWithMessage(locale, 'locationSaved', yearMonth);
|
||||
}
|
||||
|
||||
// This return is needed for TypeScript, but won't be reached due to redirect
|
||||
return {
|
||||
message: null,
|
||||
errors: undefined,
|
||||
};
|
||||
});
|
||||
|
||||
|
||||
export const fetchAllLocations = withUser(async (user:AuthenticatedUser, year:number) => {
|
||||
|
||||
unstable_noStore();
|
||||
|
||||
const dbClient = await getDbClient();
|
||||
|
||||
const { id: userId } = user;
|
||||
|
||||
// fetch all locations for the given year
|
||||
const locations = await dbClient.collection<BillingLocation>("lokacije")
|
||||
.aggregate<BillingLocation>([
|
||||
{
|
||||
$match: {
|
||||
userId,
|
||||
"yearMonth.year": year,
|
||||
},
|
||||
},
|
||||
// DUPLICATION of block below ... probably added by AI {
|
||||
// DUPLICATION of block below ... probably added by AI $addFields: {
|
||||
// DUPLICATION of block below ... probably added by AI bills: {
|
||||
// DUPLICATION of block below ... probably added by AI $map: {
|
||||
// DUPLICATION of block below ... probably added by AI input: "$bills",
|
||||
// DUPLICATION of block below ... probably added by AI as: "bill",
|
||||
// DUPLICATION of block below ... probably added by AI in: {
|
||||
// DUPLICATION of block below ... probably added by AI _id: "$$bill._id",
|
||||
// DUPLICATION of block below ... probably added by AI name: "$$bill.name",
|
||||
// DUPLICATION of block below ... probably added by AI paid: "$$bill.paid",
|
||||
// DUPLICATION of block below ... probably added by AI billedTo: "$$bill.billedTo",
|
||||
// DUPLICATION of block below ... probably added by AI payedAmount: "$$bill.payedAmount",
|
||||
// DUPLICATION of block below ... probably added by AI hasAttachment: { $ne: ["$$bill.attachment", null] },
|
||||
// DUPLICATION of block below ... probably added by AI },
|
||||
// DUPLICATION of block below ... probably added by AI },
|
||||
// DUPLICATION of block below ... probably added by AI },
|
||||
// DUPLICATION of block below ... probably added by AI },
|
||||
// DUPLICATION of block below ... probably added by AI },
|
||||
{
|
||||
$addFields: {
|
||||
_id: { $toString: "$_id" },
|
||||
bills: {
|
||||
$map: {
|
||||
input: "$bills",
|
||||
as: "bill",
|
||||
in: {
|
||||
_id: { $toString: "$$bill._id" },
|
||||
name: "$$bill.name",
|
||||
paid: "$$bill.paid",
|
||||
billedTo: "$$bill.billedTo",
|
||||
payedAmount: "$$bill.payedAmount",
|
||||
hasAttachment: { $ne: ["$$bill.attachment", null] },
|
||||
proofOfPayment: "$$bill.proofOfPayment",
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
$project: {
|
||||
"_id": 1,
|
||||
// "userId": 0,
|
||||
// "userEmail": 0,
|
||||
"name": 1,
|
||||
// "notes": 0,
|
||||
// "yearMonth": 1,
|
||||
"yearMonth.year": 1,
|
||||
"yearMonth.month": 1,
|
||||
"bills._id": 1,
|
||||
"bills.name": 1,
|
||||
"bills.paid": 1,
|
||||
"bills.hasAttachment": 1,
|
||||
"bills.payedAmount": 1,
|
||||
"bills.proofOfPayment.uploadedAt": 1,
|
||||
"seenByTenantAt": 1,
|
||||
// "bills.attachment": 0,
|
||||
// "bills.notes": 0,
|
||||
// "bills.hub3aText": 1,
|
||||
// project only file name - leave out file content so that
|
||||
// less data is transferred to the client
|
||||
"utilBillsProofOfPayment.fileName": 1,
|
||||
"utilBillsProofOfPayment.uploadedAt": 1,
|
||||
},
|
||||
},
|
||||
{
|
||||
$sort: {
|
||||
"yearMonth.year": -1,
|
||||
"yearMonth.month": -1,
|
||||
name: 1,
|
||||
},
|
||||
},
|
||||
])
|
||||
.toArray();
|
||||
|
||||
return(locations)
|
||||
})
|
||||
|
||||
/*
|
||||
ova metoda je zamijenjena sa jednostavnijom `fetchLocationById`, koja brže radi jer ne provjerava korisnika
|
||||
|
||||
export const fetchLocationByUserAndId = withUser(async (user:AuthenticatedUser, locationID:string) => {
|
||||
|
||||
unstable_noStore();
|
||||
|
||||
const dbClient = await getDbClient();
|
||||
|
||||
const { id: userId } = user;
|
||||
|
||||
// find a location with the given locationID
|
||||
const billLocation = await dbClient.collection<BillingLocation>("lokacije")
|
||||
.findOne(
|
||||
{ _id: locationID, userId },
|
||||
{
|
||||
projection: {
|
||||
// don't include the attachment binary data in the response
|
||||
"bills.attachment.fileContentsBase64": 0,
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
if(!billLocation) {
|
||||
console.log(`Location ${locationID} not found`);
|
||||
return(null);
|
||||
}
|
||||
|
||||
return(billLocation);
|
||||
});
|
||||
*/
|
||||
|
||||
export const fetchLocationById = async (locationID:string) => {
|
||||
|
||||
unstable_noStore();
|
||||
|
||||
const dbClient = await getDbClient();
|
||||
|
||||
// find a location with the given locationID
|
||||
const billLocation = await dbClient.collection<BillingLocation>("lokacije")
|
||||
.findOne(
|
||||
{ _id: locationID },
|
||||
{
|
||||
projection: {
|
||||
// don't include the attachment binary data in the response
|
||||
"bills.attachment.fileContentsBase64": 0,
|
||||
"utilBillsProofOfPayment.fileContentsBase64": 0,
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
if(!billLocation) {
|
||||
console.log(`Location ${locationID} not found`);
|
||||
return(null);
|
||||
}
|
||||
|
||||
return(billLocation);
|
||||
};
|
||||
|
||||
export const deleteLocationById = withUser(async (user:AuthenticatedUser, locationID:string, yearMonth:YearMonth, _prevState:any, formData: FormData) => {
|
||||
|
||||
unstable_noStore();
|
||||
|
||||
const dbClient = await getDbClient();
|
||||
|
||||
const { id: userId } = user;
|
||||
|
||||
const deleteInSubsequentMonths = formData.get('deleteInSubsequentMonths') === 'on';
|
||||
|
||||
if (deleteInSubsequentMonths) {
|
||||
// Get the location name first to find all locations with the same name
|
||||
const location = await dbClient.collection<BillingLocation>("lokacije")
|
||||
.findOne({ _id: locationID, userId }, { projection: { name: 1 } });
|
||||
|
||||
if (location) {
|
||||
// Delete all locations with the same name in current and subsequent months
|
||||
await dbClient.collection<BillingLocation>("lokacije").deleteMany({
|
||||
userId,
|
||||
name: location.name,
|
||||
$or: [
|
||||
{ "yearMonth.year": { $gt: yearMonth.year } },
|
||||
{
|
||||
"yearMonth.year": yearMonth.year,
|
||||
"yearMonth.month": { $gte: yearMonth.month }
|
||||
}
|
||||
]
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// Delete only the specific location (current behavior)
|
||||
await dbClient.collection<BillingLocation>("lokacije").deleteOne({ _id: locationID, userId });
|
||||
}
|
||||
|
||||
const locale = await getLocale();
|
||||
await gotoHomeWithMessage(locale, 'locationDeleted');
|
||||
|
||||
// This return is needed for TypeScript, but won't be reached due to redirect
|
||||
return {
|
||||
message: null,
|
||||
errors: undefined,
|
||||
};
|
||||
})
|
||||
|
||||
/**
|
||||
* Sets the `seenByTenantAt` flag to true for a specific location.
|
||||
*
|
||||
* This function marks a location as viewed by the tenant. It first checks if the flag
|
||||
* is already set to true to avoid unnecessary database updates.
|
||||
*
|
||||
* @param {string} locationID - The ID of the location to update
|
||||
* @returns {Promise<void>}
|
||||
*
|
||||
* @example
|
||||
* await setseenByTenantAt("507f1f77bcf86cd799439011");
|
||||
*/
|
||||
export const setSeenByTenantAt = async (locationID: string): Promise<void> => {
|
||||
const dbClient = await getDbClient();
|
||||
|
||||
// First check if the location exists and if seenByTenantAt is already true
|
||||
const location = await dbClient.collection<BillingLocation>("lokacije")
|
||||
.findOne({ _id: locationID });
|
||||
|
||||
// If location doesn't exist or seenByTenantAt is already true, no update needed
|
||||
if (!location || location.seenByTenantAt) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Update the location to mark it as seen by tenant
|
||||
await dbClient.collection<BillingLocation>("lokacije")
|
||||
.updateOne(
|
||||
{ _id: locationID },
|
||||
{ $set: { seenByTenantAt: new Date() } }
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Serializes a file attachment to be stored in the database
|
||||
* @param file - The file to serialize
|
||||
* @returns BillAttachment object or null if file is invalid
|
||||
*/
|
||||
const serializeAttachment = async (file: File | null):Promise<FileAttachment | null> => {
|
||||
if (!file) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const {
|
||||
name: fileName,
|
||||
size: fileSize,
|
||||
type: fileType,
|
||||
lastModified: fileLastModified,
|
||||
} = file;
|
||||
|
||||
if(!fileName || fileName === 'undefined' || fileSize === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Convert file contents to base64 for database storage
|
||||
const fileContents = await file.arrayBuffer();
|
||||
const fileContentsBase64 = Buffer.from(fileContents).toString('base64');
|
||||
|
||||
return {
|
||||
fileName,
|
||||
fileSize,
|
||||
fileType,
|
||||
fileLastModified,
|
||||
fileContentsBase64,
|
||||
uploadedAt: new Date(),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Uploads a single proof of payment for all utility bills in a location
|
||||
* SECURITY: Validates checksum, TTL, PDF content, and rate limits by IP
|
||||
*
|
||||
* @param shareId - Combined location ID + checksum (40 chars)
|
||||
* @param formData - FormData containing the PDF file
|
||||
* @param ipAddress - Optional IP address for rate limiting
|
||||
* @returns Promise with success status
|
||||
*/
|
||||
export const uploadUtilBillsProofOfPayment = async (
|
||||
shareId: string,
|
||||
formData: FormData,
|
||||
ipAddress?: string
|
||||
): Promise<{ success: boolean; error?: string }> => {
|
||||
|
||||
unstable_noStore();
|
||||
|
||||
try {
|
||||
// 1. EXTRACT AND VALIDATE CHECKSUM (stateless, fast)
|
||||
const extracted = extractShareId(shareId);
|
||||
if (!extracted) {
|
||||
console.log('shareID extraction failed');
|
||||
return { success: false, error: 'Invalid share link' };
|
||||
}
|
||||
|
||||
const { locationId: locationID, checksum } = extracted;
|
||||
|
||||
if (!validateShareChecksum(locationID, checksum)) {
|
||||
console.log('shareID checksum validation failed');
|
||||
return { success: false, error: 'Invalid share link' };
|
||||
}
|
||||
|
||||
// 2. RATE LIMITING (per IP)
|
||||
if (ipAddress) {
|
||||
const rateLimit = checkUploadRateLimit(ipAddress);
|
||||
if (!rateLimit.allowed) {
|
||||
return {
|
||||
success: false,
|
||||
error: `Too many uploads. Try again in ${Math.ceil(rateLimit.resetIn / 60)} minutes.`
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// 3. DATABASE VALIDATION
|
||||
const dbClient = await getDbClient();
|
||||
|
||||
const location = await dbClient.collection<BillingLocation>("lokacije")
|
||||
.findOne({ _id: locationID }, { projection: { userId: 1, utilBillsProofOfPayment: 1, shareTTL: 1 } });
|
||||
|
||||
if (!location || !location.userId) {
|
||||
return { success: false, error: 'Invalid request' };
|
||||
}
|
||||
|
||||
// Check sharing is active and not expired
|
||||
if (!location.shareTTL || new Date() > location.shareTTL) {
|
||||
return { success: false, error: 'This content is no longer shared' };
|
||||
}
|
||||
|
||||
// Check if proof of payment already uploaded
|
||||
if (location.utilBillsProofOfPayment) {
|
||||
return { success: false, error: 'Proof of payment already uploaded for this location' };
|
||||
}
|
||||
|
||||
// 4. FILE VALIDATION
|
||||
const file = formData.get('utilBillsProofOfPayment') as File;
|
||||
|
||||
if (!file || file.size === 0) {
|
||||
return { success: false, error: 'No file provided' };
|
||||
}
|
||||
|
||||
// Validate PDF content (magic bytes, not just MIME type)
|
||||
const pdfValidation = await validatePdfFile(file);
|
||||
if (!pdfValidation.valid) {
|
||||
return { success: false, error: pdfValidation.error };
|
||||
}
|
||||
|
||||
// 5. SERIALIZE & STORE FILE
|
||||
const attachment = await serializeAttachment(file);
|
||||
|
||||
if (!attachment) {
|
||||
return { success: false, error: 'Failed to process file' };
|
||||
}
|
||||
|
||||
// 6. UPDATE DATABASE
|
||||
await dbClient.collection<BillingLocation>("lokacije")
|
||||
.updateOne(
|
||||
{ _id: locationID },
|
||||
{ $set: {
|
||||
utilBillsProofOfPayment: attachment
|
||||
} }
|
||||
);
|
||||
|
||||
// 7. REVALIDATE CACHE
|
||||
revalidatePath(`/share/location/${shareId}`, 'page');
|
||||
|
||||
return { success: true };
|
||||
} catch (error: any) {
|
||||
console.error('Upload error:', error);
|
||||
return { success: false, error: 'Upload failed. Please try again.' };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate/activate share link for location
|
||||
* Called when owner clicks "Share" button
|
||||
* Sets shareTTL to 10 days from now
|
||||
*/
|
||||
export const generateShareLink = withUser(
|
||||
async (user: AuthenticatedUser, locationId: string) => {
|
||||
|
||||
const { id: userId } = user;
|
||||
const dbClient = await getDbClient();
|
||||
|
||||
// Verify ownership
|
||||
const location = await dbClient.collection<BillingLocation>("lokacije").findOne({
|
||||
_id: locationId,
|
||||
userId
|
||||
});
|
||||
|
||||
if (!location) {
|
||||
return { error: 'Location not found' };
|
||||
}
|
||||
|
||||
// Calculate TTL (10 days from now, configurable)
|
||||
const initialDays = parseInt(process.env.SHARE_TTL_INITIAL_DAYS || '10', 10);
|
||||
const shareTTL = new Date(Date.now() + initialDays * 24 * 60 * 60 * 1000);
|
||||
|
||||
// Activate sharing by setting TTL
|
||||
await dbClient.collection<BillingLocation>("lokacije").updateOne(
|
||||
{ _id: locationId },
|
||||
{
|
||||
$set: { shareTTL },
|
||||
$unset: { shareFirstVisitedAt: "" } // Reset first visit tracking
|
||||
}
|
||||
);
|
||||
|
||||
// Generate combined share ID (locationId + checksum)
|
||||
const shareId = generateShareId(locationId);
|
||||
|
||||
// Build share URL
|
||||
const baseUrl = process.env.NEXTAUTH_URL || 'http://localhost:3000';
|
||||
const shareUrl = `${baseUrl}/share/location/${shareId}`;
|
||||
|
||||
return { shareUrl };
|
||||
}
|
||||
);
|
||||
|
||||
/**
|
||||
* Validate share link and update TTL on first visit
|
||||
* Called when tenant visits share link
|
||||
*
|
||||
* SECURITY:
|
||||
* 1. Extracts locationId and checksum from combined shareId
|
||||
* 2. Validates checksum (stateless, prevents enumeration)
|
||||
* 3. Checks TTL in database (time-based access control)
|
||||
* 4. Marks first visit and resets TTL to 1 hour
|
||||
*
|
||||
* @param shareId - Combined ID (locationId + checksum, 40 chars)
|
||||
* @returns Object with validation result and extracted locationId
|
||||
*/
|
||||
export async function validateShareAccess(
|
||||
shareId: string
|
||||
): Promise<{ valid: boolean; locationId?: string; error?: string }> {
|
||||
|
||||
// 1. Extract locationId and checksum from combined ID
|
||||
const extracted = extractShareId(shareId);
|
||||
if (!extracted) {
|
||||
console.log('shareID extraction failed');
|
||||
return { valid: false, error: 'Invalid share link' };
|
||||
}
|
||||
|
||||
const { locationId, checksum } = extracted;
|
||||
|
||||
// 2. Validate checksum FIRST (before DB query - stateless validation)
|
||||
if (!validateShareChecksum(locationId, checksum)) {
|
||||
console.log('shareID checksum validation failed');
|
||||
return { valid: false, error: 'Invalid share link' };
|
||||
}
|
||||
|
||||
// 3. Check TTL in database
|
||||
const dbClient = await getDbClient();
|
||||
const location = await dbClient.collection<BillingLocation>("lokacije").findOne(
|
||||
{ _id: locationId },
|
||||
{ projection: { shareTTL: 1, shareFirstVisitedAt: 1 } }
|
||||
);
|
||||
|
||||
if (!location) {
|
||||
console.log('Location not found for shareID');
|
||||
return { valid: false, error: 'Invalid share link' };
|
||||
}
|
||||
|
||||
// 4. Check if sharing is enabled
|
||||
if (!location.shareTTL) {
|
||||
return { valid: false, error: 'This content is no longer shared' };
|
||||
}
|
||||
|
||||
// 5. Check if TTL expired
|
||||
const now = new Date();
|
||||
if (now > location.shareTTL) {
|
||||
// Clean up expired share
|
||||
await dbClient.collection<BillingLocation>("lokacije").updateOne(
|
||||
{ _id: locationId },
|
||||
{ $unset: { shareTTL: "", shareFirstVisitedAt: "" } }
|
||||
);
|
||||
|
||||
return { valid: false, error: 'This content is no longer shared' };
|
||||
}
|
||||
|
||||
// 6. Mark first visit if applicable (resets TTL to 1 hour)
|
||||
if (!location.shareFirstVisitedAt) {
|
||||
const visitHours = parseInt(process.env.SHARE_TTL_AFTER_VISIT_HOURS || '1', 10);
|
||||
const newTTL = new Date(Date.now() + visitHours * 60 * 60 * 1000);
|
||||
|
||||
await dbClient.collection<BillingLocation>("lokacije").updateOne(
|
||||
{
|
||||
_id: locationId,
|
||||
shareFirstVisitedAt: null // Only update if not already set
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
shareFirstVisitedAt: new Date(),
|
||||
shareTTL: newTTL
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
return { valid: true, locationId };
|
||||
}
|
||||
220
web-app/app/lib/actions/monthActions.ts
Normal file
220
web-app/app/lib/actions/monthActions.ts
Normal file
@@ -0,0 +1,220 @@
|
||||
'use server';
|
||||
|
||||
import { getDbClient } from '../dbClient';
|
||||
import { ObjectId } from 'mongodb';
|
||||
import { Bill, BillingLocation, YearMonth } from '../db-types';
|
||||
import { AuthenticatedUser } from '../types/next-auth';
|
||||
import { withUser } from '../auth';
|
||||
import { unstable_noStore as noStore, unstable_noStore, revalidatePath } from 'next/cache';
|
||||
import { getLocale } from 'next-intl/server';
|
||||
import { gotoHomeWithMessage } from './navigationActions';
|
||||
|
||||
/**
|
||||
* Server-side action which adds a new month to the database
|
||||
* @param locationId location of the bill
|
||||
* @param billId ID of the bill
|
||||
* @param prevState previous state of the form
|
||||
* @param formData form data
|
||||
* @returns
|
||||
*/
|
||||
export const addMonth = withUser(async (user:AuthenticatedUser, { year, month }: YearMonth) => {
|
||||
noStore();
|
||||
|
||||
const { id: userId } = user;
|
||||
|
||||
// update the bill in the mongodb
|
||||
const dbClient = await getDbClient();
|
||||
|
||||
const prevYear = month === 1 ? year - 1 : year;
|
||||
const prevMonth = month === 1 ? 12 : month - 1;
|
||||
|
||||
// find all locations for the previous month
|
||||
const prevMonthLocations = await dbClient.collection<BillingLocation>("lokacije").find({
|
||||
userId, // make sure that the locations belongs to the user
|
||||
yearMonth: {
|
||||
year: prevYear,
|
||||
month: prevMonth,
|
||||
}
|
||||
});
|
||||
|
||||
const newMonthLocationsCursor = prevMonthLocations.map((prevLocation) => {
|
||||
return({
|
||||
// copy all the properties from the previous location
|
||||
...prevLocation,
|
||||
// clear properties specific to the month
|
||||
seenByTenantAt: undefined,
|
||||
utilBillsProofOfPayment: undefined,
|
||||
// assign a new ID
|
||||
_id: (new ObjectId()).toHexString(),
|
||||
yearMonth: {
|
||||
year: year,
|
||||
month: month,
|
||||
},
|
||||
// copy bill array, but set all bills to unpaid and remove attachments and notes
|
||||
bills: prevLocation.bills.map((bill) => {
|
||||
return {
|
||||
...bill,
|
||||
paid: false,
|
||||
attachment: null,
|
||||
notes: null,
|
||||
payedAmount: null,
|
||||
hub3aText: undefined,
|
||||
} as Bill
|
||||
})
|
||||
} as BillingLocation);
|
||||
});
|
||||
|
||||
const newMonthLocations = await newMonthLocationsCursor.toArray()
|
||||
await dbClient.collection<BillingLocation>("lokacije").insertMany(newMonthLocations);
|
||||
});
|
||||
|
||||
export const fetchAvailableYears = withUser(async (user:AuthenticatedUser) => {
|
||||
noStore();
|
||||
|
||||
const { id: userId } = user;
|
||||
|
||||
const dbClient = await getDbClient();
|
||||
|
||||
// query mnogodb for all `yearMonth` values
|
||||
const years:number[] = await dbClient.collection<BillingLocation>("lokacije")
|
||||
.distinct("yearMonth.year", { userId })
|
||||
|
||||
// sort the years in descending order
|
||||
const sortedYears = years.sort((a, b) => b - a);
|
||||
|
||||
return(sortedYears);
|
||||
})
|
||||
|
||||
/**
|
||||
* Fetches all locations for a specific month for the authenticated user
|
||||
* Only projects essential fields needed for the multi-bill-edit page
|
||||
* @param yearMonth - The year and month to fetch
|
||||
* @returns Array of locations with minimal bill data
|
||||
*/
|
||||
export const getLocationsByMonth = withUser(async (user: AuthenticatedUser, yearMonth: YearMonth) => {
|
||||
|
||||
unstable_noStore();
|
||||
|
||||
const { id: userId } = user;
|
||||
const dbClient = await getDbClient();
|
||||
|
||||
// Use aggregation pipeline to calculate hasAttachment field
|
||||
const locations = await dbClient.collection<BillingLocation>("lokacije")
|
||||
.aggregate([
|
||||
{
|
||||
$match: {
|
||||
userId,
|
||||
yearMonth: {
|
||||
year: yearMonth.year,
|
||||
month: yearMonth.month,
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
$addFields: {
|
||||
_id: { $toString: "$_id" },
|
||||
bills: {
|
||||
$map: {
|
||||
input: "$bills",
|
||||
as: "bill",
|
||||
in: {
|
||||
_id: { $toString: "$$bill._id" },
|
||||
name: "$$bill.name",
|
||||
paid: "$$bill.paid",
|
||||
hasAttachment: { $ne: ["$$bill.attachment", null] },
|
||||
proofOfPayment: "$$bill.proofOfPayment",
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
$project: {
|
||||
"_id": 1,
|
||||
"name": 1,
|
||||
"yearMonth.year": 1,
|
||||
"yearMonth.month": 1,
|
||||
"bills._id": 1,
|
||||
"bills.name": 1,
|
||||
"bills.paid": 1,
|
||||
"bills.hasAttachment": 1,
|
||||
"bills.proofOfPayment.uploadedAt": 1,
|
||||
}
|
||||
},
|
||||
{
|
||||
$sort: {
|
||||
name: 1,
|
||||
},
|
||||
},
|
||||
])
|
||||
.toArray();
|
||||
|
||||
return locations as Array<BillingLocation>;
|
||||
});
|
||||
|
||||
/**
|
||||
* Updates the paid status of bills for locations in a specific month
|
||||
* @param yearMonth - The year and month to update
|
||||
* @param updates - Array of updates with locationId, billId, and paid status
|
||||
* @returns Success status
|
||||
*/
|
||||
export const updateMonth = withUser(async (
|
||||
user: AuthenticatedUser,
|
||||
yearMonth: YearMonth,
|
||||
updates: Array<{ locationId: string; billId: string; paid: boolean }>
|
||||
) => {
|
||||
unstable_noStore();
|
||||
|
||||
const { id: userId } = user;
|
||||
const dbClient = await getDbClient();
|
||||
|
||||
// Group updates by location to minimize database operations
|
||||
const updatesByLocation = updates.reduce((acc, update) => {
|
||||
if (!acc[update.locationId]) {
|
||||
acc[update.locationId] = [];
|
||||
}
|
||||
acc[update.locationId].push(update);
|
||||
return acc;
|
||||
}, {} as Record<string, typeof updates>);
|
||||
|
||||
// Perform bulk updates
|
||||
const updatePromises = Object.entries(updatesByLocation).map(
|
||||
async ([locationId, locationUpdates]) => {
|
||||
// For each bill update in this location
|
||||
const billUpdatePromises = locationUpdates.map(({ billId, paid }) =>
|
||||
dbClient.collection<BillingLocation>("lokacije").updateOne(
|
||||
{
|
||||
_id: locationId,
|
||||
userId, // Ensure the location belongs to the authenticated user
|
||||
yearMonth: {
|
||||
year: yearMonth.year,
|
||||
month: yearMonth.month,
|
||||
},
|
||||
'bills._id': billId,
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
'bills.$.paid': paid,
|
||||
},
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
return Promise.all(billUpdatePromises);
|
||||
}
|
||||
);
|
||||
|
||||
await Promise.all(updatePromises);
|
||||
|
||||
// Revalidate the home page and multi-edit page to show fresh data
|
||||
revalidatePath('/home');
|
||||
revalidatePath(`/home/multi-bill-edit/${yearMonth.year}/${yearMonth.month}`);
|
||||
|
||||
// Redirect to home page with year and month parameters, including success message
|
||||
if (yearMonth) {
|
||||
const locale = await getLocale();
|
||||
await gotoHomeWithMessage(locale, 'bill-multi-edit-saved', yearMonth);
|
||||
}
|
||||
|
||||
return { success: true };
|
||||
});
|
||||
23
web-app/app/lib/actions/navigationActions.ts
Normal file
23
web-app/app/lib/actions/navigationActions.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
'use server';
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { redirect } from 'next/navigation';
|
||||
import { YearMonth } from "../db-types";
|
||||
|
||||
export async function gotoHome({year, month}: YearMonth) {
|
||||
const path = `/home?year=${year}&month=${month}`;
|
||||
await gotoUrl(path);
|
||||
}
|
||||
|
||||
export async function gotoHomeWithMessage(locale: string, message: string, yearMonth?: YearMonth) {
|
||||
const path = yearMonth
|
||||
? `/${locale}/home?year=${yearMonth.year}&month=${yearMonth.month}&${message}=true`
|
||||
: `/${locale}/home?${message}=true`;
|
||||
await gotoUrl(path);
|
||||
}
|
||||
|
||||
export async function gotoUrl(path: string) {
|
||||
console.log(path)
|
||||
revalidatePath(path, "page");
|
||||
redirect(path);
|
||||
}
|
||||
81
web-app/app/lib/actions/printActions.ts
Normal file
81
web-app/app/lib/actions/printActions.ts
Normal file
@@ -0,0 +1,81 @@
|
||||
'use server';
|
||||
|
||||
import { getDbClient } from '../dbClient';
|
||||
import { BillingLocation } from '../db-types';
|
||||
import { AuthenticatedUser } from '../types/next-auth';
|
||||
import { withUser } from '../auth';
|
||||
import { unstable_noStore as noStore } from 'next/cache';
|
||||
|
||||
export interface PrintBarcodeData {
|
||||
locationName: string;
|
||||
billName: string;
|
||||
/**
|
||||
* LEGACY SUPPORT ... untill all bills have been migrated
|
||||
* @deprecated Use `hub3aText` instead.
|
||||
*/
|
||||
barcodeImage?: string;
|
||||
hub3aText?: string;
|
||||
payedAmount?: number | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches all bills with barcode images for a specific month for printing
|
||||
* @param year - Year to fetch data for
|
||||
* @param month - Month to fetch data for (1-12)
|
||||
* @returns Array of barcode data for printing
|
||||
*/
|
||||
export const fetchBarcodeDataForPrint = withUser(async (user: AuthenticatedUser, year: number, month: number): Promise<PrintBarcodeData[]> => {
|
||||
noStore();
|
||||
|
||||
const { id: userId } = user;
|
||||
const dbClient = await getDbClient();
|
||||
|
||||
const yearMonth = `${year}-${month.toString().padStart(2, '0')}`;
|
||||
|
||||
// Fetch all locations for the specific month
|
||||
const locations = await dbClient.collection<BillingLocation>("lokacije")
|
||||
.find({
|
||||
userId, // ensure data belongs to authenticated user
|
||||
"yearMonth.year": year,
|
||||
"yearMonth.month": month
|
||||
}, {
|
||||
// project only necessary fields
|
||||
projection: {
|
||||
name: 1,
|
||||
bills: 1,
|
||||
barcodeImage: 1,
|
||||
hub3aText: 1,
|
||||
payedAmount: 1,
|
||||
paid: 1
|
||||
}
|
||||
})
|
||||
.toArray();
|
||||
|
||||
// Extract and flatten barcode data
|
||||
const printData: PrintBarcodeData[] = [];
|
||||
|
||||
for (const location of locations) {
|
||||
for (const bill of location.bills) {
|
||||
// Only include bills that have barcode images and are NOT PAID
|
||||
if ( ( bill.hub3aText && bill.hub3aText.trim() !== "" && !bill.paid) ) {
|
||||
printData.push({
|
||||
locationName: location.name,
|
||||
billName: bill.name,
|
||||
barcodeImage: bill.barcodeImage, // LEGACY SUPPORT ... untill all bills have been migrated
|
||||
hub3aText: bill.hub3aText,
|
||||
payedAmount: bill.payedAmount
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Sort by location name, then by bill name for consistent ordering
|
||||
printData.sort((a, b) => {
|
||||
if (a.locationName !== b.locationName) {
|
||||
return a.locationName.localeCompare(b.locationName);
|
||||
}
|
||||
return a.billName.localeCompare(b.billName);
|
||||
});
|
||||
|
||||
return printData;
|
||||
});
|
||||
220
web-app/app/lib/actions/userSettingsActions.ts
Normal file
220
web-app/app/lib/actions/userSettingsActions.ts
Normal file
@@ -0,0 +1,220 @@
|
||||
'use server';
|
||||
|
||||
import { z } from 'zod';
|
||||
import { getDbClient } from '../dbClient';
|
||||
import { UserSettings } from '../db-types';
|
||||
import { withUser } from '@/app/lib/auth';
|
||||
import { AuthenticatedUser } from '../types/next-auth';
|
||||
import { unstable_noStore as noStore } from 'next/cache';
|
||||
import { IntlTemplateFn } from '@/app/i18n';
|
||||
import { getTranslations, getLocale } from "next-intl/server";
|
||||
import { revalidatePath } from 'next/cache';
|
||||
import { gotoHomeWithMessage } from './navigationActions';
|
||||
import * as IBAN from 'iban';
|
||||
|
||||
export type State = {
|
||||
errors?: {
|
||||
ownerName?: string[];
|
||||
ownerStreet?: string[];
|
||||
ownerTown?: string[];
|
||||
ownerIBAN?: string[];
|
||||
currency?: string[];
|
||||
ownerRevolutProfileName?: string[];
|
||||
};
|
||||
message?: string | null;
|
||||
success?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* Schema for validating user settings form fields
|
||||
*/
|
||||
const FormSchema = (t: IntlTemplateFn) => z.object({
|
||||
currency: z.string().optional(),
|
||||
enableIbanPayment: z.boolean().optional(),
|
||||
ownerName: z.string().max(25).optional(),
|
||||
ownerStreet: z.string().max(25).optional(),
|
||||
ownerTown: z.string().max(27).optional(),
|
||||
ownerIBAN: z.string()
|
||||
.optional()
|
||||
.refine(
|
||||
(val) => {
|
||||
if (!val || val.trim() === '') return true;
|
||||
// Remove spaces and validate using iban.js library
|
||||
const cleaned = val.replace(/\s/g, '').toUpperCase();
|
||||
return IBAN.isValid(cleaned);
|
||||
},
|
||||
{ message: t("owner-iban-invalid") }
|
||||
),
|
||||
enableRevolutPayment: z.boolean().optional(),
|
||||
ownerRevolutProfileName: z.string().max(25).optional(),
|
||||
})
|
||||
.refine((data) => {
|
||||
if (data.enableIbanPayment) {
|
||||
return !!data.ownerName && data.ownerName.trim().length > 0;
|
||||
}
|
||||
return true;
|
||||
}, {
|
||||
message: t("owner-name-required"),
|
||||
path: ["ownerName"],
|
||||
})
|
||||
.refine((data) => {
|
||||
if (data.enableIbanPayment) {
|
||||
return !!data.ownerStreet && data.ownerStreet.trim().length > 0;
|
||||
}
|
||||
return true;
|
||||
}, {
|
||||
message: t("owner-street-required"),
|
||||
path: ["ownerStreet"],
|
||||
})
|
||||
.refine((data) => {
|
||||
if (data.enableIbanPayment) {
|
||||
return !!data.ownerTown && data.ownerTown.trim().length > 0;
|
||||
}
|
||||
return true;
|
||||
}, {
|
||||
message: t("owner-town-required"),
|
||||
path: ["ownerTown"],
|
||||
})
|
||||
.refine((data) => {
|
||||
if (data.enableIbanPayment) {
|
||||
if (!data.ownerIBAN || data.ownerIBAN.trim().length === 0) {
|
||||
return false;
|
||||
}
|
||||
// Validate IBAN format when required
|
||||
const cleaned = data.ownerIBAN.replace(/\s/g, '').toUpperCase();
|
||||
return IBAN.isValid(cleaned);
|
||||
}
|
||||
return true;
|
||||
}, {
|
||||
message: t("owner-iban-required"),
|
||||
path: ["ownerIBAN"],
|
||||
})
|
||||
.refine((data) => {
|
||||
if (data.enableIbanPayment) {
|
||||
return !!data.currency && data.currency.trim().length > 0;
|
||||
}
|
||||
return true;
|
||||
}, {
|
||||
message: t("currency-required"),
|
||||
path: ["currency"],
|
||||
})
|
||||
.refine((data) => {
|
||||
if (data.enableRevolutPayment) {
|
||||
return !!data.ownerRevolutProfileName && data.ownerRevolutProfileName.trim().length > 0;
|
||||
}
|
||||
return true;
|
||||
}, {
|
||||
message: t("owner-revolut-profile-required"),
|
||||
path: ["ownerRevolutProfileName"],
|
||||
})
|
||||
.refine((data) => {
|
||||
if (data.enableRevolutPayment && data.ownerRevolutProfileName) {
|
||||
const profileName = data.ownerRevolutProfileName.trim();
|
||||
// Must start with @ and contain only English letters and numbers
|
||||
return /^@[a-zA-Z0-9]+$/.test(profileName);
|
||||
}
|
||||
return true;
|
||||
}, {
|
||||
message: t("owner-revolut-profile-invalid"),
|
||||
path: ["ownerRevolutProfileName"],
|
||||
});
|
||||
|
||||
/**
|
||||
* Get user settings
|
||||
*/
|
||||
export const getUserSettings = withUser(async (user: AuthenticatedUser) => {
|
||||
noStore();
|
||||
|
||||
const dbClient = await getDbClient();
|
||||
const { id: userId } = user;
|
||||
|
||||
const userSettings = await dbClient.collection<UserSettings>("userSettings")
|
||||
.findOne({ userId });
|
||||
|
||||
return userSettings;
|
||||
});
|
||||
|
||||
/**
|
||||
* Get user settings by userId (without authentication)
|
||||
* Used for public/shared pages where we need to display owner's payment information
|
||||
*/
|
||||
export const getUserSettingsByUserId = async (userId: string): Promise<UserSettings | null> => {
|
||||
noStore();
|
||||
|
||||
const dbClient = await getDbClient();
|
||||
|
||||
const userSettings = await dbClient.collection<UserSettings>("userSettings")
|
||||
.findOne({ userId });
|
||||
|
||||
return userSettings;
|
||||
};
|
||||
|
||||
/**
|
||||
* Update user settings
|
||||
*/
|
||||
export const updateUserSettings = withUser(async (user: AuthenticatedUser, prevState: State, formData: FormData) => {
|
||||
noStore();
|
||||
|
||||
const t = await getTranslations("user-settings-form.validation");
|
||||
|
||||
const validatedFields = FormSchema(t).safeParse({
|
||||
ownerName: formData.get('ownerName') || undefined,
|
||||
ownerStreet: formData.get('ownerStreet') || undefined,
|
||||
ownerTown: formData.get('ownerTown') || undefined,
|
||||
ownerIBAN: formData.get('ownerIBAN') || undefined,
|
||||
currency: formData.get('currency') || undefined,
|
||||
enableIbanPayment: formData.get('enableIbanPayment') === 'on' ? true : false,
|
||||
enableRevolutPayment: formData.get('enableRevolutPayment') === 'on' ? true : false,
|
||||
ownerRevolutProfileName: formData.get('ownerRevolutProfileName') || undefined,
|
||||
});
|
||||
|
||||
// If form validation fails, return errors early. Otherwise, continue...
|
||||
if (!validatedFields.success) {
|
||||
return {
|
||||
errors: validatedFields.error.flatten().fieldErrors,
|
||||
message: t("validation-failed"),
|
||||
success: false,
|
||||
};
|
||||
}
|
||||
|
||||
const { enableIbanPayment, ownerName, ownerStreet, ownerTown, ownerIBAN, currency, enableRevolutPayment, ownerRevolutProfileName } = validatedFields.data;
|
||||
|
||||
// Normalize IBAN: remove spaces and convert to uppercase
|
||||
const normalizedOwnerIBAN = ownerIBAN ? ownerIBAN.replace(/\s/g, '').toUpperCase() : null;
|
||||
|
||||
// Update the user settings in MongoDB
|
||||
const dbClient = await getDbClient();
|
||||
const { id: userId } = user;
|
||||
|
||||
const userSettings: UserSettings = {
|
||||
userId,
|
||||
enableIbanPayment: enableIbanPayment ?? false,
|
||||
ownerName: ownerName ?? undefined,
|
||||
ownerStreet: ownerStreet ?? undefined,
|
||||
ownerTown: ownerTown ?? undefined,
|
||||
ownerIBAN: normalizedOwnerIBAN,
|
||||
currency: currency ?? undefined,
|
||||
enableRevolutPayment: enableRevolutPayment ?? false,
|
||||
ownerRevolutProfileName: ownerRevolutProfileName ?? undefined,
|
||||
};
|
||||
|
||||
await dbClient.collection<UserSettings>("userSettings")
|
||||
.updateOne(
|
||||
{ userId },
|
||||
{ $set: userSettings },
|
||||
{ upsert: true }
|
||||
);
|
||||
|
||||
revalidatePath('/settings');
|
||||
|
||||
// Get current locale and redirect to home with success message
|
||||
const locale = await getLocale();
|
||||
await gotoHomeWithMessage(locale, 'userSettingsSaved');
|
||||
|
||||
// This return is needed for TypeScript, but won't be reached due to redirect
|
||||
return {
|
||||
message: null,
|
||||
errors: {},
|
||||
success: true,
|
||||
};
|
||||
});
|
||||
Reference in New Issue
Block a user