text changes

This commit is contained in:
jackiettran
2026-01-21 19:20:07 -05:00
parent 420e0efeb4
commit 5d3c124d3e
31 changed files with 16387 additions and 4053 deletions

View File

@@ -10,7 +10,7 @@ module.exports = {
}, },
down: async (queryInterface, Sequelize) => { down: async (queryInterface, Sequelize) => {
// Revert to original VARCHAR(255)[] - note: this may fail if data exceeds 255 chars // Revert to original VARCHAR(255)[]
await queryInterface.changeColumn("Items", "images", { await queryInterface.changeColumn("Items", "images", {
type: Sequelize.ARRAY(Sequelize.STRING), type: Sequelize.ARRAY(Sequelize.STRING),
defaultValue: [], defaultValue: [],

View File

@@ -20,7 +20,7 @@ module.exports = {
}, },
down: async (queryInterface, Sequelize) => { down: async (queryInterface, Sequelize) => {
// Revert to original VARCHAR(255) - note: this may fail if data exceeds 255 chars // Revert to original VARCHAR(255)
await Promise.all([ await Promise.all([
queryInterface.changeColumn("Users", "profileImage", { queryInterface.changeColumn("Users", "profileImage", {
type: Sequelize.STRING, type: Sequelize.STRING,

View File

@@ -11,7 +11,7 @@ module.exports = {
down: async (queryInterface, Sequelize) => { down: async (queryInterface, Sequelize) => {
console.log( console.log(
"Note: PostgreSQL does not support removing ENUM values. " + "PostgreSQL does not support removing ENUM values. " +
"'requires_action' will remain in the enum but will not be used.", "'requires_action' will remain in the enum but will not be used.",
); );
}, },

View File

@@ -265,7 +265,7 @@ const User = sequelize.define(
} }
}, },
}, },
} },
); );
User.prototype.comparePassword = async function (password) { User.prototype.comparePassword = async function (password) {
@@ -457,7 +457,7 @@ User.prototype.unbanUser = async function () {
bannedAt: null, bannedAt: null,
bannedBy: null, bannedBy: null,
banReason: null, banReason: null,
// Note: We don't increment jwtVersion on unban - user will need to log in fresh // We don't increment jwtVersion on unban - user will need to log in fresh
}); });
}; };
@@ -467,7 +467,7 @@ const TwoFactorService = require("../services/TwoFactorService");
// Store pending TOTP secret during setup // Store pending TOTP secret during setup
User.prototype.storePendingTotpSecret = async function ( User.prototype.storePendingTotpSecret = async function (
encryptedSecret, encryptedSecret,
encryptedSecretIv encryptedSecretIv,
) { ) {
return this.update({ return this.update({
twoFactorSetupPendingSecret: encryptedSecret, twoFactorSetupPendingSecret: encryptedSecret,
@@ -478,7 +478,7 @@ User.prototype.storePendingTotpSecret = async function (
// Enable TOTP 2FA after verification // Enable TOTP 2FA after verification
User.prototype.enableTotp = async function (recoveryCodes) { User.prototype.enableTotp = async function (recoveryCodes) {
const hashedCodes = await Promise.all( const hashedCodes = await Promise.all(
recoveryCodes.map((code) => bcrypt.hash(code, 12)) recoveryCodes.map((code) => bcrypt.hash(code, 12)),
); );
// Store in structured format // Store in structured format
@@ -506,7 +506,7 @@ User.prototype.enableTotp = async function (recoveryCodes) {
// Enable Email 2FA // Enable Email 2FA
User.prototype.enableEmailTwoFactor = async function (recoveryCodes) { User.prototype.enableEmailTwoFactor = async function (recoveryCodes) {
const hashedCodes = await Promise.all( const hashedCodes = await Promise.all(
recoveryCodes.map((code) => bcrypt.hash(code, 12)) recoveryCodes.map((code) => bcrypt.hash(code, 12)),
); );
// Store in structured format // Store in structured format
@@ -563,7 +563,7 @@ User.prototype.verifyEmailOtp = function (inputCode) {
return TwoFactorService.verifyEmailOtp( return TwoFactorService.verifyEmailOtp(
inputCode, inputCode,
this.emailOtpCode, this.emailOtpCode,
this.emailOtpExpiry this.emailOtpExpiry,
); );
}; };
@@ -603,7 +603,9 @@ User.prototype.markTotpCodeUsed = async function (code) {
const codeHash = crypto.createHash("sha256").update(code).digest("hex"); const codeHash = crypto.createHash("sha256").update(code).digest("hex");
recentCodes.unshift(codeHash); recentCodes.unshift(codeHash);
// Keep only last 5 codes (covers about 2.5 minutes of 30-second windows) // Keep only last 5 codes (covers about 2.5 minutes of 30-second windows)
await this.update({ recentTotpCodes: JSON.stringify(recentCodes.slice(0, 5)) }); await this.update({
recentTotpCodes: JSON.stringify(recentCodes.slice(0, 5)),
});
}; };
// Verify TOTP code with replay protection // Verify TOTP code with replay protection
@@ -615,18 +617,25 @@ User.prototype.verifyTotpCode = function (code) {
if (this.hasUsedTotpCode(code)) { if (this.hasUsedTotpCode(code)) {
return false; return false;
} }
return TwoFactorService.verifyTotpCode(this.totpSecret, this.totpSecretIv, code); return TwoFactorService.verifyTotpCode(
this.totpSecret,
this.totpSecretIv,
code,
);
}; };
// Verify pending TOTP code (during setup) // Verify pending TOTP code (during setup)
User.prototype.verifyPendingTotpCode = function (code) { User.prototype.verifyPendingTotpCode = function (code) {
if (!this.twoFactorSetupPendingSecret || !this.twoFactorSetupPendingSecretIv) { if (
!this.twoFactorSetupPendingSecret ||
!this.twoFactorSetupPendingSecretIv
) {
return false; return false;
} }
return TwoFactorService.verifyTotpCode( return TwoFactorService.verifyTotpCode(
this.twoFactorSetupPendingSecret, this.twoFactorSetupPendingSecret,
this.twoFactorSetupPendingSecretIv, this.twoFactorSetupPendingSecretIv,
code code,
); );
}; };
@@ -639,7 +648,7 @@ User.prototype.useRecoveryCode = async function (inputCode) {
const recoveryData = JSON.parse(this.recoveryCodesHash); const recoveryData = JSON.parse(this.recoveryCodesHash);
const { valid, index } = await TwoFactorService.verifyRecoveryCode( const { valid, index } = await TwoFactorService.verifyRecoveryCode(
inputCode, inputCode,
recoveryData recoveryData,
); );
if (valid) { if (valid) {
@@ -661,7 +670,8 @@ User.prototype.useRecoveryCode = async function (inputCode) {
return { return {
valid, valid,
remainingCodes: TwoFactorService.getRemainingRecoveryCodesCount(recoveryData), remainingCodes:
TwoFactorService.getRemainingRecoveryCodesCount(recoveryData),
}; };
}; };

View File

@@ -269,11 +269,11 @@ router.post("/", authenticateToken, requireVerifiedEmail, async (req, res) => {
totalAmount = RentalDurationCalculator.calculateRentalCost( totalAmount = RentalDurationCalculator.calculateRentalCost(
rentalStartDateTime, rentalStartDateTime,
rentalEndDateTime, rentalEndDateTime,
item item,
); );
// Check for overlapping rentals using datetime ranges // Check for overlapping rentals using datetime ranges
// Note: "active" rentals are stored as "confirmed" with startDateTime in the past // "active" rentals are stored as "confirmed" with startDateTime in the past
// Two ranges [A,B] and [C,D] overlap if and only if A < D AND C < B // Two ranges [A,B] and [C,D] overlap if and only if A < D AND C < B
// Here: existing rental [existingStart, existingEnd], new rental [rentalStartDateTime, rentalEndDateTime] // Here: existing rental [existingStart, existingEnd], new rental [rentalStartDateTime, rentalEndDateTime]
// Overlap: existingStart < rentalEndDateTime AND rentalStartDateTime < existingEnd // Overlap: existingStart < rentalEndDateTime AND rentalStartDateTime < existingEnd
@@ -352,7 +352,7 @@ router.post("/", authenticateToken, requireVerifiedEmail, async (req, res) => {
await emailServices.rentalFlow.sendRentalRequestEmail( await emailServices.rentalFlow.sendRentalRequestEmail(
rentalWithDetails.owner, rentalWithDetails.owner,
rentalWithDetails.renter, rentalWithDetails.renter,
rentalWithDetails rentalWithDetails,
); );
const reqLogger = logger.withRequestId(req.id); const reqLogger = logger.withRequestId(req.id);
reqLogger.info("Rental request notification sent to owner", { reqLogger.info("Rental request notification sent to owner", {
@@ -374,7 +374,7 @@ router.post("/", authenticateToken, requireVerifiedEmail, async (req, res) => {
try { try {
await emailServices.rentalFlow.sendRentalRequestConfirmationEmail( await emailServices.rentalFlow.sendRentalRequestConfirmationEmail(
rentalWithDetails.renter, rentalWithDetails.renter,
rentalWithDetails rentalWithDetails,
); );
const reqLogger = logger.withRequestId(req.id); const reqLogger = logger.withRequestId(req.id);
reqLogger.info("Rental request confirmation sent to renter", { reqLogger.info("Rental request confirmation sent to renter", {
@@ -474,7 +474,7 @@ router.put("/:id/status", authenticateToken, async (req, res) => {
itemName: rental.item.name, itemName: rental.item.name,
renterId: rental.renterId, renterId: rental.renterId,
ownerId: rental.ownerId, ownerId: rental.ownerId,
} },
); );
// Check if 3DS authentication is required // Check if 3DS authentication is required
@@ -494,7 +494,7 @@ router.put("/:id/status", authenticateToken, async (req, res) => {
itemName: rental.item.name, itemName: rental.item.name,
ownerName: rental.owner.firstName, ownerName: rental.owner.firstName,
amount: rental.totalAmount, amount: rental.totalAmount,
} },
); );
const reqLogger = logger.withRequestId(req.id); const reqLogger = logger.withRequestId(req.id);
reqLogger.info("Authentication required email sent to renter", { reqLogger.info("Authentication required email sent to renter", {
@@ -503,15 +503,12 @@ router.put("/:id/status", authenticateToken, async (req, res) => {
}); });
} catch (emailError) { } catch (emailError) {
const reqLogger = logger.withRequestId(req.id); const reqLogger = logger.withRequestId(req.id);
reqLogger.error( reqLogger.error("Failed to send authentication required email", {
"Failed to send authentication required email", error: emailError.message,
{ stack: emailError.stack,
error: emailError.message, rentalId: rental.id,
stack: emailError.stack, renterId: rental.renterId,
rentalId: rental.id, });
renterId: rental.renterId,
}
);
} }
return res.status(402).json({ return res.status(402).json({
@@ -557,17 +554,14 @@ router.put("/:id/status", authenticateToken, async (req, res) => {
// Create condition check reminder schedules // Create condition check reminder schedules
try { try {
await EventBridgeSchedulerService.createConditionCheckSchedules( await EventBridgeSchedulerService.createConditionCheckSchedules(
updatedRental updatedRental,
); );
} catch (schedulerError) { } catch (schedulerError) {
const reqLogger = logger.withRequestId(req.id); const reqLogger = logger.withRequestId(req.id);
reqLogger.error( reqLogger.error("Failed to create condition check schedules", {
"Failed to create condition check schedules", error: schedulerError.message,
{ rentalId: updatedRental.id,
error: schedulerError.message, });
rentalId: updatedRental.id,
}
);
// Don't fail the confirmation - schedules are non-critical // Don't fail the confirmation - schedules are non-critical
} }
@@ -577,7 +571,7 @@ router.put("/:id/status", authenticateToken, async (req, res) => {
await emailServices.rentalFlow.sendRentalApprovalConfirmationEmail( await emailServices.rentalFlow.sendRentalApprovalConfirmationEmail(
updatedRental.owner, updatedRental.owner,
updatedRental.renter, updatedRental.renter,
updatedRental updatedRental,
); );
const reqLogger = logger.withRequestId(req.id); const reqLogger = logger.withRequestId(req.id);
reqLogger.info("Rental approval confirmation sent to owner", { reqLogger.info("Rental approval confirmation sent to owner", {
@@ -593,7 +587,7 @@ router.put("/:id/status", authenticateToken, async (req, res) => {
stack: emailError.stack, stack: emailError.stack,
rentalId: updatedRental.id, rentalId: updatedRental.id,
ownerId: updatedRental.ownerId, ownerId: updatedRental.ownerId,
} },
); );
} }
@@ -616,7 +610,7 @@ router.put("/:id/status", authenticateToken, async (req, res) => {
renterNotification, renterNotification,
updatedRental, updatedRental,
renter.firstName, renter.firstName,
true // isRenter = true to show payment receipt true, // isRenter = true to show payment receipt
); );
const reqLogger = logger.withRequestId(req.id); const reqLogger = logger.withRequestId(req.id);
reqLogger.info("Rental confirmation sent to renter", { reqLogger.info("Rental confirmation sent to renter", {
@@ -633,7 +627,7 @@ router.put("/:id/status", authenticateToken, async (req, res) => {
stack: emailError.stack, stack: emailError.stack,
rentalId: updatedRental.id, rentalId: updatedRental.id,
renterId: updatedRental.renterId, renterId: updatedRental.renterId,
} },
); );
} }
@@ -670,7 +664,7 @@ router.put("/:id/status", authenticateToken, async (req, res) => {
itemName: rental.item.name, itemName: rental.item.name,
declineReason: renterMessage, declineReason: renterMessage,
rentalId: rental.id, rentalId: rental.id,
} },
); );
reqLogger.info("Payment declined email auto-sent to renter", { reqLogger.info("Payment declined email auto-sent to renter", {
rentalId: rental.id, rentalId: rental.id,
@@ -728,17 +722,14 @@ router.put("/:id/status", authenticateToken, async (req, res) => {
// Create condition check reminder schedules // Create condition check reminder schedules
try { try {
await EventBridgeSchedulerService.createConditionCheckSchedules( await EventBridgeSchedulerService.createConditionCheckSchedules(
updatedRental updatedRental,
); );
} catch (schedulerError) { } catch (schedulerError) {
const reqLogger = logger.withRequestId(req.id); const reqLogger = logger.withRequestId(req.id);
reqLogger.error( reqLogger.error("Failed to create condition check schedules", {
"Failed to create condition check schedules", error: schedulerError.message,
{ rentalId: updatedRental.id,
error: schedulerError.message, });
rentalId: updatedRental.id,
}
);
// Don't fail the confirmation - schedules are non-critical // Don't fail the confirmation - schedules are non-critical
} }
@@ -748,7 +739,7 @@ router.put("/:id/status", authenticateToken, async (req, res) => {
await emailServices.rentalFlow.sendRentalApprovalConfirmationEmail( await emailServices.rentalFlow.sendRentalApprovalConfirmationEmail(
updatedRental.owner, updatedRental.owner,
updatedRental.renter, updatedRental.renter,
updatedRental updatedRental,
); );
const reqLogger = logger.withRequestId(req.id); const reqLogger = logger.withRequestId(req.id);
reqLogger.info("Rental approval confirmation sent to owner", { reqLogger.info("Rental approval confirmation sent to owner", {
@@ -764,7 +755,7 @@ router.put("/:id/status", authenticateToken, async (req, res) => {
stack: emailError.stack, stack: emailError.stack,
rentalId: updatedRental.id, rentalId: updatedRental.id,
ownerId: updatedRental.ownerId, ownerId: updatedRental.ownerId,
} },
); );
} }
@@ -787,7 +778,7 @@ router.put("/:id/status", authenticateToken, async (req, res) => {
renterNotification, renterNotification,
updatedRental, updatedRental,
renter.firstName, renter.firstName,
true // isRenter = true (for free rentals, shows "no payment required") true, // isRenter = true (for free rentals, shows "no payment required")
); );
const reqLogger = logger.withRequestId(req.id); const reqLogger = logger.withRequestId(req.id);
reqLogger.info("Rental confirmation sent to renter", { reqLogger.info("Rental confirmation sent to renter", {
@@ -804,7 +795,7 @@ router.put("/:id/status", authenticateToken, async (req, res) => {
stack: emailError.stack, stack: emailError.stack,
rentalId: updatedRental.id, rentalId: updatedRental.id,
renterId: updatedRental.renterId, renterId: updatedRental.renterId,
} },
); );
} }
@@ -910,7 +901,7 @@ router.put("/:id/decline", authenticateToken, async (req, res) => {
await emailServices.rentalFlow.sendRentalDeclinedEmail( await emailServices.rentalFlow.sendRentalDeclinedEmail(
updatedRental.renter, updatedRental.renter,
updatedRental, updatedRental,
reason reason,
); );
const reqLogger = logger.withRequestId(req.id); const reqLogger = logger.withRequestId(req.id);
reqLogger.info("Rental decline notification sent to renter", { reqLogger.info("Rental decline notification sent to renter", {
@@ -1130,7 +1121,7 @@ router.post("/cost-preview", authenticateToken, async (req, res) => {
const totalAmount = RentalDurationCalculator.calculateRentalCost( const totalAmount = RentalDurationCalculator.calculateRentalCost(
rentalStartDateTime, rentalStartDateTime,
rentalEndDateTime, rentalEndDateTime,
item item,
); );
// Calculate fees // Calculate fees
@@ -1202,7 +1193,7 @@ router.get("/:id/refund-preview", authenticateToken, async (req, res, next) => {
try { try {
const preview = await RefundService.getRefundPreview( const preview = await RefundService.getRefundPreview(
req.params.id, req.params.id,
req.user.id req.user.id,
); );
res.json(preview); res.json(preview);
} catch (error) { } catch (error) {
@@ -1246,7 +1237,7 @@ router.get(
const lateCalculation = LateReturnService.calculateLateFee( const lateCalculation = LateReturnService.calculateLateFee(
rental, rental,
actualReturnDateTime actualReturnDateTime,
); );
res.json(lateCalculation); res.json(lateCalculation);
@@ -1260,7 +1251,7 @@ router.get(
}); });
next(error); next(error);
} }
} },
); );
// Cancel rental with refund processing // Cancel rental with refund processing
@@ -1276,7 +1267,7 @@ router.post("/:id/cancel", authenticateToken, async (req, res, next) => {
const result = await RefundService.processCancellation( const result = await RefundService.processCancellation(
req.params.id, req.params.id,
req.user.id, req.user.id,
reason.trim() reason.trim(),
); );
// Return the updated rental with refund information // Return the updated rental with refund information
@@ -1302,7 +1293,7 @@ router.post("/:id/cancel", authenticateToken, async (req, res, next) => {
updatedRental.owner, updatedRental.owner,
updatedRental.renter, updatedRental.renter,
updatedRental, updatedRental,
result.refund result.refund,
); );
const reqLogger = logger.withRequestId(req.id); const reqLogger = logger.withRequestId(req.id);
reqLogger.info("Cancellation emails sent", { reqLogger.info("Cancellation emails sent", {
@@ -1403,7 +1394,7 @@ router.post("/:id/mark-return", authenticateToken, async (req, res, next) => {
await emailServices.rentalFlow.sendRentalCompletionEmails( await emailServices.rentalFlow.sendRentalCompletionEmails(
rentalWithDetails.owner, rentalWithDetails.owner,
rentalWithDetails.renter, rentalWithDetails.renter,
rentalWithDetails rentalWithDetails,
); );
const reqLogger = logger.withRequestId(req.id); const reqLogger = logger.withRequestId(req.id);
reqLogger.info("Rental completion emails sent", { reqLogger.info("Rental completion emails sent", {
@@ -1441,7 +1432,7 @@ router.post("/:id/mark-return", authenticateToken, async (req, res, next) => {
if (statusOptions?.returned_late && actualReturnDateTime) { if (statusOptions?.returned_late && actualReturnDateTime) {
const lateReturnDamaged = await LateReturnService.processLateReturn( const lateReturnDamaged = await LateReturnService.processLateReturn(
rentalId, rentalId,
actualReturnDateTime actualReturnDateTime,
); );
damageUpdates.status = "returned_late_and_damaged"; damageUpdates.status = "returned_late_and_damaged";
damageUpdates.lateFees = lateReturnDamaged.lateCalculation.lateFee; damageUpdates.lateFees = lateReturnDamaged.lateCalculation.lateFee;
@@ -1463,7 +1454,7 @@ router.post("/:id/mark-return", authenticateToken, async (req, res, next) => {
const lateReturn = await LateReturnService.processLateReturn( const lateReturn = await LateReturnService.processLateReturn(
rentalId, rentalId,
actualReturnDateTime actualReturnDateTime,
); );
updatedRental = lateReturn.rental; updatedRental = lateReturn.rental;
@@ -1484,7 +1475,7 @@ router.post("/:id/mark-return", authenticateToken, async (req, res, next) => {
await emailServices.customerService.sendLostItemToCustomerService( await emailServices.customerService.sendLostItemToCustomerService(
updatedRental, updatedRental,
owner, owner,
renter renter,
); );
break; break;
@@ -1562,7 +1553,7 @@ router.post("/:id/report-damage", authenticateToken, async (req, res, next) => {
"damage-reports", "damage-reports",
{ {
maxKeys: IMAGE_LIMITS.damageReports, maxKeys: IMAGE_LIMITS.damageReports,
} },
); );
if (!keyValidation.valid) { if (!keyValidation.valid) {
return res.status(400).json({ return res.status(400).json({
@@ -1576,7 +1567,7 @@ router.post("/:id/report-damage", authenticateToken, async (req, res, next) => {
const result = await DamageAssessmentService.processDamageAssessment( const result = await DamageAssessmentService.processDamageAssessment(
rentalId, rentalId,
damageInfo, damageInfo,
userId userId,
); );
const reqLogger = logger.withRequestId(req.id); const reqLogger = logger.withRequestId(req.id);
@@ -1654,7 +1645,7 @@ router.put("/:id/payment-method", authenticateToken, async (req, res, next) => {
let paymentMethod; let paymentMethod;
try { try {
paymentMethod = await StripeService.getPaymentMethod( paymentMethod = await StripeService.getPaymentMethod(
stripePaymentMethodId stripePaymentMethodId,
); );
} catch { } catch {
return res.status(400).json({ error: "Invalid payment method" }); return res.status(400).json({ error: "Invalid payment method" });
@@ -1699,7 +1690,7 @@ router.put("/:id/payment-method", authenticateToken, async (req, res, next) => {
status: "pending", status: "pending",
paymentStatus: "pending", paymentStatus: "pending",
}, },
} },
); );
if (updateCount === 0) { if (updateCount === 0) {
@@ -1725,7 +1716,7 @@ router.put("/:id/payment-method", authenticateToken, async (req, res, next) => {
itemName: rental.item.name, itemName: rental.item.name,
rentalId: rental.id, rentalId: rental.id,
approvalUrl: `${process.env.FRONTEND_URL}/rentals/${rentalId}`, approvalUrl: `${process.env.FRONTEND_URL}/rentals/${rentalId}`,
} },
); );
} catch (emailError) { } catch (emailError) {
// Don't fail the request if email fails // Don't fail the request if email fails
@@ -1781,7 +1772,7 @@ router.get(
const stripe = require("stripe")(process.env.STRIPE_SECRET_KEY); const stripe = require("stripe")(process.env.STRIPE_SECRET_KEY);
const paymentIntent = await stripe.paymentIntents.retrieve( const paymentIntent = await stripe.paymentIntents.retrieve(
rental.stripePaymentIntentId rental.stripePaymentIntentId,
); );
return res.json({ return res.json({
@@ -1798,7 +1789,7 @@ router.get(
}); });
next(error); next(error);
} }
} },
); );
/** /**
@@ -1812,8 +1803,29 @@ router.post(
try { try {
const rental = await Rental.findByPk(req.params.id, { const rental = await Rental.findByPk(req.params.id, {
include: [ include: [
{ model: User, as: "renter", attributes: ["id", "firstName", "lastName", "email", "stripeCustomerId"] }, {
{ model: User, as: "owner", attributes: ["id", "firstName", "lastName", "email", "stripeConnectedAccountId", "stripePayoutsEnabled"] }, model: User,
as: "renter",
attributes: [
"id",
"firstName",
"lastName",
"email",
"stripeCustomerId",
],
},
{
model: User,
as: "owner",
attributes: [
"id",
"firstName",
"lastName",
"email",
"stripeConnectedAccountId",
"stripePayoutsEnabled",
],
},
{ model: Item, as: "item" }, { model: Item, as: "item" },
], ],
}); });
@@ -1837,7 +1849,7 @@ router.post(
const stripe = require("stripe")(process.env.STRIPE_SECRET_KEY); const stripe = require("stripe")(process.env.STRIPE_SECRET_KEY);
const paymentIntent = await stripe.paymentIntents.retrieve( const paymentIntent = await stripe.paymentIntents.retrieve(
rental.stripePaymentIntentId, rental.stripePaymentIntentId,
{ expand: ['latest_charge.payment_method_details'] } { expand: ["latest_charge.payment_method_details"] },
); );
if (paymentIntent.status !== "succeeded") { if (paymentIntent.status !== "succeeded") {
@@ -1864,7 +1876,8 @@ router.post(
paymentMethodLast4 = paymentMethodDetails.card?.last4 || null; paymentMethodLast4 = paymentMethodDetails.card?.last4 || null;
} else if (type === "us_bank_account") { } else if (type === "us_bank_account") {
paymentMethodBrand = "bank_account"; paymentMethodBrand = "bank_account";
paymentMethodLast4 = paymentMethodDetails.us_bank_account?.last4 || null; paymentMethodLast4 =
paymentMethodDetails.us_bank_account?.last4 || null;
} }
} }
@@ -1882,13 +1895,10 @@ router.post(
await EventBridgeSchedulerService.createConditionCheckSchedules(rental); await EventBridgeSchedulerService.createConditionCheckSchedules(rental);
} catch (schedulerError) { } catch (schedulerError) {
const reqLogger = logger.withRequestId(req.id); const reqLogger = logger.withRequestId(req.id);
reqLogger.error( reqLogger.error("Failed to create condition check schedules", {
"Failed to create condition check schedules", error: schedulerError.message,
{ rentalId: rental.id,
error: schedulerError.message, });
rentalId: rental.id,
}
);
// Don't fail the confirmation - schedules are non-critical // Don't fail the confirmation - schedules are non-critical
} }
@@ -1897,13 +1907,16 @@ router.post(
await emailServices.rentalFlow.sendRentalApprovalConfirmationEmail( await emailServices.rentalFlow.sendRentalApprovalConfirmationEmail(
rental.owner, rental.owner,
rental.renter, rental.renter,
rental rental,
); );
const reqLogger = logger.withRequestId(req.id); const reqLogger = logger.withRequestId(req.id);
reqLogger.info("Rental approval confirmation sent to owner (after 3DS)", { reqLogger.info(
rentalId: rental.id, "Rental approval confirmation sent to owner (after 3DS)",
ownerId: rental.ownerId, {
}); rentalId: rental.id,
ownerId: rental.ownerId,
},
);
} catch (emailError) { } catch (emailError) {
const reqLogger = logger.withRequestId(req.id); const reqLogger = logger.withRequestId(req.id);
reqLogger.error( reqLogger.error(
@@ -1911,7 +1924,7 @@ router.post(
{ {
error: emailError.message, error: emailError.message,
rentalId: rental.id, rentalId: rental.id,
} },
); );
} }
@@ -1929,7 +1942,7 @@ router.post(
renterNotification, renterNotification,
rental, rental,
rental.renter.firstName, rental.renter.firstName,
true true,
); );
const reqLogger = logger.withRequestId(req.id); const reqLogger = logger.withRequestId(req.id);
reqLogger.info("Rental confirmation sent to renter (after 3DS)", { reqLogger.info("Rental confirmation sent to renter (after 3DS)", {
@@ -1938,17 +1951,17 @@ router.post(
}); });
} catch (emailError) { } catch (emailError) {
const reqLogger = logger.withRequestId(req.id); const reqLogger = logger.withRequestId(req.id);
reqLogger.error( reqLogger.error("Failed to send rental confirmation email after 3DS", {
"Failed to send rental confirmation email after 3DS", error: emailError.message,
{ rentalId: rental.id,
error: emailError.message, });
rentalId: rental.id,
}
);
} }
// Trigger payout if owner has payouts enabled // Trigger payout if owner has payouts enabled
if (rental.owner.stripePayoutsEnabled && rental.owner.stripeConnectedAccountId) { if (
rental.owner.stripePayoutsEnabled &&
rental.owner.stripeConnectedAccountId
) {
try { try {
await PayoutService.processRentalPayout(rental); await PayoutService.processRentalPayout(rental);
const reqLogger = logger.withRequestId(req.id); const reqLogger = logger.withRequestId(req.id);
@@ -1983,7 +1996,7 @@ router.post(
}); });
next(error); next(error);
} }
} },
); );
module.exports = router; module.exports = router;

View File

@@ -26,7 +26,7 @@ class LocationService {
// distance = 3959 * acos(cos(radians(lat1)) * cos(radians(lat2)) // distance = 3959 * acos(cos(radians(lat1)) * cos(radians(lat2))
// * cos(radians(lng2) - radians(lng1)) // * cos(radians(lng2) - radians(lng1))
// + sin(radians(lat1)) * sin(radians(lat2))) // + sin(radians(lat1)) * sin(radians(lat2)))
// Note: 3959 is Earth's radius in miles // 3959 is Earth's radius in miles
const query = ` const query = `
SELECT * FROM ( SELECT * FROM (
SELECT SELECT

View File

@@ -1,283 +1,322 @@
<!DOCTYPE html> <!doctype html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Your Alpha Access Code - Village Share</title> <title>Your Alpha Access Code - Village Share</title>
<style> <style>
/* Reset styles */ /* Reset styles */
body, table, td, p, a, li, blockquote { body,
-webkit-text-size-adjust: 100%; table,
-ms-text-size-adjust: 100%; td,
} p,
table, td { a,
mso-table-lspace: 0pt; li,
mso-table-rspace: 0pt; blockquote {
} -webkit-text-size-adjust: 100%;
img { -ms-text-size-adjust: 100%;
-ms-interpolation-mode: bicubic; }
} table,
td {
mso-table-lspace: 0pt;
mso-table-rspace: 0pt;
}
img {
-ms-interpolation-mode: bicubic;
}
/* Base styles */ /* Base styles */
body { body {
margin: 0; margin: 0;
padding: 0; padding: 0;
width: 100% !important; width: 100% !important;
min-width: 100%; min-width: 100%;
height: 100%; height: 100%;
background-color: #f8f9fa; background-color: #f8f9fa;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif; font-family:
line-height: 1.6; -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu,
color: #212529; Cantarell, sans-serif;
} line-height: 1.6;
color: #212529;
}
/* Container */ /* Container */
.email-container {
max-width: 600px;
margin: 0 auto;
background-color: #ffffff;
border-radius: 8px;
overflow: hidden;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
/* Header */
.header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
padding: 40px 30px;
text-align: center;
}
.logo {
font-size: 32px;
font-weight: 700;
color: #ffffff;
text-decoration: none;
letter-spacing: -1px;
}
.tagline {
color: #e0e7ff;
font-size: 14px;
margin-top: 8px;
}
/* Content */
.content {
padding: 40px 30px;
}
.content h1 {
font-size: 24px;
font-weight: 600;
margin: 0 0 20px 0;
color: #212529;
}
.content p {
margin: 0 0 16px 0;
color: #6c757d;
line-height: 1.6;
}
.content strong {
color: #495057;
}
/* Code box */
.code-box {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border-radius: 8px;
padding: 30px;
margin: 30px 0;
text-align: center;
}
.code-label {
color: #e0e7ff;
font-size: 14px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 1px;
margin-bottom: 12px;
}
.code {
font-family: "Courier New", Courier, monospace;
font-size: 32px;
font-weight: 700;
color: #ffffff;
letter-spacing: 4px;
margin: 10px 0;
user-select: all;
}
/* Button */
.button {
display: inline-block;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: #ffffff !important;
text-decoration: none;
padding: 16px 32px;
border-radius: 6px;
font-weight: 600;
margin: 20px 0;
text-align: center;
transition: all 0.3s ease;
}
.button:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}
/* Info box */
.info-box {
background-color: #e7f3ff;
border-left: 4px solid #667eea;
padding: 20px;
margin: 20px 0;
border-radius: 0 6px 6px 0;
}
.info-box p {
margin: 0 0 10px 0;
color: #004085;
font-size: 14px;
}
.info-box p:last-child {
margin-bottom: 0;
}
.info-box ul {
margin: 10px 0 0 0;
padding-left: 20px;
color: #004085;
font-size: 14px;
}
.info-box li {
margin-bottom: 6px;
}
/* Footer */
.footer {
background-color: #f8f9fa;
padding: 30px;
text-align: center;
border-top: 1px solid #e9ecef;
}
.footer p {
margin: 0 0 10px 0;
font-size: 14px;
color: #6c757d;
}
.footer a {
color: #667eea;
text-decoration: none;
}
.footer a:hover {
text-decoration: underline;
}
/* Responsive */
@media only screen and (max-width: 600px) {
.email-container { .email-container {
max-width: 600px; margin: 0;
margin: 0 auto; border-radius: 0;
background-color: #ffffff;
border-radius: 8px;
overflow: hidden;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
} }
/* Header */ .header,
.header { .content,
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); .footer {
padding: 40px 30px; padding: 20px;
text-align: center;
} }
.logo { .logo {
font-size: 32px; font-size: 28px;
font-weight: 700;
color: #ffffff;
text-decoration: none;
letter-spacing: -1px;
}
.tagline {
color: #e0e7ff;
font-size: 14px;
margin-top: 8px;
}
/* Content */
.content {
padding: 40px 30px;
} }
.content h1 { .content h1 {
font-size: 24px; font-size: 22px;
font-weight: 600;
margin: 0 0 20px 0;
color: #212529;
}
.content p {
margin: 0 0 16px 0;
color: #6c757d;
line-height: 1.6;
}
.content strong {
color: #495057;
}
/* Code box */
.code-box {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border-radius: 8px;
padding: 30px;
margin: 30px 0;
text-align: center;
}
.code-label {
color: #e0e7ff;
font-size: 14px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 1px;
margin-bottom: 12px;
} }
.code { .code {
font-family: 'Courier New', Courier, monospace; font-size: 24px;
font-size: 32px; letter-spacing: 2px;
font-weight: 700;
color: #ffffff;
letter-spacing: 4px;
margin: 10px 0;
user-select: all;
} }
/* Button */
.button { .button {
display: inline-block; display: block;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); width: 100%;
color: #ffffff !important; box-sizing: border-box;
text-decoration: none;
padding: 16px 32px;
border-radius: 6px;
font-weight: 600;
margin: 20px 0;
text-align: center;
transition: all 0.3s ease;
}
.button:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}
/* Info box */
.info-box {
background-color: #e7f3ff;
border-left: 4px solid #667eea;
padding: 20px;
margin: 20px 0;
border-radius: 0 6px 6px 0;
}
.info-box p {
margin: 0 0 10px 0;
color: #004085;
font-size: 14px;
}
.info-box p:last-child {
margin-bottom: 0;
}
.info-box ul {
margin: 10px 0 0 0;
padding-left: 20px;
color: #004085;
font-size: 14px;
}
.info-box li {
margin-bottom: 6px;
}
/* Footer */
.footer {
background-color: #f8f9fa;
padding: 30px;
text-align: center;
border-top: 1px solid #e9ecef;
}
.footer p {
margin: 0 0 10px 0;
font-size: 14px;
color: #6c757d;
}
.footer a {
color: #667eea;
text-decoration: none;
}
.footer a:hover {
text-decoration: underline;
}
/* Responsive */
@media only screen and (max-width: 600px) {
.email-container {
margin: 0;
border-radius: 0;
}
.header, .content, .footer {
padding: 20px;
}
.logo {
font-size: 28px;
}
.content h1 {
font-size: 22px;
}
.code {
font-size: 24px;
letter-spacing: 2px;
}
.button {
display: block;
width: 100%;
box-sizing: border-box;
}
} }
}
</style> </style>
</head> </head>
<body> <body>
<div class="email-container"> <div class="email-container">
<div class="header"> <div class="header">
<div class="logo">Village Share</div> <div class="logo">Village Share</div>
<div class="tagline">Alpha Access Invitation</div> <div class="tagline">Alpha Access Invitation</div>
</div>
<div class="content">
<h1>Welcome to Alpha Testing!</h1>
<p>
Congratulations! You've been selected to participate in the exclusive
alpha testing program for Village Share, the community-powered rental
marketplace.
</p>
<p>
Your unique alpha access code is:
<strong style="font-family: monospace">{{code}}</strong>
</p>
<p>To get started:</p>
<div class="info-box">
<p><strong>Steps to Access:</strong></p>
<ul>
<li>
Visit
<a href="{{frontendUrl}}" style="color: #667eea; font-weight: 600"
>{{frontendUrl}}</a
>
</li>
<li>Enter your alpha access code when prompted</li>
<li>
Register with <strong>this email address</strong> ({{email}})
</li>
<li>Start exploring the platform!</li>
</ul>
</div> </div>
<div class="content"> <div style="text-align: center">
<h1>Welcome to Alpha Testing!</h1> <a href="{{frontendUrl}}" class="button"
>Access Village Share Alpha</a
<p>Congratulations! You've been selected to participate in the exclusive alpha testing program for Village Share, the community-powered rental marketplace.</p> >
<p>Your unique alpha access code is: <strong style="font-family: monospace;">{{code}}</strong></p>
<p>To get started:</p>
<div class="info-box">
<p><strong>Steps to Access:</strong></p>
<ul>
<li>Visit <a href="{{frontendUrl}}" style="color: #667eea; font-weight: 600;">{{frontendUrl}}</a></li>
<li>Enter your alpha access code when prompted</li>
<li>Register with <strong>this email address</strong> ({{email}})</li>
<li>Start exploring the platform!</li>
</ul>
</div>
<div style="text-align: center;">
<a href="{{frontendUrl}}" class="button">Access Village Share Alpha</a>
</div>
<p><strong>What to expect as an alpha tester:</strong></p>
<div class="info-box">
<ul>
<li>Early access to new features before public launch</li>
<li>Opportunity to shape the product with your feedback</li>
<li>Direct communication with the development team</li>
<li>Special recognition as an early supporter</li>
</ul>
</div>
<p><strong>Important notes:</strong></p>
<ul style="color: #6c757d; font-size: 14px;">
<li>Your code is tied to this email address only</li>
<li>This is a permanent access code (no expiration)</li>
<li>Please keep your code confidential</li>
<li>We value your feedback - let us know what you think!</li>
</ul>
<p>We're excited to have you as part of our alpha testing community. Your feedback will be invaluable in making Village Share the best it can be.</p>
<p>If you have any questions or encounter any issues, please don't hesitate to reach out to us.</p>
<p>Happy renting!</p>
</div> </div>
<div class="footer"> <p><strong>What to expect as an alpha tester:</strong></p>
<p><strong>Village Share Alpha Testing Program</strong></p>
<p>Need help? Contact us at <a href="mailto:support@villageshare.app">support@villageshare.app</a></p> <div class="info-box">
<p>&copy; 2025 Village Share. All rights reserved.</p> <ul>
<li>Early access to new features before public launch</li>
<li>Opportunity to shape the product with your feedback</li>
<li>Direct communication with the development team</li>
<li>Special recognition as an early supporter</li>
</ul>
</div> </div>
<p><strong>Important notes:</strong></p>
<ul style="color: #6c757d; font-size: 14px">
<li>Your code is tied to this email address only</li>
<li>This is a permanent access code (no expiration)</li>
<li>Please keep your code confidential</li>
<li>We value your feedback - let us know what you think!</li>
</ul>
<p>
We're excited to have you as part of our alpha testing community. Your
feedback will be invaluable in making Village Share the best it can
be.
</p>
<p>
If you have any questions or encounter any issues, please don't
hesitate to reach out to us.
</p>
<p>Happy renting!</p>
</div>
<div class="footer">
<p><strong>Village Share Alpha Testing Program</strong></p>
<p>
Need help? Contact us at
<a href="mailto:community-support@village-share.com"
>community-support@village-share.com</a
>
</p>
<p>&copy; 2025 Village Share. All rights reserved.</p>
</div>
</div> </div>
</body> </body>
</html> </html>

View File

@@ -1,4 +1,4 @@
<!DOCTYPE html> <!doctype html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="utf-8" /> <meta charset="utf-8" />
@@ -34,8 +34,9 @@
min-width: 100%; min-width: 100%;
height: 100%; height: 100%;
background-color: #f8f9fa; background-color: #f8f9fa;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, font-family:
Oxygen, Ubuntu, Cantarell, sans-serif; -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu,
Cantarell, sans-serif;
line-height: 1.6; line-height: 1.6;
color: #212529; color: #212529;
} }
@@ -260,7 +261,8 @@
</p> </p>
<p> <p>
If you have any questions, please If you have any questions, please
<a href="mailto:support@villageshare.app">contact our support team</a <a href="mailto:community-support@village-share.com"
>contact our support team</a
>. >.
</p> </p>
</div> </div>

View File

@@ -1,4 +1,4 @@
<!DOCTYPE html> <!doctype html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="utf-8" /> <meta charset="utf-8" />
@@ -34,8 +34,9 @@
min-width: 100%; min-width: 100%;
height: 100%; height: 100%;
background-color: #f8f9fa; background-color: #f8f9fa;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, font-family:
Oxygen, Ubuntu, Cantarell, sans-serif; -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu,
Cantarell, sans-serif;
line-height: 1.6; line-height: 1.6;
color: #212529; color: #212529;
} }
@@ -246,8 +247,8 @@
<p> <p>
<strong>Didn't change your password?</strong> If you did not make <strong>Didn't change your password?</strong> If you did not make
this change, your account may be compromised. Please contact our this change, your account may be compromised. Please contact our
support team immediately at support@villageshare.app to secure your support team immediately at community-support@village-share.com to
account. secure your account.
</p> </p>
</div> </div>

View File

@@ -1,246 +1,279 @@
<!DOCTYPE html> <!doctype html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Personal Information Updated - Village Share</title> <title>Personal Information Updated - Village Share</title>
<style> <style>
/* Reset styles */ /* Reset styles */
body, table, td, p, a, li, blockquote { body,
-webkit-text-size-adjust: 100%; table,
-ms-text-size-adjust: 100%; td,
} p,
table, td { a,
mso-table-lspace: 0pt; li,
mso-table-rspace: 0pt; blockquote {
} -webkit-text-size-adjust: 100%;
img { -ms-text-size-adjust: 100%;
-ms-interpolation-mode: bicubic; }
} table,
td {
mso-table-lspace: 0pt;
mso-table-rspace: 0pt;
}
img {
-ms-interpolation-mode: bicubic;
}
/* Base styles */ /* Base styles */
body { body {
margin: 0; margin: 0;
padding: 0; padding: 0;
width: 100% !important; width: 100% !important;
min-width: 100%; min-width: 100%;
height: 100%; height: 100%;
background-color: #f8f9fa; background-color: #f8f9fa;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif; font-family:
line-height: 1.6; -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu,
color: #212529; Cantarell, sans-serif;
} line-height: 1.6;
color: #212529;
}
/* Container */ /* Container */
.email-container {
max-width: 600px;
margin: 0 auto;
background-color: #ffffff;
border-radius: 8px;
overflow: hidden;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
/* Header */
.header {
background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
padding: 40px 30px;
text-align: center;
}
.logo {
font-size: 32px;
font-weight: 700;
color: #ffffff;
text-decoration: none;
letter-spacing: -1px;
}
.tagline {
color: #d4edda;
font-size: 14px;
margin-top: 8px;
}
/* Content */
.content {
padding: 40px 30px;
}
.content h1 {
font-size: 24px;
font-weight: 600;
margin: 0 0 20px 0;
color: #212529;
}
.content p {
margin: 0 0 16px 0;
color: #6c757d;
line-height: 1.6;
}
.content strong {
color: #495057;
}
/* Success box */
.success-box {
background-color: #d4edda;
border-left: 4px solid #28a745;
padding: 20px;
margin: 20px 0;
border-radius: 0 6px 6px 0;
}
.success-box p {
margin: 0;
color: #155724;
font-size: 14px;
}
/* Info box */
.info-box {
background-color: #e7f3ff;
border-left: 4px solid #0066cc;
padding: 20px;
margin: 20px 0;
border-radius: 0 6px 6px 0;
}
.info-box p {
margin: 0;
color: #004085;
font-size: 14px;
}
/* Security box */
.security-box {
background-color: #f8d7da;
border-left: 4px solid #dc3545;
padding: 15px;
margin: 20px 0;
border-radius: 0 6px 6px 0;
}
.security-box p {
margin: 0;
color: #721c24;
font-size: 14px;
}
/* Details table */
.details-table {
width: 100%;
border-collapse: collapse;
margin: 20px 0;
}
.details-table td {
padding: 12px;
border-bottom: 1px solid #e9ecef;
}
.details-table td:first-child {
font-weight: 600;
color: #495057;
width: 40%;
}
.details-table td:last-child {
color: #6c757d;
}
/* Footer */
.footer {
background-color: #f8f9fa;
padding: 30px;
text-align: center;
border-top: 1px solid #e9ecef;
}
.footer p {
margin: 0 0 10px 0;
font-size: 14px;
color: #6c757d;
}
.footer a {
color: #667eea;
text-decoration: none;
}
.footer a:hover {
text-decoration: underline;
}
/* Responsive */
@media only screen and (max-width: 600px) {
.email-container { .email-container {
max-width: 600px; margin: 0;
margin: 0 auto; border-radius: 0;
background-color: #ffffff;
border-radius: 8px;
overflow: hidden;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
} }
/* Header */ .header,
.header { .content,
background: linear-gradient(135deg, #28a745 0%, #20c997 100%); .footer {
padding: 40px 30px; padding: 20px;
text-align: center;
} }
.logo { .logo {
font-size: 32px; font-size: 28px;
font-weight: 700;
color: #ffffff;
text-decoration: none;
letter-spacing: -1px;
}
.tagline {
color: #d4edda;
font-size: 14px;
margin-top: 8px;
}
/* Content */
.content {
padding: 40px 30px;
} }
.content h1 { .content h1 {
font-size: 24px; font-size: 22px;
font-weight: 600;
margin: 0 0 20px 0;
color: #212529;
}
.content p {
margin: 0 0 16px 0;
color: #6c757d;
line-height: 1.6;
}
.content strong {
color: #495057;
}
/* Success box */
.success-box {
background-color: #d4edda;
border-left: 4px solid #28a745;
padding: 20px;
margin: 20px 0;
border-radius: 0 6px 6px 0;
}
.success-box p {
margin: 0;
color: #155724;
font-size: 14px;
}
/* Info box */
.info-box {
background-color: #e7f3ff;
border-left: 4px solid #0066cc;
padding: 20px;
margin: 20px 0;
border-radius: 0 6px 6px 0;
}
.info-box p {
margin: 0;
color: #004085;
font-size: 14px;
}
/* Security box */
.security-box {
background-color: #f8d7da;
border-left: 4px solid #dc3545;
padding: 15px;
margin: 20px 0;
border-radius: 0 6px 6px 0;
}
.security-box p {
margin: 0;
color: #721c24;
font-size: 14px;
}
/* Details table */
.details-table {
width: 100%;
border-collapse: collapse;
margin: 20px 0;
}
.details-table td {
padding: 12px;
border-bottom: 1px solid #e9ecef;
}
.details-table td:first-child {
font-weight: 600;
color: #495057;
width: 40%;
}
.details-table td:last-child {
color: #6c757d;
}
/* Footer */
.footer {
background-color: #f8f9fa;
padding: 30px;
text-align: center;
border-top: 1px solid #e9ecef;
}
.footer p {
margin: 0 0 10px 0;
font-size: 14px;
color: #6c757d;
}
.footer a {
color: #667eea;
text-decoration: none;
}
.footer a:hover {
text-decoration: underline;
}
/* Responsive */
@media only screen and (max-width: 600px) {
.email-container {
margin: 0;
border-radius: 0;
}
.header, .content, .footer {
padding: 20px;
}
.logo {
font-size: 28px;
}
.content h1 {
font-size: 22px;
}
} }
}
</style> </style>
</head> </head>
<body> <body>
<div class="email-container"> <div class="email-container">
<div class="header"> <div class="header">
<div class="logo">Village Share</div> <div class="logo">Village Share</div>
<div class="tagline">Personal Information Updated</div> <div class="tagline">Personal Information Updated</div>
</div>
<div class="content">
<p>Hi {{recipientName}},</p>
<h1>Your Personal Information Has Been Updated</h1>
<div class="info-box">
<p>
<strong>Your account information was recently updated.</strong> This
email is to notify you that changes were made to your personal
information on your Village Share account.
</p>
</div> </div>
<div class="content"> <p>
<p>Hi {{recipientName}},</p> We're sending you this notification as part of our commitment to
keeping your account secure. If you made these changes, no further
action is required.
</p>
<h1>Your Personal Information Has Been Updated</h1> <table class="details-table">
<tr>
<td>Date & Time:</td>
<td>{{timestamp}}</td>
</tr>
<tr>
<td>Account Email:</td>
<td>{{email}}</td>
</tr>
</table>
<div class="info-box"> <div class="security-box">
<p><strong>Your account information was recently updated.</strong> This email is to notify you that changes were made to your personal information on your Village Share account.</p> <p>
</div> <strong>Didn't make these changes?</strong> If you did not update
your personal information, your account may be compromised. Please
<p>We're sending you this notification as part of our commitment to keeping your account secure. If you made these changes, no further action is required.</p> contact our support team immediately at
community-support@village-share.com and consider changing your
<table class="details-table"> password.
<tr> </p>
<td>Date & Time:</td>
<td>{{timestamp}}</td>
</tr>
<tr>
<td>Account Email:</td>
<td>{{email}}</td>
</tr>
</table>
<div class="security-box">
<p><strong>Didn't make these changes?</strong> If you did not update your personal information, your account may be compromised. Please contact our support team immediately at support@villageshare.app and consider changing your password.</p>
</div>
<div class="info-box">
<p><strong>Security tip:</strong> Regularly review your account information to ensure it's accurate and up to date. If you notice any suspicious activity, contact our support team right away.</p>
</div>
<p>Thanks for using Village Share!</p>
</div> </div>
<div class="footer"> <div class="info-box">
<p><strong>Village Share</strong></p> <p>
<p>This is a security notification sent to confirm changes to your account. If you have any concerns about your account security, please contact our support team immediately.</p> <strong>Security tip:</strong> Regularly review your account
<p>&copy; 2025 Village Share. All rights reserved.</p> information to ensure it's accurate and up to date. If you notice
any suspicious activity, contact our support team right away.
</p>
</div> </div>
<p>Thanks for using Village Share!</p>
</div>
<div class="footer">
<p><strong>Village Share</strong></p>
<p>
This is a security notification sent to confirm changes to your
account. If you have any concerns about your account security, please
contact our support team immediately.
</p>
<p>&copy; 2025 Village Share. All rights reserved.</p>
</div>
</div> </div>
</body> </body>
</html> </html>

View File

@@ -6,12 +6,12 @@
* cancellation flows. * cancellation flows.
*/ */
const request = require('supertest'); const request = require("supertest");
const express = require('express'); const express = require("express");
const cookieParser = require('cookie-parser'); const cookieParser = require("cookie-parser");
const jwt = require('jsonwebtoken'); const jwt = require("jsonwebtoken");
const { sequelize, User, Item, Rental } = require('../../models'); const { sequelize, User, Item, Rental } = require("../../models");
const rentalRoutes = require('../../routes/rentals'); const rentalRoutes = require("../../routes/rentals");
// Test app setup // Test app setup
const createTestApp = () => { const createTestApp = () => {
@@ -21,11 +21,11 @@ const createTestApp = () => {
// Add request ID middleware // Add request ID middleware
app.use((req, res, next) => { app.use((req, res, next) => {
req.id = 'test-request-id'; req.id = "test-request-id";
next(); next();
}); });
app.use('/rentals', rentalRoutes); app.use("/rentals", rentalRoutes);
return app; return app;
}; };
@@ -34,7 +34,7 @@ const generateAuthToken = (user) => {
return jwt.sign( return jwt.sign(
{ id: user.id, jwtVersion: user.jwtVersion || 0 }, { id: user.id, jwtVersion: user.jwtVersion || 0 },
process.env.JWT_ACCESS_SECRET, process.env.JWT_ACCESS_SECRET,
{ expiresIn: '15m' } { expiresIn: "15m" },
); );
}; };
@@ -42,11 +42,11 @@ const generateAuthToken = (user) => {
const createTestUser = async (overrides = {}) => { const createTestUser = async (overrides = {}) => {
const defaultData = { const defaultData = {
email: `user-${Date.now()}-${Math.random().toString(36).slice(2)}@example.com`, email: `user-${Date.now()}-${Math.random().toString(36).slice(2)}@example.com`,
password: 'TestPassword123!', password: "TestPassword123!",
firstName: 'Test', firstName: "Test",
lastName: 'User', lastName: "User",
isVerified: true, isVerified: true,
authProvider: 'local', authProvider: "local",
}; };
return User.create({ ...defaultData, ...overrides }); return User.create({ ...defaultData, ...overrides });
@@ -54,17 +54,17 @@ const createTestUser = async (overrides = {}) => {
const createTestItem = async (ownerId, overrides = {}) => { const createTestItem = async (ownerId, overrides = {}) => {
const defaultData = { const defaultData = {
name: 'Test Item', name: "Test Item",
description: 'A test item for rental', description: "A test item for rental",
pricePerDay: 25.00, pricePerDay: 25.0,
pricePerHour: 5.00, pricePerHour: 5.0,
replacementCost: 500.00, replacementCost: 500.0,
condition: 'excellent', condition: "excellent",
isAvailable: true, isAvailable: true,
pickUpAvailable: true, pickUpAvailable: true,
ownerId, ownerId,
city: 'Test City', city: "Test City",
state: 'California', state: "California",
}; };
return Item.create({ ...defaultData, ...overrides }); return Item.create({ ...defaultData, ...overrides });
@@ -84,15 +84,15 @@ const createTestRental = async (itemId, renterId, ownerId, overrides = {}) => {
totalAmount: 0, totalAmount: 0,
platformFee: 0, platformFee: 0,
payoutAmount: 0, payoutAmount: 0,
status: 'pending', status: "pending",
paymentStatus: 'pending', paymentStatus: "pending",
deliveryMethod: 'pickup', deliveryMethod: "pickup",
}; };
return Rental.create({ ...defaultData, ...overrides }); return Rental.create({ ...defaultData, ...overrides });
}; };
describe('Rental Integration Tests', () => { describe("Rental Integration Tests", () => {
let app; let app;
let owner; let owner;
let renter; let renter;
@@ -100,9 +100,9 @@ describe('Rental Integration Tests', () => {
beforeAll(async () => { beforeAll(async () => {
// Set test environment variables // Set test environment variables
process.env.NODE_ENV = 'test'; process.env.NODE_ENV = "test";
process.env.JWT_ACCESS_SECRET = 'test-access-secret'; process.env.JWT_ACCESS_SECRET = "test-access-secret";
process.env.JWT_REFRESH_SECRET = 'test-refresh-secret'; process.env.JWT_REFRESH_SECRET = "test-refresh-secret";
// Sync database // Sync database
await sequelize.sync({ force: true }); await sequelize.sync({ force: true });
@@ -122,32 +122,32 @@ describe('Rental Integration Tests', () => {
// Create test users // Create test users
owner = await createTestUser({ owner = await createTestUser({
email: 'owner@example.com', email: "owner@example.com",
firstName: 'Item', firstName: "Item",
lastName: 'Owner', lastName: "Owner",
stripeConnectedAccountId: 'acct_test_owner', stripeConnectedAccountId: "acct_test_owner",
}); });
renter = await createTestUser({ renter = await createTestUser({
email: 'renter@example.com', email: "renter@example.com",
firstName: 'Item', firstName: "Item",
lastName: 'Renter', lastName: "Renter",
}); });
// Create test item // Create test item
item = await createTestItem(owner.id); item = await createTestItem(owner.id);
}); });
describe('GET /rentals/renting', () => { describe("GET /rentals/renting", () => {
it('should return rentals where user is the renter', async () => { it("should return rentals where user is the renter", async () => {
// Create a rental where renter is the renter // Create a rental where renter is the renter
await createTestRental(item.id, renter.id, owner.id); await createTestRental(item.id, renter.id, owner.id);
const token = generateAuthToken(renter); const token = generateAuthToken(renter);
const response = await request(app) const response = await request(app)
.get('/rentals/renting') .get("/rentals/renting")
.set('Cookie', [`accessToken=${token}`]) .set("Cookie", [`accessToken=${token}`])
.expect(200); .expect(200);
expect(Array.isArray(response.body)).toBe(true); expect(Array.isArray(response.body)).toBe(true);
@@ -155,37 +155,35 @@ describe('Rental Integration Tests', () => {
expect(response.body[0].renterId).toBe(renter.id); expect(response.body[0].renterId).toBe(renter.id);
}); });
it('should return empty array for user with no rentals', async () => { it("should return empty array for user with no rentals", async () => {
const token = generateAuthToken(renter); const token = generateAuthToken(renter);
const response = await request(app) const response = await request(app)
.get('/rentals/renting') .get("/rentals/renting")
.set('Cookie', [`accessToken=${token}`]) .set("Cookie", [`accessToken=${token}`])
.expect(200); .expect(200);
expect(Array.isArray(response.body)).toBe(true); expect(Array.isArray(response.body)).toBe(true);
expect(response.body.length).toBe(0); expect(response.body.length).toBe(0);
}); });
it('should require authentication', async () => { it("should require authentication", async () => {
const response = await request(app) const response = await request(app).get("/rentals/renting").expect(401);
.get('/rentals/renting')
.expect(401);
expect(response.body.code).toBeDefined(); expect(response.body.code).toBeDefined();
}); });
}); });
describe('GET /rentals/owning', () => { describe("GET /rentals/owning", () => {
it('should return rentals where user is the owner', async () => { it("should return rentals where user is the owner", async () => {
// Create a rental where owner is the item owner // Create a rental where owner is the item owner
await createTestRental(item.id, renter.id, owner.id); await createTestRental(item.id, renter.id, owner.id);
const token = generateAuthToken(owner); const token = generateAuthToken(owner);
const response = await request(app) const response = await request(app)
.get('/rentals/owning') .get("/rentals/owning")
.set('Cookie', [`accessToken=${token}`]) .set("Cookie", [`accessToken=${token}`])
.expect(200); .expect(200);
expect(Array.isArray(response.body)).toBe(true); expect(Array.isArray(response.body)).toBe(true);
@@ -194,208 +192,213 @@ describe('Rental Integration Tests', () => {
}); });
}); });
describe('PUT /rentals/:id/status', () => { describe("PUT /rentals/:id/status", () => {
let rental; let rental;
beforeEach(async () => { beforeEach(async () => {
rental = await createTestRental(item.id, renter.id, owner.id); rental = await createTestRental(item.id, renter.id, owner.id);
}); });
it('should allow owner to confirm a pending rental', async () => { it("should allow owner to confirm a pending rental", async () => {
const token = generateAuthToken(owner); const token = generateAuthToken(owner);
const response = await request(app) const response = await request(app)
.put(`/rentals/${rental.id}/status`) .put(`/rentals/${rental.id}/status`)
.set('Cookie', [`accessToken=${token}`]) .set("Cookie", [`accessToken=${token}`])
.send({ status: 'confirmed' }) .send({ status: "confirmed" })
.expect(200); .expect(200);
expect(response.body.status).toBe('confirmed'); expect(response.body.status).toBe("confirmed");
// Verify in database // Verify in database
await rental.reload(); await rental.reload();
expect(rental.status).toBe('confirmed'); expect(rental.status).toBe("confirmed");
}); });
it('should allow renter to update status (no owner-only restriction)', async () => { it("should allow renter to update status (no owner-only restriction)", async () => {
const token = generateAuthToken(renter); const token = generateAuthToken(renter);
const response = await request(app) const response = await request(app)
.put(`/rentals/${rental.id}/status`) .put(`/rentals/${rental.id}/status`)
.set('Cookie', [`accessToken=${token}`]) .set("Cookie", [`accessToken=${token}`])
.send({ status: 'confirmed' }) .send({ status: "confirmed" })
.expect(200); .expect(200);
// Note: API currently allows both owner and renter to update status
// Owner-specific logic (payment processing) only runs for owner // Owner-specific logic (payment processing) only runs for owner
await rental.reload(); await rental.reload();
expect(rental.status).toBe('confirmed'); expect(rental.status).toBe("confirmed");
}); });
it('should handle confirming already confirmed rental (idempotent)', async () => { it("should handle confirming already confirmed rental (idempotent)", async () => {
// First confirm it // First confirm it
await rental.update({ status: 'confirmed' }); await rental.update({ status: "confirmed" });
const token = generateAuthToken(owner); const token = generateAuthToken(owner);
// API allows re-confirming (idempotent operation) // API allows re-confirming (idempotent operation)
const response = await request(app) const response = await request(app)
.put(`/rentals/${rental.id}/status`) .put(`/rentals/${rental.id}/status`)
.set('Cookie', [`accessToken=${token}`]) .set("Cookie", [`accessToken=${token}`])
.send({ status: 'confirmed' }) .send({ status: "confirmed" })
.expect(200); .expect(200);
// Status should remain confirmed // Status should remain confirmed
await rental.reload(); await rental.reload();
expect(rental.status).toBe('confirmed'); expect(rental.status).toBe("confirmed");
}); });
}); });
describe('PUT /rentals/:id/decline', () => { describe("PUT /rentals/:id/decline", () => {
let rental; let rental;
beforeEach(async () => { beforeEach(async () => {
rental = await createTestRental(item.id, renter.id, owner.id); rental = await createTestRental(item.id, renter.id, owner.id);
}); });
it('should allow owner to decline a pending rental', async () => { it("should allow owner to decline a pending rental", async () => {
const token = generateAuthToken(owner); const token = generateAuthToken(owner);
const response = await request(app) const response = await request(app)
.put(`/rentals/${rental.id}/decline`) .put(`/rentals/${rental.id}/decline`)
.set('Cookie', [`accessToken=${token}`]) .set("Cookie", [`accessToken=${token}`])
.send({ reason: 'Item not available for those dates' }) .send({ reason: "Item not available for those dates" })
.expect(200); .expect(200);
expect(response.body.status).toBe('declined'); expect(response.body.status).toBe("declined");
// Verify in database // Verify in database
await rental.reload(); await rental.reload();
expect(rental.status).toBe('declined'); expect(rental.status).toBe("declined");
expect(rental.declineReason).toBe('Item not available for those dates'); expect(rental.declineReason).toBe("Item not available for those dates");
}); });
it('should not allow declining already declined rental', async () => { it("should not allow declining already declined rental", async () => {
await rental.update({ status: 'declined' }); await rental.update({ status: "declined" });
const token = generateAuthToken(owner); const token = generateAuthToken(owner);
const response = await request(app) const response = await request(app)
.put(`/rentals/${rental.id}/decline`) .put(`/rentals/${rental.id}/decline`)
.set('Cookie', [`accessToken=${token}`]) .set("Cookie", [`accessToken=${token}`])
.send({ reason: 'Already declined' }) .send({ reason: "Already declined" })
.expect(400); .expect(400);
expect(response.body.error).toBeDefined(); expect(response.body.error).toBeDefined();
}); });
}); });
describe('POST /rentals/:id/cancel', () => { describe("POST /rentals/:id/cancel", () => {
let rental; let rental;
beforeEach(async () => { beforeEach(async () => {
rental = await createTestRental(item.id, renter.id, owner.id, { rental = await createTestRental(item.id, renter.id, owner.id, {
status: 'confirmed', status: "confirmed",
paymentStatus: 'paid', paymentStatus: "paid",
}); });
}); });
it('should allow renter to cancel their rental', async () => { it("should allow renter to cancel their rental", async () => {
const token = generateAuthToken(renter); const token = generateAuthToken(renter);
const response = await request(app) const response = await request(app)
.post(`/rentals/${rental.id}/cancel`) .post(`/rentals/${rental.id}/cancel`)
.set('Cookie', [`accessToken=${token}`]) .set("Cookie", [`accessToken=${token}`])
.send({ reason: 'Change of plans' }) .send({ reason: "Change of plans" })
.expect(200); .expect(200);
// Response format is { rental: {...}, refund: {...} } // Response format is { rental: {...}, refund: {...} }
expect(response.body.rental.status).toBe('cancelled'); expect(response.body.rental.status).toBe("cancelled");
expect(response.body.rental.cancelledBy).toBe('renter'); expect(response.body.rental.cancelledBy).toBe("renter");
// Verify in database // Verify in database
await rental.reload(); await rental.reload();
expect(rental.status).toBe('cancelled'); expect(rental.status).toBe("cancelled");
expect(rental.cancelledBy).toBe('renter'); expect(rental.cancelledBy).toBe("renter");
expect(rental.cancelledAt).toBeDefined(); expect(rental.cancelledAt).toBeDefined();
}); });
it('should allow owner to cancel their rental', async () => { it("should allow owner to cancel their rental", async () => {
const token = generateAuthToken(owner); const token = generateAuthToken(owner);
const response = await request(app) const response = await request(app)
.post(`/rentals/${rental.id}/cancel`) .post(`/rentals/${rental.id}/cancel`)
.set('Cookie', [`accessToken=${token}`]) .set("Cookie", [`accessToken=${token}`])
.send({ reason: 'Item broken' }) .send({ reason: "Item broken" })
.expect(200); .expect(200);
expect(response.body.rental.status).toBe('cancelled'); expect(response.body.rental.status).toBe("cancelled");
expect(response.body.rental.cancelledBy).toBe('owner'); expect(response.body.rental.cancelledBy).toBe("owner");
}); });
it('should not allow cancelling completed rental', async () => { it("should not allow cancelling completed rental", async () => {
await rental.update({ status: 'completed', paymentStatus: 'paid' }); await rental.update({ status: "completed", paymentStatus: "paid" });
const token = generateAuthToken(renter); const token = generateAuthToken(renter);
// RefundService throws error which becomes 500 via next(error) // RefundService throws error which becomes 500 via next(error)
const response = await request(app) const response = await request(app)
.post(`/rentals/${rental.id}/cancel`) .post(`/rentals/${rental.id}/cancel`)
.set('Cookie', [`accessToken=${token}`]) .set("Cookie", [`accessToken=${token}`])
.send({ reason: 'Too late' }); .send({ reason: "Too late" });
// Expect error (could be 400 or 500 depending on error middleware) // Expect error (could be 400 or 500 depending on error middleware)
expect(response.status).toBeGreaterThanOrEqual(400); expect(response.status).toBeGreaterThanOrEqual(400);
}); });
it('should not allow unauthorized user to cancel rental', async () => { it("should not allow unauthorized user to cancel rental", async () => {
const otherUser = await createTestUser({ email: 'other@example.com' }); const otherUser = await createTestUser({ email: "other@example.com" });
const token = generateAuthToken(otherUser); const token = generateAuthToken(otherUser);
const response = await request(app) const response = await request(app)
.post(`/rentals/${rental.id}/cancel`) .post(`/rentals/${rental.id}/cancel`)
.set('Cookie', [`accessToken=${token}`]) .set("Cookie", [`accessToken=${token}`])
.send({ reason: 'Not my rental' }); .send({ reason: "Not my rental" });
// Expect error (could be 403 or 500 depending on error middleware) // Expect error (could be 403 or 500 depending on error middleware)
expect(response.status).toBeGreaterThanOrEqual(400); expect(response.status).toBeGreaterThanOrEqual(400);
}); });
}); });
describe('GET /rentals/pending-requests-count', () => { describe("GET /rentals/pending-requests-count", () => {
it('should return count of pending rental requests for owner', async () => { it("should return count of pending rental requests for owner", async () => {
// Create multiple pending rentals // Create multiple pending rentals
await createTestRental(item.id, renter.id, owner.id, { status: 'pending' }); await createTestRental(item.id, renter.id, owner.id, {
await createTestRental(item.id, renter.id, owner.id, { status: 'pending' }); status: "pending",
await createTestRental(item.id, renter.id, owner.id, { status: 'confirmed' }); });
await createTestRental(item.id, renter.id, owner.id, {
status: "pending",
});
await createTestRental(item.id, renter.id, owner.id, {
status: "confirmed",
});
const token = generateAuthToken(owner); const token = generateAuthToken(owner);
const response = await request(app) const response = await request(app)
.get('/rentals/pending-requests-count') .get("/rentals/pending-requests-count")
.set('Cookie', [`accessToken=${token}`]) .set("Cookie", [`accessToken=${token}`])
.expect(200); .expect(200);
expect(response.body.count).toBe(2); expect(response.body.count).toBe(2);
}); });
it('should return 0 for user with no pending requests', async () => { it("should return 0 for user with no pending requests", async () => {
const token = generateAuthToken(renter); const token = generateAuthToken(renter);
const response = await request(app) const response = await request(app)
.get('/rentals/pending-requests-count') .get("/rentals/pending-requests-count")
.set('Cookie', [`accessToken=${token}`]) .set("Cookie", [`accessToken=${token}`])
.expect(200); .expect(200);
expect(response.body.count).toBe(0); expect(response.body.count).toBe(0);
}); });
}); });
describe('Rental Lifecycle', () => { describe("Rental Lifecycle", () => {
it('should complete full rental lifecycle: pending -> confirmed -> active -> completed', async () => { it("should complete full rental lifecycle: pending -> confirmed -> active -> completed", async () => {
// Create pending free rental (totalAmount: 0 is default) // Create pending free rental (totalAmount: 0 is default)
const rental = await createTestRental(item.id, renter.id, owner.id, { const rental = await createTestRental(item.id, renter.id, owner.id, {
status: 'pending', status: "pending",
startDateTime: new Date(Date.now() - 60 * 60 * 1000), // Started 1 hour ago startDateTime: new Date(Date.now() - 60 * 60 * 1000), // Started 1 hour ago
endDateTime: new Date(Date.now() + 60 * 60 * 1000), // Ends in 1 hour endDateTime: new Date(Date.now() + 60 * 60 * 1000), // Ends in 1 hour
}); });
@@ -405,52 +408,52 @@ describe('Rental Integration Tests', () => {
// Step 1: Owner confirms rental (works for free rentals) // Step 1: Owner confirms rental (works for free rentals)
let response = await request(app) let response = await request(app)
.put(`/rentals/${rental.id}/status`) .put(`/rentals/${rental.id}/status`)
.set('Cookie', [`accessToken=${ownerToken}`]) .set("Cookie", [`accessToken=${ownerToken}`])
.send({ status: 'confirmed' }) .send({ status: "confirmed" })
.expect(200); .expect(200);
expect(response.body.status).toBe('confirmed'); expect(response.body.status).toBe("confirmed");
// Step 2: Rental is now "active" because status is confirmed and startDateTime has passed // Step 2: Rental is now "active" because status is confirmed and startDateTime has passed.
// Note: "active" is a computed status, not stored. The stored status remains "confirmed" // "active" is a computed status, not stored. The stored status remains "confirmed"
await rental.reload(); await rental.reload();
expect(rental.status).toBe('confirmed'); // Stored status is still 'confirmed' expect(rental.status).toBe("confirmed"); // Stored status is still 'confirmed'
// isActive() returns true because status='confirmed' and startDateTime is in the past // isActive() returns true because status='confirmed' and startDateTime is in the past
// Step 3: Owner marks rental as completed (via mark-return with status='returned') // Step 3: Owner marks rental as completed (via mark-return with status='returned')
response = await request(app) response = await request(app)
.post(`/rentals/${rental.id}/mark-return`) .post(`/rentals/${rental.id}/mark-return`)
.set('Cookie', [`accessToken=${ownerToken}`]) .set("Cookie", [`accessToken=${ownerToken}`])
.send({ status: 'returned' }) .send({ status: "returned" })
.expect(200); .expect(200);
expect(response.body.rental.status).toBe('completed'); expect(response.body.rental.status).toBe("completed");
// Verify final state // Verify final state
await rental.reload(); await rental.reload();
expect(rental.status).toBe('completed'); expect(rental.status).toBe("completed");
}); });
}); });
describe('Review System', () => { describe("Review System", () => {
let completedRental; let completedRental;
beforeEach(async () => { beforeEach(async () => {
completedRental = await createTestRental(item.id, renter.id, owner.id, { completedRental = await createTestRental(item.id, renter.id, owner.id, {
status: 'completed', status: "completed",
paymentStatus: 'paid', paymentStatus: "paid",
}); });
}); });
it('should allow renter to review item', async () => { it("should allow renter to review item", async () => {
const token = generateAuthToken(renter); const token = generateAuthToken(renter);
const response = await request(app) const response = await request(app)
.post(`/rentals/${completedRental.id}/review-item`) .post(`/rentals/${completedRental.id}/review-item`)
.set('Cookie', [`accessToken=${token}`]) .set("Cookie", [`accessToken=${token}`])
.send({ .send({
rating: 5, rating: 5,
review: 'Great item, worked perfectly!', review: "Great item, worked perfectly!",
}) })
.expect(200); .expect(200);
@@ -459,19 +462,19 @@ describe('Rental Integration Tests', () => {
// Verify in database // Verify in database
await completedRental.reload(); await completedRental.reload();
expect(completedRental.itemRating).toBe(5); expect(completedRental.itemRating).toBe(5);
expect(completedRental.itemReview).toBe('Great item, worked perfectly!'); expect(completedRental.itemReview).toBe("Great item, worked perfectly!");
expect(completedRental.itemReviewSubmittedAt).toBeDefined(); expect(completedRental.itemReviewSubmittedAt).toBeDefined();
}); });
it('should allow owner to review renter', async () => { it("should allow owner to review renter", async () => {
const token = generateAuthToken(owner); const token = generateAuthToken(owner);
const response = await request(app) const response = await request(app)
.post(`/rentals/${completedRental.id}/review-renter`) .post(`/rentals/${completedRental.id}/review-renter`)
.set('Cookie', [`accessToken=${token}`]) .set("Cookie", [`accessToken=${token}`])
.send({ .send({
rating: 4, rating: 4,
review: 'Good renter, returned on time.', review: "Good renter, returned on time.",
}) })
.expect(200); .expect(200);
@@ -480,33 +483,40 @@ describe('Rental Integration Tests', () => {
// Verify in database // Verify in database
await completedRental.reload(); await completedRental.reload();
expect(completedRental.renterRating).toBe(4); expect(completedRental.renterRating).toBe(4);
expect(completedRental.renterReview).toBe('Good renter, returned on time.'); expect(completedRental.renterReview).toBe(
"Good renter, returned on time.",
);
}); });
it('should not allow review of non-completed rental', async () => { it("should not allow review of non-completed rental", async () => {
const pendingRental = await createTestRental(item.id, renter.id, owner.id, { const pendingRental = await createTestRental(
status: 'pending', item.id,
}); renter.id,
owner.id,
{
status: "pending",
},
);
const token = generateAuthToken(renter); const token = generateAuthToken(renter);
const response = await request(app) const response = await request(app)
.post(`/rentals/${pendingRental.id}/review-item`) .post(`/rentals/${pendingRental.id}/review-item`)
.set('Cookie', [`accessToken=${token}`]) .set("Cookie", [`accessToken=${token}`])
.send({ .send({
rating: 5, rating: 5,
review: 'Cannot review yet', review: "Cannot review yet",
}) })
.expect(400); .expect(400);
expect(response.body.error).toBeDefined(); expect(response.body.error).toBeDefined();
}); });
it('should not allow duplicate reviews', async () => { it("should not allow duplicate reviews", async () => {
// First review // First review
await completedRental.update({ await completedRental.update({
itemRating: 5, itemRating: 5,
itemReview: 'First review', itemReview: "First review",
itemReviewSubmittedAt: new Date(), itemReviewSubmittedAt: new Date(),
}); });
@@ -514,31 +524,39 @@ describe('Rental Integration Tests', () => {
const response = await request(app) const response = await request(app)
.post(`/rentals/${completedRental.id}/review-item`) .post(`/rentals/${completedRental.id}/review-item`)
.set('Cookie', [`accessToken=${token}`]) .set("Cookie", [`accessToken=${token}`])
.send({ .send({
rating: 3, rating: 3,
review: 'Second review attempt', review: "Second review attempt",
}) })
.expect(400); .expect(400);
expect(response.body.error).toContain('already'); expect(response.body.error).toContain("already");
}); });
}); });
describe('Database Constraints', () => { describe("Database Constraints", () => {
it('should not allow rental with invalid item ID', async () => { it("should not allow rental with invalid item ID", async () => {
await expect( await expect(
createTestRental('00000000-0000-0000-0000-000000000000', renter.id, owner.id) createTestRental(
"00000000-0000-0000-0000-000000000000",
renter.id,
owner.id,
),
).rejects.toThrow(); ).rejects.toThrow();
}); });
it('should not allow rental with invalid user IDs', async () => { it("should not allow rental with invalid user IDs", async () => {
await expect( await expect(
createTestRental(item.id, '00000000-0000-0000-0000-000000000000', owner.id) createTestRental(
item.id,
"00000000-0000-0000-0000-000000000000",
owner.id,
),
).rejects.toThrow(); ).rejects.toThrow();
}); });
it('should cascade delete rentals when item is deleted', async () => { it("should cascade delete rentals when item is deleted", async () => {
const rental = await createTestRental(item.id, renter.id, owner.id); const rental = await createTestRental(item.id, renter.id, owner.id);
// Delete the item // Delete the item
@@ -550,10 +568,10 @@ describe('Rental Integration Tests', () => {
}); });
}); });
describe('Concurrent Operations', () => { describe("Concurrent Operations", () => {
it('should handle concurrent status updates (last write wins)', async () => { it("should handle concurrent status updates (last write wins)", async () => {
const rental = await createTestRental(item.id, renter.id, owner.id, { const rental = await createTestRental(item.id, renter.id, owner.id, {
status: 'pending', status: "pending",
}); });
const ownerToken = generateAuthToken(owner); const ownerToken = generateAuthToken(owner);
@@ -562,22 +580,22 @@ describe('Rental Integration Tests', () => {
const [confirmResult, declineResult] = await Promise.allSettled([ const [confirmResult, declineResult] = await Promise.allSettled([
request(app) request(app)
.put(`/rentals/${rental.id}/status`) .put(`/rentals/${rental.id}/status`)
.set('Cookie', [`accessToken=${ownerToken}`]) .set("Cookie", [`accessToken=${ownerToken}`])
.send({ status: 'confirmed' }), .send({ status: "confirmed" }),
request(app) request(app)
.put(`/rentals/${rental.id}/decline`) .put(`/rentals/${rental.id}/decline`)
.set('Cookie', [`accessToken=${ownerToken}`]) .set("Cookie", [`accessToken=${ownerToken}`])
.send({ reason: 'Declining instead' }), .send({ reason: "Declining instead" }),
]); ]);
// Both requests may succeed (no optimistic locking) // Both requests may succeed (no optimistic locking)
// Verify rental ends up in a valid state // Verify rental ends up in a valid state
await rental.reload(); await rental.reload();
expect(['confirmed', 'declined']).toContain(rental.status); expect(["confirmed", "declined"]).toContain(rental.status);
// At least one should have succeeded // At least one should have succeeded
const successes = [confirmResult, declineResult].filter( const successes = [confirmResult, declineResult].filter(
r => r.status === 'fulfilled' && r.value.status === 200 (r) => r.status === "fulfilled" && r.value.status === 200,
); );
expect(successes.length).toBeGreaterThanOrEqual(1); expect(successes.length).toBeGreaterThanOrEqual(1);
}); });

View File

@@ -98,7 +98,7 @@ describe("Stripe Routes", () => {
StripeService.getCheckoutSession.mockResolvedValue(mockSession); StripeService.getCheckoutSession.mockResolvedValue(mockSession);
const response = await request(app).get( const response = await request(app).get(
"/stripe/checkout-session/cs_123456789" "/stripe/checkout-session/cs_123456789",
); );
expect(response.status).toBe(200); expect(response.status).toBe(200);
@@ -116,7 +116,7 @@ describe("Stripe Routes", () => {
}); });
expect(StripeService.getCheckoutSession).toHaveBeenCalledWith( expect(StripeService.getCheckoutSession).toHaveBeenCalledWith(
"cs_123456789" "cs_123456789",
); );
}); });
@@ -132,7 +132,7 @@ describe("Stripe Routes", () => {
StripeService.getCheckoutSession.mockResolvedValue(mockSession); StripeService.getCheckoutSession.mockResolvedValue(mockSession);
const response = await request(app).get( const response = await request(app).get(
"/stripe/checkout-session/cs_123456789" "/stripe/checkout-session/cs_123456789",
); );
expect(response.status).toBe(200); expect(response.status).toBe(200);
@@ -150,7 +150,7 @@ describe("Stripe Routes", () => {
StripeService.getCheckoutSession.mockRejectedValue(error); StripeService.getCheckoutSession.mockRejectedValue(error);
const response = await request(app).get( const response = await request(app).get(
"/stripe/checkout-session/invalid_session" "/stripe/checkout-session/invalid_session",
); );
expect(response.status).toBe(500); expect(response.status).toBe(500);
@@ -261,7 +261,6 @@ describe("Stripe Routes", () => {
expect(response.status).toBe(500); expect(response.status).toBe(500);
expect(response.body).toEqual({ error: "Invalid email address" }); expect(response.body).toEqual({ error: "Invalid email address" });
// Note: route uses logger instead of console.error
}); });
it("should handle database update errors", async () => { it("should handle database update errors", async () => {
@@ -313,7 +312,7 @@ describe("Stripe Routes", () => {
expect(StripeService.createAccountLink).toHaveBeenCalledWith( expect(StripeService.createAccountLink).toHaveBeenCalledWith(
"acct_123456789", "acct_123456789",
"http://localhost:3000/refresh", "http://localhost:3000/refresh",
"http://localhost:3000/return" "http://localhost:3000/return",
); );
}); });
@@ -413,7 +412,6 @@ describe("Stripe Routes", () => {
expect(response.status).toBe(500); expect(response.status).toBe(500);
expect(response.body).toEqual({ error: "Account not found" }); expect(response.body).toEqual({ error: "Account not found" });
// Note: route uses logger instead of console.error
}); });
}); });
@@ -466,7 +464,7 @@ describe("Stripe Routes", () => {
}); });
expect(StripeService.getAccountStatus).toHaveBeenCalledWith( expect(StripeService.getAccountStatus).toHaveBeenCalledWith(
"acct_123456789" "acct_123456789",
); );
}); });
@@ -516,7 +514,6 @@ describe("Stripe Routes", () => {
expect(response.status).toBe(500); expect(response.status).toBe(500);
expect(response.body).toEqual({ error: "Account not found" }); expect(response.body).toEqual({ error: "Account not found" });
// Note: route uses logger instead of console.error
}); });
}); });
@@ -682,7 +679,6 @@ describe("Stripe Routes", () => {
expect(response.status).toBe(500); expect(response.status).toBe(500);
expect(response.body).toEqual({ error: "Invalid email address" }); expect(response.body).toEqual({ error: "Invalid email address" });
// Note: route uses logger.withRequestId().error() instead of console.error
}); });
it("should handle database update errors", async () => { it("should handle database update errors", async () => {
@@ -785,7 +781,7 @@ describe("Stripe Routes", () => {
StripeService.getCheckoutSession.mockRejectedValue(error); StripeService.getCheckoutSession.mockRejectedValue(error);
const response = await request(app).get( const response = await request(app).get(
`/stripe/checkout-session/${longSessionId}` `/stripe/checkout-session/${longSessionId}`,
); );
expect(response.status).toBe(500); expect(response.status).toBe(500);

View File

@@ -159,7 +159,7 @@ describe("EmailClient", () => {
); );
expect(SendEmailCommand).toHaveBeenCalledWith({ expect(SendEmailCommand).toHaveBeenCalledWith({
Source: "Village Share <noreply@villageshare.app>", Source: "Village Share <noreply@email.com>",
Destination: { Destination: {
ToAddresses: ["test@example.com"], ToAddresses: ["test@example.com"],
}, },
@@ -253,7 +253,7 @@ describe("EmailClient", () => {
expect(SendEmailCommand).toHaveBeenCalledWith( expect(SendEmailCommand).toHaveBeenCalledWith(
expect.objectContaining({ expect.objectContaining({
ReplyToAddresses: ["support@villageshare.app"], ReplyToAddresses: ["support@email.com"],
}), }),
); );
}); });

View File

@@ -123,7 +123,7 @@ describe("UserEngagementEmailService", () => {
ownerName: "John", ownerName: "John",
itemName: "Power Drill", itemName: "Power Drill",
deletionReason: "Violated community guidelines", deletionReason: "Violated community guidelines",
supportEmail: "support@villageshare.com", supportEmail: "support@email.com",
dashboardUrl: "http://localhost:3000/owning", dashboardUrl: "http://localhost:3000/owning",
}), }),
); );
@@ -183,7 +183,7 @@ describe("UserEngagementEmailService", () => {
expect.objectContaining({ expect.objectContaining({
userName: "John", userName: "John",
banReason: "Multiple policy violations", banReason: "Multiple policy violations",
supportEmail: "support@villageshare.com", supportEmail: "support@email.com",
}), }),
); );
expect(service.emailClient.sendEmail).toHaveBeenCalledWith( expect(service.emailClient.sendEmail).toHaveBeenCalledWith(

View File

@@ -1,46 +0,0 @@
# Getting Started with Create React App
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.\
You will also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `npm run build`
Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you cant go back!**
If you arent satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point youre on your own.
You dont have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldnt feel obligated to use this feature. However we understand that this tool wouldnt be useful if you couldnt customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).

View File

@@ -5,19 +5,25 @@
* automatic token verification and manual code entry. * automatic token verification and manual code entry.
*/ */
import React from 'react'; import React from "react";
import { render, screen, waitFor, fireEvent, act } from '@testing-library/react'; import {
import userEvent from '@testing-library/user-event'; render,
import { vi, type MockedFunction } from 'vitest'; screen,
import { MemoryRouter, Routes, Route } from 'react-router'; waitFor,
import VerifyEmail from '../../pages/VerifyEmail'; fireEvent,
import { useAuth } from '../../contexts/AuthContext'; act,
import { authAPI } from '../../services/api'; } from "@testing-library/react";
import { mockUser, mockUnverifiedUser } from '../../mocks/handlers'; import userEvent from "@testing-library/user-event";
import { vi, type MockedFunction } from "vitest";
import { MemoryRouter, Routes, Route } from "react-router";
import VerifyEmail from "../../pages/VerifyEmail";
import { useAuth } from "../../contexts/AuthContext";
import { authAPI } from "../../services/api";
import { mockUser, mockUnverifiedUser } from "../../mocks/handlers";
// Mock dependencies // Mock dependencies
vi.mock('../../contexts/AuthContext'); vi.mock("../../contexts/AuthContext");
vi.mock('../../services/api', () => ({ vi.mock("../../services/api", () => ({
authAPI: { authAPI: {
verifyEmail: vi.fn(), verifyEmail: vi.fn(),
resendVerification: vi.fn(), resendVerification: vi.fn(),
@@ -25,8 +31,8 @@ vi.mock('../../services/api', () => ({
})); }));
const mockNavigate = vi.fn(); const mockNavigate = vi.fn();
vi.mock('react-router', async (importOriginal) => { vi.mock("react-router", async (importOriginal) => {
const actual = await importOriginal<typeof import('react-router')>(); const actual = await importOriginal<typeof import("react-router")>();
return { return {
...actual, ...actual,
useNavigate: () => mockNavigate, useNavigate: () => mockNavigate,
@@ -34,16 +40,23 @@ vi.mock('react-router', async (importOriginal) => {
}); });
const mockedUseAuth = useAuth as MockedFunction<typeof useAuth>; const mockedUseAuth = useAuth as MockedFunction<typeof useAuth>;
const mockedVerifyEmail = authAPI.verifyEmail as MockedFunction<typeof authAPI.verifyEmail>; const mockedVerifyEmail = authAPI.verifyEmail as MockedFunction<
const mockedResendVerification = authAPI.resendVerification as MockedFunction<typeof authAPI.resendVerification>; typeof authAPI.verifyEmail
>;
const mockedResendVerification = authAPI.resendVerification as MockedFunction<
typeof authAPI.resendVerification
>;
// Helper to render VerifyEmail with route params // Helper to render VerifyEmail with route params
const renderVerifyEmail = (searchParams: string = '', authOverrides: Partial<ReturnType<typeof useAuth>> = {}) => { const renderVerifyEmail = (
searchParams: string = "",
authOverrides: Partial<ReturnType<typeof useAuth>> = {},
) => {
mockedUseAuth.mockReturnValue({ mockedUseAuth.mockReturnValue({
user: mockUnverifiedUser, user: mockUnverifiedUser,
loading: false, loading: false,
showAuthModal: false, showAuthModal: false,
authModalMode: 'login', authModalMode: "login",
login: vi.fn(), login: vi.fn(),
register: vi.fn(), register: vi.fn(),
googleLogin: vi.fn(), googleLogin: vi.fn(),
@@ -60,11 +73,11 @@ const renderVerifyEmail = (searchParams: string = '', authOverrides: Partial<Ret
<Routes> <Routes>
<Route path="/verify-email" element={<VerifyEmail />} /> <Route path="/verify-email" element={<VerifyEmail />} />
</Routes> </Routes>
</MemoryRouter> </MemoryRouter>,
); );
}; };
describe('VerifyEmail', () => { describe("VerifyEmail", () => {
beforeEach(() => { beforeEach(() => {
vi.clearAllMocks(); vi.clearAllMocks();
vi.useFakeTimers({ shouldAdvanceTime: true }); vi.useFakeTimers({ shouldAdvanceTime: true });
@@ -76,77 +89,85 @@ describe('VerifyEmail', () => {
vi.useRealTimers(); vi.useRealTimers();
}); });
describe('Initial Loading State', () => { describe("Initial Loading State", () => {
it('shows loading state while auth is initializing', async () => { it("shows loading state while auth is initializing", async () => {
renderVerifyEmail('', { loading: true }); renderVerifyEmail("", { loading: true });
expect(screen.getByRole('status')).toBeInTheDocument(); expect(screen.getByRole("status")).toBeInTheDocument();
// There are multiple "Loading..." elements - the spinner's visually-hidden text and the heading // There are multiple "Loading..." elements - the spinner's visually-hidden text and the heading
expect(screen.getAllByText('Loading...').length).toBeGreaterThanOrEqual(1); expect(screen.getAllByText("Loading...").length).toBeGreaterThanOrEqual(
1,
);
}); });
}); });
describe('Authentication Check', () => { describe("Authentication Check", () => {
it('redirects unauthenticated users to login', async () => { it("redirects unauthenticated users to login", async () => {
renderVerifyEmail('', { user: null }); renderVerifyEmail("", { user: null });
await waitFor(() => { await waitFor(() => {
expect(mockNavigate).toHaveBeenCalledWith( expect(mockNavigate).toHaveBeenCalledWith(
expect.stringContaining('/?login=true&redirect='), expect.stringContaining("/?login=true&redirect="),
{ replace: true } { replace: true },
); );
}); });
}); });
it('redirects unauthenticated users with token to login with return URL', async () => { it("redirects unauthenticated users with token to login with return URL", async () => {
renderVerifyEmail('?token=test-token-123', { user: null }); renderVerifyEmail("?token=test-token-123", { user: null });
await waitFor(() => { await waitFor(() => {
expect(mockNavigate).toHaveBeenCalledWith( expect(mockNavigate).toHaveBeenCalledWith(
expect.stringContaining('login=true'), expect.stringContaining("login=true"),
{ replace: true } { replace: true },
); );
expect(mockNavigate).toHaveBeenCalledWith( expect(mockNavigate).toHaveBeenCalledWith(
expect.stringContaining('verify-email'), expect.stringContaining("verify-email"),
{ replace: true } { replace: true },
); );
}); });
}); });
}); });
describe('Auto-Verification with Token', () => { describe("Auto-Verification with Token", () => {
it('auto-verifies when token present in URL', async () => { it("auto-verifies when token present in URL", async () => {
renderVerifyEmail('?token=valid-token-123'); renderVerifyEmail("?token=valid-token-123");
await waitFor(() => { await waitFor(() => {
expect(mockedVerifyEmail).toHaveBeenCalledWith('valid-token-123'); expect(mockedVerifyEmail).toHaveBeenCalledWith("valid-token-123");
}); });
}); });
it('shows success state after successful verification', async () => { it("shows success state after successful verification", async () => {
const mockCheckAuth = vi.fn(); const mockCheckAuth = vi.fn();
renderVerifyEmail('?token=valid-token', { checkAuth: mockCheckAuth }); renderVerifyEmail("?token=valid-token", { checkAuth: mockCheckAuth });
await waitFor(() => { await waitFor(() => {
expect(screen.getByText('Email Verified Successfully!')).toBeInTheDocument(); expect(
screen.getByText("Email Verified Successfully!"),
).toBeInTheDocument();
}); });
expect(mockCheckAuth).toHaveBeenCalled(); expect(mockCheckAuth).toHaveBeenCalled();
}); });
it('shows success state immediately for already verified user', async () => { it("shows success state immediately for already verified user", async () => {
renderVerifyEmail('', { user: mockUser }); renderVerifyEmail("", { user: mockUser });
await waitFor(() => { await waitFor(() => {
expect(screen.getByText('Email Verified Successfully!')).toBeInTheDocument(); expect(
screen.getByText("Email Verified Successfully!"),
).toBeInTheDocument();
}); });
}); });
it('auto-redirects to home after successful verification', async () => { it("auto-redirects to home after successful verification", async () => {
renderVerifyEmail('?token=valid-token'); renderVerifyEmail("?token=valid-token");
await waitFor(() => { await waitFor(() => {
expect(screen.getByText('Email Verified Successfully!')).toBeInTheDocument(); expect(
screen.getByText("Email Verified Successfully!"),
).toBeInTheDocument();
}); });
// Advance timers to trigger auto-redirect (3 seconds) // Advance timers to trigger auto-redirect (3 seconds)
@@ -155,215 +176,228 @@ describe('VerifyEmail', () => {
}); });
await waitFor(() => { await waitFor(() => {
expect(mockNavigate).toHaveBeenCalledWith('/', { replace: true }); expect(mockNavigate).toHaveBeenCalledWith("/", { replace: true });
}); });
}); });
}); });
describe('Manual Code Entry', () => { describe("Manual Code Entry", () => {
it('shows manual code entry form when no token in URL', async () => { it("shows manual code entry form when no token in URL", async () => {
renderVerifyEmail(); renderVerifyEmail();
await waitFor(() => { await waitFor(() => {
expect(screen.getByText('Enter Verification Code')).toBeInTheDocument(); expect(screen.getByText("Enter Verification Code")).toBeInTheDocument();
expect(screen.getByText('Enter the 6-digit code sent to your email')).toBeInTheDocument(); expect(
screen.getByText("Enter the 6-digit code sent to your email"),
).toBeInTheDocument();
}); });
// Check for 6 input fields // Check for 6 input fields
const inputs = screen.getAllByRole('textbox'); const inputs = screen.getAllByRole("textbox");
expect(inputs).toHaveLength(6); expect(inputs).toHaveLength(6);
}); });
it('handles 6-digit input with auto-focus', async () => { it("handles 6-digit input with auto-focus", async () => {
renderVerifyEmail(); renderVerifyEmail();
await waitFor(() => { await waitFor(() => {
expect(screen.getByText('Enter Verification Code')).toBeInTheDocument(); expect(screen.getByText("Enter Verification Code")).toBeInTheDocument();
}); });
const inputs = screen.getAllByRole('textbox'); const inputs = screen.getAllByRole("textbox");
// Type first digit using fireEvent // Type first digit using fireEvent
fireEvent.change(inputs[0], { target: { value: '1' } }); fireEvent.change(inputs[0], { target: { value: "1" } });
expect(inputs[0]).toHaveValue('1'); expect(inputs[0]).toHaveValue("1");
// Focus should auto-move to next input // Focus should auto-move to next input
// (Note: actual focus behavior may depend on DOM focus events) // (actual focus behavior may depend on DOM focus events)
}); });
it('filters non-numeric input', async () => { it("filters non-numeric input", async () => {
renderVerifyEmail(); renderVerifyEmail();
await waitFor(() => { await waitFor(() => {
expect(screen.getByText('Enter Verification Code')).toBeInTheDocument(); expect(screen.getByText("Enter Verification Code")).toBeInTheDocument();
}); });
const inputs = screen.getAllByRole('textbox'); const inputs = screen.getAllByRole("textbox");
// Try typing letters // Try typing letters
fireEvent.change(inputs[0], { target: { value: 'a' } }); fireEvent.change(inputs[0], { target: { value: "a" } });
expect(inputs[0]).toHaveValue(''); expect(inputs[0]).toHaveValue("");
// Try typing numbers // Try typing numbers
fireEvent.change(inputs[0], { target: { value: '5' } }); fireEvent.change(inputs[0], { target: { value: "5" } });
expect(inputs[0]).toHaveValue('5'); expect(inputs[0]).toHaveValue("5");
}); });
it('handles paste of 6-digit code', async () => { it("handles paste of 6-digit code", async () => {
renderVerifyEmail(); renderVerifyEmail();
await waitFor(() => { await waitFor(() => {
expect(screen.getByText('Enter Verification Code')).toBeInTheDocument(); expect(screen.getByText("Enter Verification Code")).toBeInTheDocument();
}); });
const container = document.querySelector('.d-flex.justify-content-center.gap-2'); const container = document.querySelector(
".d-flex.justify-content-center.gap-2",
);
// Simulate paste event // Simulate paste event
const pasteEvent = new Event('paste', { bubbles: true, cancelable: true }) as any; const pasteEvent = new Event("paste", {
bubbles: true,
cancelable: true,
}) as any;
pasteEvent.clipboardData = { pasteEvent.clipboardData = {
getData: () => '123456', getData: () => "123456",
}; };
fireEvent(container!, pasteEvent); fireEvent(container!, pasteEvent);
await waitFor(() => { await waitFor(() => {
expect(mockedVerifyEmail).toHaveBeenCalledWith('123456'); expect(mockedVerifyEmail).toHaveBeenCalledWith("123456");
}); });
}); });
it('submits manual code on button click', async () => { it("submits manual code on button click", async () => {
// Make the verification hang to test the button state // Make the verification hang to test the button state
mockedVerifyEmail.mockImplementation(() => new Promise(() => {})); mockedVerifyEmail.mockImplementation(() => new Promise(() => {}));
renderVerifyEmail(); renderVerifyEmail();
await waitFor(() => { await waitFor(() => {
expect(screen.getByText('Enter Verification Code')).toBeInTheDocument(); expect(screen.getByText("Enter Verification Code")).toBeInTheDocument();
}); });
const inputs = screen.getAllByRole('textbox'); const inputs = screen.getAllByRole("textbox");
// Fill in 5 digits (not 6 to avoid auto-submit) // Fill in 5 digits (not 6 to avoid auto-submit)
fireEvent.change(inputs[0], { target: { value: '1' } }); fireEvent.change(inputs[0], { target: { value: "1" } });
fireEvent.change(inputs[1], { target: { value: '2' } }); fireEvent.change(inputs[1], { target: { value: "2" } });
fireEvent.change(inputs[2], { target: { value: '3' } }); fireEvent.change(inputs[2], { target: { value: "3" } });
fireEvent.change(inputs[3], { target: { value: '4' } }); fireEvent.change(inputs[3], { target: { value: "4" } });
fireEvent.change(inputs[4], { target: { value: '5' } }); fireEvent.change(inputs[4], { target: { value: "5" } });
// Button should be disabled with only 5 digits // Button should be disabled with only 5 digits
const verifyButton = screen.getByRole('button', { name: /verify email/i }); const verifyButton = screen.getByRole("button", {
name: /verify email/i,
});
expect(verifyButton).toBeDisabled(); expect(verifyButton).toBeDisabled();
// Now fill in the 6th digit - this will auto-submit // Now fill in the 6th digit - this will auto-submit
fireEvent.change(inputs[5], { target: { value: '6' } }); fireEvent.change(inputs[5], { target: { value: "6" } });
// The component auto-submits when 6 digits are entered // The component auto-submits when 6 digits are entered
await waitFor(() => { await waitFor(() => {
expect(mockedVerifyEmail).toHaveBeenCalledWith('123456'); expect(mockedVerifyEmail).toHaveBeenCalledWith("123456");
}); });
}); });
it('disables verify button when code incomplete', async () => { it("disables verify button when code incomplete", async () => {
renderVerifyEmail(); renderVerifyEmail();
await waitFor(() => { await waitFor(() => {
expect(screen.getByText('Enter Verification Code')).toBeInTheDocument(); expect(screen.getByText("Enter Verification Code")).toBeInTheDocument();
}); });
const verifyButton = screen.getByRole('button', { name: /verify email/i }); const verifyButton = screen.getByRole("button", {
name: /verify email/i,
});
expect(verifyButton).toBeDisabled(); expect(verifyButton).toBeDisabled();
}); });
it('backspace moves focus to previous input', async () => { it("backspace moves focus to previous input", async () => {
renderVerifyEmail(); renderVerifyEmail();
await waitFor(() => { await waitFor(() => {
expect(screen.getByText('Enter Verification Code')).toBeInTheDocument(); expect(screen.getByText("Enter Verification Code")).toBeInTheDocument();
}); });
const inputs = screen.getAllByRole('textbox'); const inputs = screen.getAllByRole("textbox");
// Fill first input and move to second // Fill first input and move to second
fireEvent.change(inputs[0], { target: { value: '1' } }); fireEvent.change(inputs[0], { target: { value: "1" } });
fireEvent.change(inputs[1], { target: { value: '2' } }); fireEvent.change(inputs[1], { target: { value: "2" } });
// Clear second input and press backspace // Clear second input and press backspace
fireEvent.change(inputs[1], { target: { value: '' } }); fireEvent.change(inputs[1], { target: { value: "" } });
fireEvent.keyDown(inputs[1], { key: 'Backspace' }); fireEvent.keyDown(inputs[1], { key: "Backspace" });
// The component handles this by focusing previous input // The component handles this by focusing previous input
}); });
}); });
describe('Error Handling', () => { describe("Error Handling", () => {
it('displays EXPIRED error message', async () => { it("displays EXPIRED error message", async () => {
mockedVerifyEmail.mockRejectedValue({ mockedVerifyEmail.mockRejectedValue({
response: { data: { code: 'VERIFICATION_EXPIRED' } }, response: { data: { code: "VERIFICATION_EXPIRED" } },
}); });
renderVerifyEmail('?token=expired-token'); renderVerifyEmail("?token=expired-token");
await waitFor(() => { await waitFor(() => {
expect(screen.getByText(/verification code has expired/i)).toBeInTheDocument(); expect(
screen.getByText(/verification code has expired/i),
).toBeInTheDocument();
}); });
}); });
it('displays INVALID error message', async () => { it("displays INVALID error message", async () => {
mockedVerifyEmail.mockRejectedValue({ mockedVerifyEmail.mockRejectedValue({
response: { data: { code: 'VERIFICATION_INVALID' } }, response: { data: { code: "VERIFICATION_INVALID" } },
}); });
renderVerifyEmail('?token=invalid-token'); renderVerifyEmail("?token=invalid-token");
await waitFor(() => { await waitFor(() => {
expect(screen.getByText(/code didn't match/i)).toBeInTheDocument(); expect(screen.getByText(/code didn't match/i)).toBeInTheDocument();
}); });
}); });
it('displays TOO_MANY_ATTEMPTS error message', async () => { it("displays TOO_MANY_ATTEMPTS error message", async () => {
mockedVerifyEmail.mockRejectedValue({ mockedVerifyEmail.mockRejectedValue({
response: { data: { code: 'TOO_MANY_ATTEMPTS' } }, response: { data: { code: "TOO_MANY_ATTEMPTS" } },
}); });
renderVerifyEmail('?token=blocked-token'); renderVerifyEmail("?token=blocked-token");
await waitFor(() => { await waitFor(() => {
expect(screen.getByText(/too many attempts/i)).toBeInTheDocument(); expect(screen.getByText(/too many attempts/i)).toBeInTheDocument();
}); });
}); });
it('displays ALREADY_VERIFIED error message', async () => { it("displays ALREADY_VERIFIED error message", async () => {
mockedVerifyEmail.mockRejectedValue({ mockedVerifyEmail.mockRejectedValue({
response: { data: { code: 'ALREADY_VERIFIED' } }, response: { data: { code: "ALREADY_VERIFIED" } },
}); });
renderVerifyEmail('?token=already-verified-token'); renderVerifyEmail("?token=already-verified-token");
await waitFor(() => { await waitFor(() => {
expect(screen.getByText(/already verified/i)).toBeInTheDocument(); expect(screen.getByText(/already verified/i)).toBeInTheDocument();
}); });
}); });
it('clears input on error', async () => { it("clears input on error", async () => {
mockedVerifyEmail.mockRejectedValue({ mockedVerifyEmail.mockRejectedValue({
response: { data: { code: 'VERIFICATION_INVALID' } }, response: { data: { code: "VERIFICATION_INVALID" } },
}); });
renderVerifyEmail(); renderVerifyEmail();
await waitFor(() => { await waitFor(() => {
expect(screen.getByText('Enter Verification Code')).toBeInTheDocument(); expect(screen.getByText("Enter Verification Code")).toBeInTheDocument();
}); });
const inputs = screen.getAllByRole('textbox'); const inputs = screen.getAllByRole("textbox");
// Fill all digits - this will auto-submit due to the component behavior // Fill all digits - this will auto-submit due to the component behavior
fireEvent.change(inputs[0], { target: { value: '1' } }); fireEvent.change(inputs[0], { target: { value: "1" } });
fireEvent.change(inputs[1], { target: { value: '2' } }); fireEvent.change(inputs[1], { target: { value: "2" } });
fireEvent.change(inputs[2], { target: { value: '3' } }); fireEvent.change(inputs[2], { target: { value: "3" } });
fireEvent.change(inputs[3], { target: { value: '4' } }); fireEvent.change(inputs[3], { target: { value: "4" } });
fireEvent.change(inputs[4], { target: { value: '5' } }); fireEvent.change(inputs[4], { target: { value: "5" } });
fireEvent.change(inputs[5], { target: { value: '6' } }); fireEvent.change(inputs[5], { target: { value: "6" } });
// Wait for error message to appear // Wait for error message to appear
await waitFor(() => { await waitFor(() => {
@@ -372,33 +406,35 @@ describe('VerifyEmail', () => {
// Inputs should be cleared after error // Inputs should be cleared after error
await waitFor(() => { await waitFor(() => {
const updatedInputs = screen.getAllByRole('textbox'); const updatedInputs = screen.getAllByRole("textbox");
updatedInputs.forEach((input) => { updatedInputs.forEach((input) => {
expect(input).toHaveValue(''); expect(input).toHaveValue("");
}); });
}); });
}); });
}); });
describe('Resend Verification', () => { describe("Resend Verification", () => {
it('shows resend button', async () => { it("shows resend button", async () => {
renderVerifyEmail(); renderVerifyEmail();
await waitFor(() => { await waitFor(() => {
expect(screen.getByText('Enter Verification Code')).toBeInTheDocument(); expect(screen.getByText("Enter Verification Code")).toBeInTheDocument();
}); });
expect(screen.getByRole('button', { name: /send code/i })).toBeInTheDocument(); expect(
screen.getByRole("button", { name: /send code/i }),
).toBeInTheDocument();
}); });
it('starts 60-second cooldown after resend', async () => { it("starts 60-second cooldown after resend", async () => {
renderVerifyEmail(); renderVerifyEmail();
await waitFor(() => { await waitFor(() => {
expect(screen.getByText('Enter Verification Code')).toBeInTheDocument(); expect(screen.getByText("Enter Verification Code")).toBeInTheDocument();
}); });
const resendButton = screen.getByRole('button', { name: /send code/i }); const resendButton = screen.getByRole("button", { name: /send code/i });
fireEvent.click(resendButton); fireEvent.click(resendButton);
await waitFor(() => { await waitFor(() => {
@@ -408,32 +444,32 @@ describe('VerifyEmail', () => {
expect(mockedResendVerification).toHaveBeenCalled(); expect(mockedResendVerification).toHaveBeenCalled();
}); });
it('disables resend during cooldown', async () => { it("disables resend during cooldown", async () => {
renderVerifyEmail(); renderVerifyEmail();
await waitFor(() => { await waitFor(() => {
expect(screen.getByText('Enter Verification Code')).toBeInTheDocument(); expect(screen.getByText("Enter Verification Code")).toBeInTheDocument();
}); });
const resendButton = screen.getByRole('button', { name: /send code/i }); const resendButton = screen.getByRole("button", { name: /send code/i });
fireEvent.click(resendButton); fireEvent.click(resendButton);
await waitFor(() => { await waitFor(() => {
expect(screen.getByText(/resend in 60s/i)).toBeInTheDocument(); expect(screen.getByText(/resend in 60s/i)).toBeInTheDocument();
}); });
const cooldownButton = screen.getByRole('button', { name: /resend in/i }); const cooldownButton = screen.getByRole("button", { name: /resend in/i });
expect(cooldownButton).toBeDisabled(); expect(cooldownButton).toBeDisabled();
}); });
it('shows success message after resend', async () => { it("shows success message after resend", async () => {
renderVerifyEmail(); renderVerifyEmail();
await waitFor(() => { await waitFor(() => {
expect(screen.getByText('Enter Verification Code')).toBeInTheDocument(); expect(screen.getByText("Enter Verification Code")).toBeInTheDocument();
}); });
const resendButton = screen.getByRole('button', { name: /send code/i }); const resendButton = screen.getByRole("button", { name: /send code/i });
fireEvent.click(resendButton); fireEvent.click(resendButton);
await waitFor(() => { await waitFor(() => {
@@ -441,14 +477,14 @@ describe('VerifyEmail', () => {
}); });
}); });
it('counts down timer', async () => { it("counts down timer", async () => {
renderVerifyEmail(); renderVerifyEmail();
await waitFor(() => { await waitFor(() => {
expect(screen.getByText('Enter Verification Code')).toBeInTheDocument(); expect(screen.getByText("Enter Verification Code")).toBeInTheDocument();
}); });
const resendButton = screen.getByRole('button', { name: /send code/i }); const resendButton = screen.getByRole("button", { name: /send code/i });
fireEvent.click(resendButton); fireEvent.click(resendButton);
await waitFor(() => { await waitFor(() => {
@@ -457,25 +493,30 @@ describe('VerifyEmail', () => {
// With shouldAdvanceTime: true, the timer will automatically count down // With shouldAdvanceTime: true, the timer will automatically count down
// Wait for the countdown to show a lower value // Wait for the countdown to show a lower value
await waitFor(() => { await waitFor(
// Timer should have counted down from 60s to something less () => {
const resendText = screen.getByRole('button', { name: /resend in \d+s/i }).textContent; // Timer should have counted down from 60s to something less
expect(resendText).toMatch(/Resend in [0-5][0-9]s/); const resendText = screen.getByRole("button", {
}, { timeout: 3000 }); name: /resend in \d+s/i,
}).textContent;
expect(resendText).toMatch(/Resend in [0-5][0-9]s/);
},
{ timeout: 3000 },
);
}); });
it('handles resend error for already verified', async () => { it("handles resend error for already verified", async () => {
mockedResendVerification.mockRejectedValue({ mockedResendVerification.mockRejectedValue({
response: { data: { code: 'ALREADY_VERIFIED' } }, response: { data: { code: "ALREADY_VERIFIED" } },
}); });
renderVerifyEmail(); renderVerifyEmail();
await waitFor(() => { await waitFor(() => {
expect(screen.getByText('Enter Verification Code')).toBeInTheDocument(); expect(screen.getByText("Enter Verification Code")).toBeInTheDocument();
}); });
const resendButton = screen.getByRole('button', { name: /send code/i }); const resendButton = screen.getByRole("button", { name: /send code/i });
fireEvent.click(resendButton); fireEvent.click(resendButton);
await waitFor(() => { await waitFor(() => {
@@ -483,7 +524,7 @@ describe('VerifyEmail', () => {
}); });
}); });
it('handles rate limit error (429)', async () => { it("handles rate limit error (429)", async () => {
mockedResendVerification.mockRejectedValue({ mockedResendVerification.mockRejectedValue({
response: { status: 429 }, response: { status: 429 },
}); });
@@ -491,39 +532,43 @@ describe('VerifyEmail', () => {
renderVerifyEmail(); renderVerifyEmail();
await waitFor(() => { await waitFor(() => {
expect(screen.getByText('Enter Verification Code')).toBeInTheDocument(); expect(screen.getByText("Enter Verification Code")).toBeInTheDocument();
}); });
const resendButton = screen.getByRole('button', { name: /send code/i }); const resendButton = screen.getByRole("button", { name: /send code/i });
fireEvent.click(resendButton); fireEvent.click(resendButton);
await waitFor(() => { await waitFor(() => {
expect(screen.getByText(/please wait before requesting/i)).toBeInTheDocument(); expect(
screen.getByText(/please wait before requesting/i),
).toBeInTheDocument();
}); });
}); });
}); });
describe('Navigation', () => { describe("Navigation", () => {
it('has return to home link', async () => { it("has return to home link", async () => {
renderVerifyEmail(); renderVerifyEmail();
await waitFor(() => { await waitFor(() => {
expect(screen.getByText('Enter Verification Code')).toBeInTheDocument(); expect(screen.getByText("Enter Verification Code")).toBeInTheDocument();
}); });
const homeLink = screen.getByRole('link', { name: /return to home/i }); const homeLink = screen.getByRole("link", { name: /return to home/i });
expect(homeLink).toHaveAttribute('href', '/'); expect(homeLink).toHaveAttribute("href", "/");
}); });
it('has go to home link on success', async () => { it("has go to home link on success", async () => {
renderVerifyEmail('?token=valid-token'); renderVerifyEmail("?token=valid-token");
await waitFor(() => { await waitFor(() => {
expect(screen.getByText('Email Verified Successfully!')).toBeInTheDocument(); expect(
screen.getByText("Email Verified Successfully!"),
).toBeInTheDocument();
}); });
const homeLink = screen.getByRole('link', { name: /go to home page/i }); const homeLink = screen.getByRole("link", { name: /go to home page/i });
expect(homeLink).toHaveAttribute('href', '/'); expect(homeLink).toHaveAttribute("href", "/");
}); });
}); });
}); });

View File

@@ -5,8 +5,8 @@
* direct uploads, and signed URL generation for private content. * direct uploads, and signed URL generation for private content.
*/ */
import { vi, type Mocked } from 'vitest'; import { vi, type Mocked } from "vitest";
import api from '../../services/api'; import api from "../../services/api";
import { import {
getPublicImageUrl, getPublicImageUrl,
getPresignedUrl, getPresignedUrl,
@@ -16,10 +16,10 @@ import {
uploadFile, uploadFile,
getSignedUrl, getSignedUrl,
PresignedUrlResponse, PresignedUrlResponse,
} from '../../services/uploadService'; } from "../../services/uploadService";
// Mock the api module // Mock the api module
vi.mock('../../services/api'); vi.mock("../../services/api");
const mockedApi = api as Mocked<typeof api>; const mockedApi = api as Mocked<typeof api>;
@@ -29,16 +29,22 @@ class MockXMLHttpRequest {
status = 200; status = 200;
readyState = 4; readyState = 4;
responseText = ''; responseText = "";
upload = { upload = {
onprogress: null as ((e: { lengthComputable: boolean; loaded: number; total: number }) => void) | null, onprogress: null as
| ((e: {
lengthComputable: boolean;
loaded: number;
total: number;
}) => void)
| null,
}; };
onload: (() => void) | null = null; onload: (() => void) | null = null;
onerror: (() => void) | null = null; onerror: (() => void) | null = null;
private headers: Record<string, string> = {}; private headers: Record<string, string> = {};
private method = ''; private method = "";
private url = ''; private url = "";
constructor() { constructor() {
MockXMLHttpRequest.instances.push(this); MockXMLHttpRequest.instances.push(this);
@@ -58,8 +64,16 @@ class MockXMLHttpRequest {
// This allows promises to resolve without real delays // This allows promises to resolve without real delays
Promise.resolve().then(() => { Promise.resolve().then(() => {
if (this.upload.onprogress) { if (this.upload.onprogress) {
this.upload.onprogress({ lengthComputable: true, loaded: 50, total: 100 }); this.upload.onprogress({
this.upload.onprogress({ lengthComputable: true, loaded: 100, total: 100 }); lengthComputable: true,
loaded: 50,
total: 100,
});
this.upload.onprogress({
lengthComputable: true,
loaded: 100,
total: 100,
});
} }
if (this.onload) { if (this.onload) {
this.onload(); this.onload();
@@ -84,181 +98,222 @@ class MockXMLHttpRequest {
} }
static getLastInstance() { static getLastInstance() {
return MockXMLHttpRequest.instances[MockXMLHttpRequest.instances.length - 1]; return MockXMLHttpRequest.instances[
MockXMLHttpRequest.instances.length - 1
];
} }
} }
// Store original XMLHttpRequest // Store original XMLHttpRequest
const originalXMLHttpRequest = global.XMLHttpRequest; const originalXMLHttpRequest = global.XMLHttpRequest;
describe('Upload Service', () => { describe("Upload Service", () => {
beforeEach(() => { beforeEach(() => {
vi.clearAllMocks(); vi.clearAllMocks();
MockXMLHttpRequest.reset(); MockXMLHttpRequest.reset();
// Reset environment variables using stubEnv for Vitest // Reset environment variables using stubEnv for Vitest
vi.stubEnv('VITE_S3_BUCKET', 'test-bucket'); vi.stubEnv("VITE_S3_BUCKET", "test-bucket");
vi.stubEnv('VITE_AWS_REGION', 'us-east-1'); vi.stubEnv("VITE_AWS_REGION", "us-east-1");
// Mock XMLHttpRequest globally // Mock XMLHttpRequest globally
(global as unknown as { XMLHttpRequest: typeof MockXMLHttpRequest }).XMLHttpRequest = MockXMLHttpRequest; (
global as unknown as { XMLHttpRequest: typeof MockXMLHttpRequest }
).XMLHttpRequest = MockXMLHttpRequest;
}); });
afterEach(() => { afterEach(() => {
// Restore original XMLHttpRequest // Restore original XMLHttpRequest
(global as unknown as { XMLHttpRequest: typeof XMLHttpRequest }).XMLHttpRequest = originalXMLHttpRequest; (
global as unknown as { XMLHttpRequest: typeof XMLHttpRequest }
).XMLHttpRequest = originalXMLHttpRequest;
}); });
describe('getPublicImageUrl', () => { describe("getPublicImageUrl", () => {
it('should return empty string for null input', () => { it("should return empty string for null input", () => {
expect(getPublicImageUrl(null)).toBe(''); expect(getPublicImageUrl(null)).toBe("");
}); });
it('should return empty string for undefined input', () => { it("should return empty string for undefined input", () => {
expect(getPublicImageUrl(undefined)).toBe(''); expect(getPublicImageUrl(undefined)).toBe("");
}); });
it('should return empty string for empty string input', () => { it("should return empty string for empty string input", () => {
expect(getPublicImageUrl('')).toBe(''); expect(getPublicImageUrl("")).toBe("");
}); });
it('should return full S3 URL unchanged', () => { it("should return full S3 URL unchanged", () => {
const fullUrl = 'https://bucket.s3.us-east-1.amazonaws.com/items/uuid.jpg'; const fullUrl =
"https://bucket.s3.us-east-1.amazonaws.com/items/uuid.jpg";
expect(getPublicImageUrl(fullUrl)).toBe(fullUrl); expect(getPublicImageUrl(fullUrl)).toBe(fullUrl);
}); });
it('should construct S3 URL from key', () => { it("should construct S3 URL from key", () => {
const key = 'items/550e8400-e29b-41d4-a716-446655440000.jpg'; const key = "items/550e8400-e29b-41d4-a716-446655440000.jpg";
const expectedUrl = 'https://test-bucket.s3.us-east-1.amazonaws.com/items/550e8400-e29b-41d4-a716-446655440000.jpg'; const expectedUrl =
"https://test-bucket.s3.us-east-1.amazonaws.com/items/550e8400-e29b-41d4-a716-446655440000.jpg";
expect(getPublicImageUrl(key)).toBe(expectedUrl); expect(getPublicImageUrl(key)).toBe(expectedUrl);
}); });
it('should handle profiles folder', () => { it("should handle profiles folder", () => {
const key = 'profiles/550e8400-e29b-41d4-a716-446655440000.jpg'; const key = "profiles/550e8400-e29b-41d4-a716-446655440000.jpg";
expect(getPublicImageUrl(key)).toContain('profiles/'); expect(getPublicImageUrl(key)).toContain("profiles/");
}); });
it('should handle forum folder', () => { it("should handle forum folder", () => {
const key = 'forum/550e8400-e29b-41d4-a716-446655440000.jpg'; const key = "forum/550e8400-e29b-41d4-a716-446655440000.jpg";
expect(getPublicImageUrl(key)).toContain('forum/'); expect(getPublicImageUrl(key)).toContain("forum/");
}); });
}); });
describe('getPresignedUrl', () => { describe("getPresignedUrl", () => {
const mockFile = new File(['test content'], 'photo.jpg', { type: 'image/jpeg' }); const mockFile = new File(["test content"], "photo.jpg", {
type: "image/jpeg",
});
const mockResponse: PresignedUrlResponse = { const mockResponse: PresignedUrlResponse = {
uploadUrl: 'https://presigned-url.s3.amazonaws.com/items/uuid.jpg?signature=abc', uploadUrl:
key: 'items/550e8400-e29b-41d4-a716-446655440000.jpg', "https://presigned-url.s3.amazonaws.com/items/uuid.jpg?signature=abc",
key: "items/550e8400-e29b-41d4-a716-446655440000.jpg",
stagingKey: null, stagingKey: null,
publicUrl: 'https://bucket.s3.amazonaws.com/items/550e8400-e29b-41d4-a716-446655440000.jpg', publicUrl:
"https://bucket.s3.amazonaws.com/items/550e8400-e29b-41d4-a716-446655440000.jpg",
expiresAt: new Date().toISOString(), expiresAt: new Date().toISOString(),
}; };
it('should request presigned URL with correct parameters', async () => { it("should request presigned URL with correct parameters", async () => {
mockedApi.post.mockResolvedValue({ data: mockResponse }); mockedApi.post.mockResolvedValue({ data: mockResponse });
const result = await getPresignedUrl('item', mockFile); const result = await getPresignedUrl("item", mockFile);
expect(mockedApi.post).toHaveBeenCalledWith('/upload/presign', { expect(mockedApi.post).toHaveBeenCalledWith("/upload/presign", {
uploadType: 'item', uploadType: "item",
contentType: 'image/jpeg', contentType: "image/jpeg",
fileName: 'photo.jpg', fileName: "photo.jpg",
fileSize: mockFile.size, fileSize: mockFile.size,
}); });
expect(result).toEqual(mockResponse); expect(result).toEqual(mockResponse);
}); });
it('should handle different upload types', async () => { it("should handle different upload types", async () => {
mockedApi.post.mockResolvedValue({ data: mockResponse }); mockedApi.post.mockResolvedValue({ data: mockResponse });
await getPresignedUrl('profile', mockFile); await getPresignedUrl("profile", mockFile);
expect(mockedApi.post).toHaveBeenCalledWith('/upload/presign', expect.objectContaining({ expect(mockedApi.post).toHaveBeenCalledWith(
uploadType: 'profile', "/upload/presign",
})); expect.objectContaining({
uploadType: "profile",
}),
);
await getPresignedUrl('message', mockFile); await getPresignedUrl("message", mockFile);
expect(mockedApi.post).toHaveBeenCalledWith('/upload/presign', expect.objectContaining({ expect(mockedApi.post).toHaveBeenCalledWith(
uploadType: 'message', "/upload/presign",
})); expect.objectContaining({
uploadType: "message",
}),
);
await getPresignedUrl('forum', mockFile); await getPresignedUrl("forum", mockFile);
expect(mockedApi.post).toHaveBeenCalledWith('/upload/presign', expect.objectContaining({ expect(mockedApi.post).toHaveBeenCalledWith(
uploadType: 'forum', "/upload/presign",
})); expect.objectContaining({
uploadType: "forum",
}),
);
await getPresignedUrl('condition-check', mockFile); await getPresignedUrl("condition-check", mockFile);
expect(mockedApi.post).toHaveBeenCalledWith('/upload/presign', expect.objectContaining({ expect(mockedApi.post).toHaveBeenCalledWith(
uploadType: 'condition-check', "/upload/presign",
})); expect.objectContaining({
uploadType: "condition-check",
}),
);
}); });
it('should propagate API errors', async () => { it("should propagate API errors", async () => {
const error = new Error('API error'); const error = new Error("API error");
mockedApi.post.mockRejectedValue(error); mockedApi.post.mockRejectedValue(error);
await expect(getPresignedUrl('item', mockFile)).rejects.toThrow('API error'); await expect(getPresignedUrl("item", mockFile)).rejects.toThrow(
"API error",
);
}); });
}); });
describe('getPresignedUrls', () => { describe("getPresignedUrls", () => {
const mockFiles = [ const mockFiles = [
new File(['test1'], 'photo1.jpg', { type: 'image/jpeg' }), new File(["test1"], "photo1.jpg", { type: "image/jpeg" }),
new File(['test2'], 'photo2.png', { type: 'image/png' }), new File(["test2"], "photo2.png", { type: "image/png" }),
]; ];
const mockResponses: PresignedUrlResponse[] = [ const mockResponses: PresignedUrlResponse[] = [
{ {
uploadUrl: 'https://presigned-url1.s3.amazonaws.com', uploadUrl: "https://presigned-url1.s3.amazonaws.com",
key: 'items/uuid1.jpg', key: "items/uuid1.jpg",
stagingKey: null, stagingKey: null,
publicUrl: 'https://bucket.s3.amazonaws.com/items/uuid1.jpg', publicUrl: "https://bucket.s3.amazonaws.com/items/uuid1.jpg",
expiresAt: new Date().toISOString(), expiresAt: new Date().toISOString(),
}, },
{ {
uploadUrl: 'https://presigned-url2.s3.amazonaws.com', uploadUrl: "https://presigned-url2.s3.amazonaws.com",
key: 'items/uuid2.png', key: "items/uuid2.png",
stagingKey: null, stagingKey: null,
publicUrl: 'https://bucket.s3.amazonaws.com/items/uuid2.png', publicUrl: "https://bucket.s3.amazonaws.com/items/uuid2.png",
expiresAt: new Date().toISOString(), expiresAt: new Date().toISOString(),
}, },
]; ];
it('should request batch presigned URLs', async () => { it("should request batch presigned URLs", async () => {
mockedApi.post.mockResolvedValue({ data: { uploads: mockResponses, baseKey: 'base-key' } }); mockedApi.post.mockResolvedValue({
data: { uploads: mockResponses, baseKey: "base-key" },
});
const result = await getPresignedUrls('item', mockFiles); const result = await getPresignedUrls("item", mockFiles);
expect(mockedApi.post).toHaveBeenCalledWith('/upload/presign-batch', { expect(mockedApi.post).toHaveBeenCalledWith("/upload/presign-batch", {
uploadType: 'item', uploadType: "item",
files: [ files: [
{ contentType: 'image/jpeg', fileName: 'photo1.jpg', fileSize: mockFiles[0].size }, {
{ contentType: 'image/png', fileName: 'photo2.png', fileSize: mockFiles[1].size }, contentType: "image/jpeg",
fileName: "photo1.jpg",
fileSize: mockFiles[0].size,
},
{
contentType: "image/png",
fileName: "photo2.png",
fileSize: mockFiles[1].size,
},
], ],
}); });
expect(result).toEqual({ uploads: mockResponses, baseKey: 'base-key' }); expect(result).toEqual({ uploads: mockResponses, baseKey: "base-key" });
}); });
it('should handle empty file array', async () => { it("should handle empty file array", async () => {
mockedApi.post.mockResolvedValue({ data: { uploads: [], baseKey: undefined } }); mockedApi.post.mockResolvedValue({
data: { uploads: [], baseKey: undefined },
});
const result = await getPresignedUrls('item', []); const result = await getPresignedUrls("item", []);
expect(result).toEqual({ uploads: [], baseKey: undefined }); expect(result).toEqual({ uploads: [], baseKey: undefined });
}); });
}); });
describe('uploadToS3', () => { describe("uploadToS3", () => {
const mockFile = new File(['test content'], 'photo.jpg', { type: 'image/jpeg' }); const mockFile = new File(["test content"], "photo.jpg", {
const mockUploadUrl = 'https://presigned-url.s3.amazonaws.com/items/uuid.jpg?signature=abc'; type: "image/jpeg",
});
const mockUploadUrl =
"https://presigned-url.s3.amazonaws.com/items/uuid.jpg?signature=abc";
it('should upload file successfully', async () => { it("should upload file successfully", async () => {
await uploadToS3(mockFile, mockUploadUrl); await uploadToS3(mockFile, mockUploadUrl);
const instance = MockXMLHttpRequest.getLastInstance(); const instance = MockXMLHttpRequest.getLastInstance();
expect(instance.getMethod()).toBe('PUT'); expect(instance.getMethod()).toBe("PUT");
expect(instance.getUrl()).toBe(mockUploadUrl); expect(instance.getUrl()).toBe(mockUploadUrl);
expect(instance.getHeaders()['Content-Type']).toBe('image/jpeg'); expect(instance.getHeaders()["Content-Type"]).toBe("image/jpeg");
}); });
it('should call onProgress callback during upload', async () => { it("should call onProgress callback during upload", async () => {
const onProgress = vi.fn(); const onProgress = vi.fn();
await uploadToS3(mockFile, mockUploadUrl, { onProgress }); await uploadToS3(mockFile, mockUploadUrl, { onProgress });
@@ -269,37 +324,37 @@ describe('Upload Service', () => {
expect(onProgress).toHaveBeenCalledWith(expect.any(Number)); expect(onProgress).toHaveBeenCalledWith(expect.any(Number));
}); });
it('should export uploadToS3 function with correct signature', () => { it("should export uploadToS3 function with correct signature", () => {
expect(typeof uploadToS3).toBe('function'); expect(typeof uploadToS3).toBe("function");
// Function accepts file, url, and optional options // Function accepts file, url, and optional options
expect(uploadToS3.length).toBeGreaterThanOrEqual(2); expect(uploadToS3.length).toBeGreaterThanOrEqual(2);
}); });
it('should set correct content-type header', async () => { it("should set correct content-type header", async () => {
const pngFile = new File(['test'], 'image.png', { type: 'image/png' }); const pngFile = new File(["test"], "image.png", { type: "image/png" });
await uploadToS3(pngFile, mockUploadUrl); await uploadToS3(pngFile, mockUploadUrl);
const instance = MockXMLHttpRequest.getLastInstance(); const instance = MockXMLHttpRequest.getLastInstance();
expect(instance.getHeaders()['Content-Type']).toBe('image/png'); expect(instance.getHeaders()["Content-Type"]).toBe("image/png");
}); });
}); });
describe('confirmUploads', () => { describe("confirmUploads", () => {
it('should confirm uploaded keys', async () => { it("should confirm uploaded keys", async () => {
const keys = ['items/uuid1.jpg', 'items/uuid2.jpg']; const keys = ["items/uuid1.jpg", "items/uuid2.jpg"];
const mockResponse = { confirmed: keys, total: 2 }; const mockResponse = { confirmed: keys, total: 2 };
mockedApi.post.mockResolvedValue({ data: mockResponse }); mockedApi.post.mockResolvedValue({ data: mockResponse });
const result = await confirmUploads(keys); const result = await confirmUploads(keys);
expect(mockedApi.post).toHaveBeenCalledWith('/upload/confirm', { keys }); expect(mockedApi.post).toHaveBeenCalledWith("/upload/confirm", { keys });
expect(result).toEqual(mockResponse); expect(result).toEqual(mockResponse);
}); });
it('should handle partial confirmation', async () => { it("should handle partial confirmation", async () => {
const keys = ['items/uuid1.jpg', 'items/uuid2.jpg']; const keys = ["items/uuid1.jpg", "items/uuid2.jpg"];
const mockResponse = { confirmed: ['items/uuid1.jpg'], total: 2 }; const mockResponse = { confirmed: ["items/uuid1.jpg"], total: 2 };
mockedApi.post.mockResolvedValue({ data: mockResponse }); mockedApi.post.mockResolvedValue({ data: mockResponse });
@@ -310,17 +365,19 @@ describe('Upload Service', () => {
}); });
}); });
describe('uploadFile', () => { describe("uploadFile", () => {
const mockFile = new File(['test content'], 'photo.jpg', { type: 'image/jpeg' }); const mockFile = new File(["test content"], "photo.jpg", {
type: "image/jpeg",
});
const presignResponse: PresignedUrlResponse = { const presignResponse: PresignedUrlResponse = {
uploadUrl: 'https://presigned.s3.amazonaws.com/items/uuid.jpg', uploadUrl: "https://presigned.s3.amazonaws.com/items/uuid.jpg",
key: 'items/uuid.jpg', key: "items/uuid.jpg",
stagingKey: null, stagingKey: null,
publicUrl: 'https://bucket.s3.amazonaws.com/items/uuid.jpg', publicUrl: "https://bucket.s3.amazonaws.com/items/uuid.jpg",
expiresAt: new Date().toISOString(), expiresAt: new Date().toISOString(),
}; };
it('should complete full upload flow successfully', async () => { it("should complete full upload flow successfully", async () => {
// Mock presign response // Mock presign response
mockedApi.post.mockResolvedValueOnce({ data: presignResponse }); mockedApi.post.mockResolvedValueOnce({ data: presignResponse });
// Mock confirm response // Mock confirm response
@@ -328,7 +385,7 @@ describe('Upload Service', () => {
data: { confirmed: [presignResponse.key], total: 1 }, data: { confirmed: [presignResponse.key], total: 1 },
}); });
const result = await uploadFile('item', mockFile); const result = await uploadFile("item", mockFile);
expect(result).toEqual({ expect(result).toEqual({
key: presignResponse.key, key: presignResponse.key,
@@ -336,30 +393,32 @@ describe('Upload Service', () => {
}); });
// Verify presign was called // Verify presign was called
expect(mockedApi.post).toHaveBeenCalledWith('/upload/presign', { expect(mockedApi.post).toHaveBeenCalledWith("/upload/presign", {
uploadType: 'item', uploadType: "item",
contentType: 'image/jpeg', contentType: "image/jpeg",
fileName: 'photo.jpg', fileName: "photo.jpg",
fileSize: mockFile.size, fileSize: mockFile.size,
}); });
// Verify confirm was called // Verify confirm was called
expect(mockedApi.post).toHaveBeenCalledWith('/upload/confirm', { expect(mockedApi.post).toHaveBeenCalledWith("/upload/confirm", {
keys: [presignResponse.key], keys: [presignResponse.key],
}); });
}); });
it('should throw error when upload verification fails', async () => { it("should throw error when upload verification fails", async () => {
mockedApi.post.mockResolvedValueOnce({ data: presignResponse }); mockedApi.post.mockResolvedValueOnce({ data: presignResponse });
// Mock confirm returning empty confirmed array // Mock confirm returning empty confirmed array
mockedApi.post.mockResolvedValueOnce({ mockedApi.post.mockResolvedValueOnce({
data: { confirmed: [], total: 1 }, data: { confirmed: [], total: 1 },
}); });
await expect(uploadFile('item', mockFile)).rejects.toThrow('Upload verification failed'); await expect(uploadFile("item", mockFile)).rejects.toThrow(
"Upload verification failed",
);
}); });
it('should pass onProgress to uploadToS3', async () => { it("should pass onProgress to uploadToS3", async () => {
const onProgress = vi.fn(); const onProgress = vi.fn();
mockedApi.post.mockResolvedValueOnce({ data: presignResponse }); mockedApi.post.mockResolvedValueOnce({ data: presignResponse });
@@ -367,16 +426,16 @@ describe('Upload Service', () => {
data: { confirmed: [presignResponse.key], total: 1 }, data: { confirmed: [presignResponse.key], total: 1 },
}); });
await uploadFile('item', mockFile, { onProgress }); await uploadFile("item", mockFile, { onProgress });
// onProgress should have been called during XHR upload // onProgress should have been called during XHR upload
expect(onProgress).toHaveBeenCalled(); expect(onProgress).toHaveBeenCalled();
}); });
it('should work with different upload types', async () => { it("should work with different upload types", async () => {
const messagePresignResponse = { const messagePresignResponse = {
...presignResponse, ...presignResponse,
key: 'messages/uuid.jpg', key: "messages/uuid.jpg",
publicUrl: null, // Messages are private publicUrl: null, // Messages are private
}; };
@@ -385,49 +444,54 @@ describe('Upload Service', () => {
data: { confirmed: [messagePresignResponse.key], total: 1 }, data: { confirmed: [messagePresignResponse.key], total: 1 },
}); });
const result = await uploadFile('message', mockFile); const result = await uploadFile("message", mockFile);
expect(result.key).toBe('messages/uuid.jpg'); expect(result.key).toBe("messages/uuid.jpg");
expect(mockedApi.post).toHaveBeenCalledWith('/upload/presign', expect.objectContaining({ expect(mockedApi.post).toHaveBeenCalledWith(
uploadType: 'message', "/upload/presign",
})); expect.objectContaining({
uploadType: "message",
}),
);
}); });
}); });
// Note: uploadFiles function was removed from uploadService and replaced with uploadImagesWithVariants describe("getSignedUrl", () => {
// Tests for batch uploads would need to be updated to test the new function it("should request signed URL for private content", async () => {
const key = "messages/uuid.jpg";
describe('getSignedUrl', () => { const signedUrl =
it('should request signed URL for private content', async () => { "https://bucket.s3.amazonaws.com/messages/uuid.jpg?signature=abc";
const key = 'messages/uuid.jpg';
const signedUrl = 'https://bucket.s3.amazonaws.com/messages/uuid.jpg?signature=abc';
mockedApi.get.mockResolvedValue({ data: { url: signedUrl } }); mockedApi.get.mockResolvedValue({ data: { url: signedUrl } });
const result = await getSignedUrl(key); const result = await getSignedUrl(key);
expect(mockedApi.get).toHaveBeenCalledWith(`/upload/signed-url/${encodeURIComponent(key)}`); expect(mockedApi.get).toHaveBeenCalledWith(
`/upload/signed-url/${encodeURIComponent(key)}`,
);
expect(result).toBe(signedUrl); expect(result).toBe(signedUrl);
}); });
it('should encode key in URL', async () => { it("should encode key in URL", async () => {
const key = 'condition-checks/uuid with spaces.jpg'; const key = "condition-checks/uuid with spaces.jpg";
const signedUrl = 'https://bucket.s3.amazonaws.com/signed'; const signedUrl = "https://bucket.s3.amazonaws.com/signed";
mockedApi.get.mockResolvedValue({ data: { url: signedUrl } }); mockedApi.get.mockResolvedValue({ data: { url: signedUrl } });
await getSignedUrl(key); await getSignedUrl(key);
expect(mockedApi.get).toHaveBeenCalledWith( expect(mockedApi.get).toHaveBeenCalledWith(
`/upload/signed-url/${encodeURIComponent(key)}` `/upload/signed-url/${encodeURIComponent(key)}`,
); );
}); });
it('should propagate API errors', async () => { it("should propagate API errors", async () => {
const error = new Error('Unauthorized'); const error = new Error("Unauthorized");
mockedApi.get.mockRejectedValue(error); mockedApi.get.mockRejectedValue(error);
await expect(getSignedUrl('messages/uuid.jpg')).rejects.toThrow('Unauthorized'); await expect(getSignedUrl("messages/uuid.jpg")).rejects.toThrow(
"Unauthorized",
);
}); });
}); });
}); });

View File

@@ -34,7 +34,7 @@ const AlphaGate: React.FC = () => {
const response = await axios.post( const response = await axios.post(
`${API_URL}/alpha/validate-code`, `${API_URL}/alpha/validate-code`,
{ code: fullCode }, { code: fullCode },
{ withCredentials: true } { withCredentials: true },
); );
if (response.data.success) { if (response.data.success) {
@@ -115,7 +115,7 @@ const AlphaGate: React.FC = () => {
<p className="text-center text-muted small mb-0"> <p className="text-center text-muted small mb-0">
Have an alpha code? Get started below! <br></br> Want to join?{" "} Have an alpha code? Get started below! <br></br> Want to join?{" "}
<a <a
href="mailto:support@villageshare.app?subject=Alpha Access Request" href="mailto:community-support@village-share.com?subject=Alpha Access Request"
className="text-decoration-none" className="text-decoration-none"
style={{ color: "#667eea" }} style={{ color: "#667eea" }}
> >

View File

@@ -77,9 +77,13 @@ const Owning: React.FC = () => {
const [itemToDelete, setItemToDelete] = useState<Item | null>(null); const [itemToDelete, setItemToDelete] = useState<Item | null>(null);
const [showPaymentFailedModal, setShowPaymentFailedModal] = useState(false); const [showPaymentFailedModal, setShowPaymentFailedModal] = useState(false);
const [paymentFailedError, setPaymentFailedError] = useState<any>(null); const [paymentFailedError, setPaymentFailedError] = useState<any>(null);
const [paymentFailedRental, setPaymentFailedRental] = useState<Rental | null>(null); const [paymentFailedRental, setPaymentFailedRental] = useState<Rental | null>(
null,
);
const [showAuthRequiredModal, setShowAuthRequiredModal] = useState(false); const [showAuthRequiredModal, setShowAuthRequiredModal] = useState(false);
const [authRequiredRental, setAuthRequiredRental] = useState<Rental | null>(null); const [authRequiredRental, setAuthRequiredRental] = useState<Rental | null>(
null,
);
useEffect(() => { useEffect(() => {
fetchListings(); fetchListings();
@@ -89,7 +93,7 @@ const Owning: React.FC = () => {
useEffect(() => { useEffect(() => {
// Only fetch condition checks for rentals that will be displayed (pending/confirmed/active) // Only fetch condition checks for rentals that will be displayed (pending/confirmed/active)
const displayedRentals = ownerRentals.filter((r) => const displayedRentals = ownerRentals.filter((r) =>
["pending", "confirmed", "active"].includes(r.displayStatus || r.status) ["pending", "confirmed", "active"].includes(r.displayStatus || r.status),
); );
if (displayedRentals.length > 0) { if (displayedRentals.length > 0) {
const rentalIds = displayedRentals.map((r) => r.id); const rentalIds = displayedRentals.map((r) => r.id);
@@ -111,7 +115,7 @@ const Owning: React.FC = () => {
// Filter items to only show ones owned by current user // Filter items to only show ones owned by current user
const myItems = response.data.items.filter( const myItems = response.data.items.filter(
(item: Item) => item.ownerId === user.id (item: Item) => item.ownerId === user.id,
); );
setListings(myItems); setListings(myItems);
} catch (err: any) { } catch (err: any) {
@@ -152,8 +156,8 @@ const Owning: React.FC = () => {
}); });
setListings( setListings(
listings.map((i) => listings.map((i) =>
i.id === item.id ? { ...i, isAvailable: !i.isAvailable } : i i.id === item.id ? { ...i, isAvailable: !i.isAvailable } : i,
) ),
); );
} catch (err: any) { } catch (err: any) {
alert("Failed to update availability"); alert("Failed to update availability");
@@ -189,7 +193,8 @@ const Owning: React.FC = () => {
return; return;
} }
const rentalIds = rentalsToFetch.map((r) => r.id); const rentalIds = rentalsToFetch.map((r) => r.id);
const response = await conditionCheckAPI.getBatchConditionChecks(rentalIds); const response =
await conditionCheckAPI.getBatchConditionChecks(rentalIds);
setConditionChecks(response.data.conditionChecks || []); setConditionChecks(response.data.conditionChecks || []);
} catch (err) { } catch (err) {
console.error("Failed to fetch condition checks:", err); console.error("Failed to fetch condition checks:", err);
@@ -203,7 +208,7 @@ const Owning: React.FC = () => {
setIsProcessingPayment(rentalId); setIsProcessingPayment(rentalId);
const response = await rentalAPI.updateRentalStatus( const response = await rentalAPI.updateRentalStatus(
rentalId, rentalId,
"confirmed" "confirmed",
); );
// Check if payment processing was successful // Check if payment processing was successful
@@ -216,7 +221,6 @@ const Owning: React.FC = () => {
} }
fetchOwnerRentals(); fetchOwnerRentals();
// Note: fetchAvailableChecks() removed - it will be triggered via ownerRentals useEffect
// Notify Navbar to update pending count // Notify Navbar to update pending count
window.dispatchEvent(new CustomEvent("rentalStatusChanged")); window.dispatchEvent(new CustomEvent("rentalStatusChanged"));
@@ -246,7 +250,7 @@ const Owning: React.FC = () => {
alert( alert(
err.response?.data?.error || err.response?.data?.error ||
err.response?.data?.details || err.response?.data?.details ||
"Failed to accept rental request" "Failed to accept rental request",
); );
} }
} finally { } finally {
@@ -263,8 +267,8 @@ const Owning: React.FC = () => {
// Update the rental in the owner rentals list // Update the rental in the owner rentals list
setOwnerRentals((prev) => setOwnerRentals((prev) =>
prev.map((rental) => prev.map((rental) =>
rental.id === updatedRental.id ? updatedRental : rental rental.id === updatedRental.id ? updatedRental : rental,
) ),
); );
setShowDeclineModal(false); setShowDeclineModal(false);
setRentalToDecline(null); setRentalToDecline(null);
@@ -279,8 +283,8 @@ const Owning: React.FC = () => {
// Update the rental in the list // Update the rental in the list
setOwnerRentals((prev) => setOwnerRentals((prev) =>
prev.map((rental) => prev.map((rental) =>
rental.id === updatedRental.id ? updatedRental : rental rental.id === updatedRental.id ? updatedRental : rental,
) ),
); );
// Close the return status modal // Close the return status modal
@@ -306,8 +310,8 @@ const Owning: React.FC = () => {
// Update the rental in the owner rentals list // Update the rental in the owner rentals list
setOwnerRentals((prev) => setOwnerRentals((prev) =>
prev.map((rental) => prev.map((rental) =>
rental.id === updatedRental.id ? updatedRental : rental rental.id === updatedRental.id ? updatedRental : rental,
) ),
); );
setShowCancelModal(false); setShowCancelModal(false);
setRentalToCancel(null); setRentalToCancel(null);
@@ -321,7 +325,7 @@ const Owning: React.FC = () => {
const handleConditionCheckSuccess = () => { const handleConditionCheckSuccess = () => {
// Refetch condition checks for displayed rentals // Refetch condition checks for displayed rentals
const displayedRentals = ownerRentals.filter((r) => const displayedRentals = ownerRentals.filter((r) =>
["pending", "confirmed", "active"].includes(r.displayStatus || r.status) ["pending", "confirmed", "active"].includes(r.displayStatus || r.status),
); );
const rentalIds = displayedRentals.map((r) => r.id); const rentalIds = displayedRentals.map((r) => r.id);
fetchAvailableChecks(rentalIds); fetchAvailableChecks(rentalIds);
@@ -337,7 +341,7 @@ const Owning: React.FC = () => {
if (!Array.isArray(availableChecks)) return []; if (!Array.isArray(availableChecks)) return [];
return availableChecks.filter( return availableChecks.filter(
(check) => (check) =>
check.rentalId === rentalId && check.checkType === "pre_rental_owner" // Only pre-rental; post-rental is in return modal check.rentalId === rentalId && check.checkType === "pre_rental_owner", // Only pre-rental; post-rental is in return modal
); );
}; };
@@ -349,7 +353,9 @@ const Owning: React.FC = () => {
// Filter owner rentals - exclude cancelled (shown in Rental History) // Filter owner rentals - exclude cancelled (shown in Rental History)
// Use displayStatus for filtering/sorting as it includes computed "active" status // Use displayStatus for filtering/sorting as it includes computed "active" status
const allOwnerRentals = ownerRentals const allOwnerRentals = ownerRentals
.filter((r) => ["pending", "confirmed", "active"].includes(r.displayStatus || r.status)) .filter((r) =>
["pending", "confirmed", "active"].includes(r.displayStatus || r.status),
)
.sort((a, b) => { .sort((a, b) => {
const statusOrder = { pending: 0, confirmed: 1, active: 2 }; const statusOrder = { pending: 0, confirmed: 1, active: 2 };
const aStatus = a.displayStatus || a.status; const aStatus = a.displayStatus || a.status;
@@ -396,14 +402,20 @@ const Owning: React.FC = () => {
{rental.item?.imageFilenames && {rental.item?.imageFilenames &&
rental.item.imageFilenames[0] && ( rental.item.imageFilenames[0] && (
<img <img
src={getImageUrl(rental.item.imageFilenames[0], 'thumbnail')} src={getImageUrl(
rental.item.imageFilenames[0],
"thumbnail",
)}
className="card-img-top" className="card-img-top"
alt={rental.item.name} alt={rental.item.name}
onError={(e) => { onError={(e) => {
const target = e.currentTarget; const target = e.currentTarget;
if (!target.dataset.fallback && rental.item) { if (!target.dataset.fallback && rental.item) {
target.dataset.fallback = 'true'; target.dataset.fallback = "true";
target.src = getImageUrl(rental.item.imageFilenames[0], 'original'); target.src = getImageUrl(
rental.item.imageFilenames[0],
"original",
);
} }
}} }}
style={{ style={{
@@ -435,14 +447,18 @@ const Owning: React.FC = () => {
className={`badge ${ className={`badge ${
(rental.displayStatus || rental.status) === "active" (rental.displayStatus || rental.status) === "active"
? "bg-success" ? "bg-success"
: (rental.displayStatus || rental.status) === "pending" : (rental.displayStatus || rental.status) ===
? "bg-warning" "pending"
: (rental.displayStatus || rental.status) === "confirmed" ? "bg-warning"
? "bg-info" : (rental.displayStatus || rental.status) ===
: "bg-danger" "confirmed"
? "bg-info"
: "bg-danger"
}`} }`}
> >
{(rental.displayStatus || rental.status).charAt(0).toUpperCase() + {(rental.displayStatus || rental.status)
.charAt(0)
.toUpperCase() +
(rental.displayStatus || rental.status).slice(1)} (rental.displayStatus || rental.status).slice(1)}
</span> </span>
</div> </div>
@@ -478,7 +494,7 @@ const Owning: React.FC = () => {
<small className="d-block text-muted mt-1"> <small className="d-block text-muted mt-1">
Processed:{" "} Processed:{" "}
{new Date( {new Date(
rental.refundProcessedAt rental.refundProcessedAt,
).toLocaleDateString()} ).toLocaleDateString()}
</small> </small>
)} )}
@@ -556,7 +572,8 @@ const Owning: React.FC = () => {
</button> </button>
</> </>
)} )}
{(rental.displayStatus || rental.status) === "confirmed" && ( {(rental.displayStatus || rental.status) ===
"confirmed" && (
<button <button
className="btn btn-sm btn-outline-danger" className="btn btn-sm btn-outline-danger"
onClick={() => handleCancelClick(rental)} onClick={() => handleCancelClick(rental)}
@@ -564,7 +581,8 @@ const Owning: React.FC = () => {
Cancel Cancel
</button> </button>
)} )}
{(rental.displayStatus || rental.status) === "active" && ( {(rental.displayStatus || rental.status) ===
"active" && (
<button <button
className="btn btn-sm btn-success" className="btn btn-sm btn-success"
onClick={() => handleCompleteClick(rental)} onClick={() => handleCompleteClick(rental)}
@@ -587,17 +605,17 @@ const Owning: React.FC = () => {
{check.checkType === "pre_rental_owner" {check.checkType === "pre_rental_owner"
? "Pre-Rental Condition" ? "Pre-Rental Condition"
: check.checkType === "rental_start_renter" : check.checkType === "rental_start_renter"
? "Rental Start Condition" ? "Rental Start Condition"
: check.checkType === "rental_end_renter" : check.checkType === "rental_end_renter"
? "Rental End Condition" ? "Rental End Condition"
: "Post-Rental Condition"} : "Post-Rental Condition"}
<small className="text-muted ms-2"> <small className="text-muted ms-2">
{new Date( {new Date(
check.createdAt check.createdAt,
).toLocaleDateString()} ).toLocaleDateString()}
</small> </small>
</button> </button>
) ),
)} )}
</div> </div>
)} )}
@@ -660,14 +678,17 @@ const Owning: React.FC = () => {
> >
{item.imageFilenames && item.imageFilenames[0] && ( {item.imageFilenames && item.imageFilenames[0] && (
<img <img
src={getImageUrl(item.imageFilenames[0], 'thumbnail')} src={getImageUrl(item.imageFilenames[0], "thumbnail")}
className="card-img-top" className="card-img-top"
alt={item.name} alt={item.name}
onError={(e) => { onError={(e) => {
const target = e.currentTarget; const target = e.currentTarget;
if (!target.dataset.fallback) { if (!target.dataset.fallback) {
target.dataset.fallback = 'true'; target.dataset.fallback = "true";
target.src = getImageUrl(item.imageFilenames[0], 'original'); target.src = getImageUrl(
item.imageFilenames[0],
"original",
);
} }
}} }}
style={{ style={{

View File

@@ -15,7 +15,7 @@ let failedQueue: Array<{
const processQueue = ( const processQueue = (
error: AxiosError | null, error: AxiosError | null,
token: string | null = null token: string | null = null,
) => { ) => {
failedQueue.forEach((prom) => { failedQueue.forEach((prom) => {
if (error) { if (error) {
@@ -95,7 +95,7 @@ api.interceptors.response.use(
methods: errorData.methods, methods: errorData.methods,
originalRequest, originalRequest,
}, },
}) }),
); );
return Promise.reject(error); return Promise.reject(error);
} }
@@ -128,7 +128,6 @@ api.interceptors.response.use(
const errorData = error.response?.data as any; const errorData = error.response?.data as any;
// Try to refresh for token errors // Try to refresh for token errors
// Note: We can't check refresh token from JS (httpOnly cookies)
// The backend will determine if refresh is possible // The backend will determine if refresh is possible
if ( if (
(errorData?.code === "TOKEN_EXPIRED" || (errorData?.code === "TOKEN_EXPIRED" ||
@@ -167,7 +166,7 @@ api.interceptors.response.use(
} }
return Promise.reject(error); return Promise.reject(error);
} },
); );
export const authAPI = { export const authAPI = {
@@ -279,7 +278,7 @@ export const rentalAPI = {
// Return status marking // Return status marking
markReturn: ( markReturn: (
id: string, id: string,
data: { status: string; actualReturnDateTime?: string } data: { status: string; actualReturnDateTime?: string },
) => api.post(`/rentals/${id}/mark-return`, data), ) => api.post(`/rentals/${id}/mark-return`, data),
reportDamage: (id: string, data: any) => reportDamage: (id: string, data: any) =>
api.post(`/rentals/${id}/report-damage`, data), api.post(`/rentals/${id}/report-damage`, data),
@@ -338,7 +337,7 @@ export const forumAPI = {
content: string; content: string;
parentId?: string; parentId?: string;
imageFilenames?: string[]; imageFilenames?: string[];
} },
) => api.post(`/forum/posts/${postId}/comments`, data), ) => api.post(`/forum/posts/${postId}/comments`, data),
updateComment: (commentId: string, data: any) => updateComment: (commentId: string, data: any) =>
api.put(`/forum/comments/${commentId}`, data), api.put(`/forum/comments/${commentId}`, data),
@@ -388,7 +387,7 @@ export const mapsAPI = {
export const conditionCheckAPI = { export const conditionCheckAPI = {
submitConditionCheck: ( submitConditionCheck: (
rentalId: string, rentalId: string,
data: { checkType: string; imageFilenames: string[]; notes?: string } data: { checkType: string; imageFilenames: string[]; notes?: string },
) => api.post(`/condition-checks/${rentalId}`, data), ) => api.post(`/condition-checks/${rentalId}`, data),
getBatchConditionChecks: (rentalIds: string[]) => getBatchConditionChecks: (rentalIds: string[]) =>
api.get(`/condition-checks/batch`, { api.get(`/condition-checks/batch`, {

File diff suppressed because it is too large Load Diff

View File

@@ -5,7 +5,7 @@
"main": "index.js", "main": "index.js",
"dependencies": { "dependencies": {
"@aws-sdk/client-scheduler": "^3.896.0", "@aws-sdk/client-scheduler": "^3.896.0",
"@rentall/lambda-shared": "file:../shared" "@village-share/lambda-shared": "file:../shared"
}, },
"devDependencies": { "devDependencies": {
"dotenv": "^17.2.3", "dotenv": "^17.2.3",

View File

@@ -1,4 +1,4 @@
<!DOCTYPE html> <!doctype html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="utf-8" /> <meta charset="utf-8" />
@@ -34,8 +34,9 @@
min-width: 100%; min-width: 100%;
height: 100%; height: 100%;
background-color: #f8f9fa; background-color: #f8f9fa;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, font-family:
Oxygen, Ubuntu, Cantarell, sans-serif; -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu,
Cantarell, sans-serif;
line-height: 1.6; line-height: 1.6;
color: #212529; color: #212529;
} }
@@ -257,7 +258,8 @@
</p> </p>
<p> <p>
If you have any questions, please If you have any questions, please
<a href="mailto:support@villageshare.app">contact our support team</a <a href="mailto:community-support@village-share.com"
>contact our support team</a
>. >.
</p> </p>
</div> </div>

File diff suppressed because it is too large Load Diff

View File

@@ -5,7 +5,7 @@
"main": "index.js", "main": "index.js",
"dependencies": { "dependencies": {
"@aws-sdk/client-s3": "^3.400.0", "@aws-sdk/client-s3": "^3.400.0",
"@rentall/lambda-shared": "file:../shared", "@village-share/lambda-shared": "file:../shared",
"exif-reader": "^2.0.0", "exif-reader": "^2.0.0",
"sharp": "^0.33.0" "sharp": "^0.33.0"
}, },

View File

@@ -7,14 +7,15 @@
* Example: * Example:
* npm run local -- staging/items/test-image.jpg my-bucket * npm run local -- staging/items/test-image.jpg my-bucket
* *
* Note: Requires .env.dev file with DATABASE_URL and AWS credentials configured.
*/ */
const { handler } = require("./index"); const { handler } = require("./index");
async function main() { async function main() {
// Filter out dotenv config args from process.argv // Filter out dotenv config args from process.argv
const args = process.argv.slice(2).filter(arg => !arg.startsWith("dotenv_config_path")); const args = process.argv
.slice(2)
.filter((arg) => !arg.startsWith("dotenv_config_path"));
// Get staging key from command line args // Get staging key from command line args
const stagingKey = args[0] || "staging/items/test-image.jpg"; const stagingKey = args[0] || "staging/items/test-image.jpg";

File diff suppressed because it is too large Load Diff

View File

@@ -4,7 +4,7 @@
"description": "Lambda function to retry failed payouts via Stripe Connect", "description": "Lambda function to retry failed payouts via Stripe Connect",
"main": "index.js", "main": "index.js",
"dependencies": { "dependencies": {
"@rentall/lambda-shared": "file:../shared" "@village-share/lambda-shared": "file:../shared"
}, },
"devDependencies": { "devDependencies": {
"dotenv": "^16.4.5" "dotenv": "^16.4.5"

View File

@@ -1,5 +1,5 @@
/** /**
* Shared utilities for Rentall Lambda functions. * Shared utilities for Village Share Lambda functions.
*/ */
const db = require("./db/connection"); const db = require("./db/connection");

View File

@@ -1,11 +1,11 @@
{ {
"name": "@rentall/lambda-shared", "name": "@village-share/lambda-shared",
"version": "1.0.0", "version": "1.0.0",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "@rentall/lambda-shared", "name": "@village-share/lambda-shared",
"version": "1.0.0", "version": "1.0.0",
"dependencies": { "dependencies": {
"@aws-sdk/client-scheduler": "^3.896.0", "@aws-sdk/client-scheduler": "^3.896.0",
@@ -1216,40 +1216,6 @@
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/@emnapi/core": {
"version": "1.8.1",
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.8.1.tgz",
"integrity": "sha512-AvT9QFpxK0Zd8J0jopedNm+w/2fIzvtPKPjqyw9jwvBaReTTqPBk9Hixaz7KbjimP+QNz605/XnjFcDAL2pqBg==",
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"@emnapi/wasi-threads": "1.1.0",
"tslib": "^2.4.0"
}
},
"node_modules/@emnapi/runtime": {
"version": "1.8.1",
"resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.8.1.tgz",
"integrity": "sha512-mehfKSMWjjNol8659Z8KxEMrdSJDDot5SXMq00dM8BN4o+CLNXQ0xH2V7EchNHV4RmbZLmmPdEaXZc5H2FXmDg==",
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"tslib": "^2.4.0"
}
},
"node_modules/@emnapi/wasi-threads": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.1.0.tgz",
"integrity": "sha512-WI0DdZ8xFSbgMjR1sFsKABJ/C5OnRrjT06JXbZKexJGrDuPTzZdDYfFlsgcCXCyf+suG5QU2e/y1Wo2V/OapLQ==",
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"tslib": "^2.4.0"
}
},
"node_modules/@isaacs/cliui": { "node_modules/@isaacs/cliui": {
"version": "8.0.2", "version": "8.0.2",
"resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz", "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz",
@@ -1687,19 +1653,6 @@
"@jridgewell/sourcemap-codec": "^1.4.14" "@jridgewell/sourcemap-codec": "^1.4.14"
} }
}, },
"node_modules/@napi-rs/wasm-runtime": {
"version": "0.2.12",
"resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-0.2.12.tgz",
"integrity": "sha512-ZVWUcfwY4E/yPitQJl481FjFo3K22D6qF0DuFH6Y/nbnE11GY5uguDxZMGXPQ8WQ0128MXQD7TnfHyK4oWoIJQ==",
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"@emnapi/core": "^1.4.3",
"@emnapi/runtime": "^1.4.3",
"@tybys/wasm-util": "^0.10.0"
}
},
"node_modules/@pkgjs/parseargs": { "node_modules/@pkgjs/parseargs": {
"version": "0.11.0", "version": "0.11.0",
"resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz", "resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz",
@@ -2345,17 +2298,6 @@
"node": ">=18.0.0" "node": ">=18.0.0"
} }
}, },
"node_modules/@tybys/wasm-util": {
"version": "0.10.1",
"resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.1.tgz",
"integrity": "sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg==",
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"tslib": "^2.4.0"
}
},
"node_modules/@types/babel__core": { "node_modules/@types/babel__core": {
"version": "7.20.5", "version": "7.20.5",
"resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz",
@@ -2468,48 +2410,6 @@
"dev": true, "dev": true,
"license": "ISC" "license": "ISC"
}, },
"node_modules/@unrs/resolver-binding-android-arm-eabi": {
"version": "1.11.1",
"resolved": "https://registry.npmjs.org/@unrs/resolver-binding-android-arm-eabi/-/resolver-binding-android-arm-eabi-1.11.1.tgz",
"integrity": "sha512-ppLRUgHVaGRWUx0R0Ut06Mjo9gBaBkg3v/8AxusGLhsIotbBLuRk51rAzqLC8gq6NyyAojEXglNjzf6R948DNw==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
]
},
"node_modules/@unrs/resolver-binding-android-arm64": {
"version": "1.11.1",
"resolved": "https://registry.npmjs.org/@unrs/resolver-binding-android-arm64/-/resolver-binding-android-arm64-1.11.1.tgz",
"integrity": "sha512-lCxkVtb4wp1v+EoN+HjIG9cIIzPkX5OtM03pQYkG+U5O/wL53LC4QbIeazgiKqluGeVEeBlZahHalCaBvU1a2g==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
]
},
"node_modules/@unrs/resolver-binding-darwin-arm64": {
"version": "1.11.1",
"resolved": "https://registry.npmjs.org/@unrs/resolver-binding-darwin-arm64/-/resolver-binding-darwin-arm64-1.11.1.tgz",
"integrity": "sha512-gPVA1UjRu1Y/IsB/dQEsp2V1pm44Of6+LWvbLc9SDk1c2KhhDRDBUkQCYVWe6f26uJb3fOK8saWMgtX8IrMk3g==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
]
},
"node_modules/@unrs/resolver-binding-darwin-x64": { "node_modules/@unrs/resolver-binding-darwin-x64": {
"version": "1.11.1", "version": "1.11.1",
"resolved": "https://registry.npmjs.org/@unrs/resolver-binding-darwin-x64/-/resolver-binding-darwin-x64-1.11.1.tgz", "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-darwin-x64/-/resolver-binding-darwin-x64-1.11.1.tgz",
@@ -2524,219 +2424,6 @@
"darwin" "darwin"
] ]
}, },
"node_modules/@unrs/resolver-binding-freebsd-x64": {
"version": "1.11.1",
"resolved": "https://registry.npmjs.org/@unrs/resolver-binding-freebsd-x64/-/resolver-binding-freebsd-x64-1.11.1.tgz",
"integrity": "sha512-fqtGgak3zX4DCB6PFpsH5+Kmt/8CIi4Bry4rb1ho6Av2QHTREM+47y282Uqiu3ZRF5IQioJQ5qWRV6jduA+iGw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
]
},
"node_modules/@unrs/resolver-binding-linux-arm-gnueabihf": {
"version": "1.11.1",
"resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-arm-gnueabihf/-/resolver-binding-linux-arm-gnueabihf-1.11.1.tgz",
"integrity": "sha512-u92mvlcYtp9MRKmP+ZvMmtPN34+/3lMHlyMj7wXJDeXxuM0Vgzz0+PPJNsro1m3IZPYChIkn944wW8TYgGKFHw==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
]
},
"node_modules/@unrs/resolver-binding-linux-arm-musleabihf": {
"version": "1.11.1",
"resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-arm-musleabihf/-/resolver-binding-linux-arm-musleabihf-1.11.1.tgz",
"integrity": "sha512-cINaoY2z7LVCrfHkIcmvj7osTOtm6VVT16b5oQdS4beibX2SYBwgYLmqhBjA1t51CarSaBuX5YNsWLjsqfW5Cw==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
]
},
"node_modules/@unrs/resolver-binding-linux-arm64-gnu": {
"version": "1.11.1",
"resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-arm64-gnu/-/resolver-binding-linux-arm64-gnu-1.11.1.tgz",
"integrity": "sha512-34gw7PjDGB9JgePJEmhEqBhWvCiiWCuXsL9hYphDF7crW7UgI05gyBAi6MF58uGcMOiOqSJ2ybEeCvHcq0BCmQ==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
]
},
"node_modules/@unrs/resolver-binding-linux-arm64-musl": {
"version": "1.11.1",
"resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-arm64-musl/-/resolver-binding-linux-arm64-musl-1.11.1.tgz",
"integrity": "sha512-RyMIx6Uf53hhOtJDIamSbTskA99sPHS96wxVE/bJtePJJtpdKGXO1wY90oRdXuYOGOTuqjT8ACccMc4K6QmT3w==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
]
},
"node_modules/@unrs/resolver-binding-linux-ppc64-gnu": {
"version": "1.11.1",
"resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-ppc64-gnu/-/resolver-binding-linux-ppc64-gnu-1.11.1.tgz",
"integrity": "sha512-D8Vae74A4/a+mZH0FbOkFJL9DSK2R6TFPC9M+jCWYia/q2einCubX10pecpDiTmkJVUH+y8K3BZClycD8nCShA==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
]
},
"node_modules/@unrs/resolver-binding-linux-riscv64-gnu": {
"version": "1.11.1",
"resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-riscv64-gnu/-/resolver-binding-linux-riscv64-gnu-1.11.1.tgz",
"integrity": "sha512-frxL4OrzOWVVsOc96+V3aqTIQl1O2TjgExV4EKgRY09AJ9leZpEg8Ak9phadbuX0BA4k8U5qtvMSQQGGmaJqcQ==",
"cpu": [
"riscv64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
]
},
"node_modules/@unrs/resolver-binding-linux-riscv64-musl": {
"version": "1.11.1",
"resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-riscv64-musl/-/resolver-binding-linux-riscv64-musl-1.11.1.tgz",
"integrity": "sha512-mJ5vuDaIZ+l/acv01sHoXfpnyrNKOk/3aDoEdLO/Xtn9HuZlDD6jKxHlkN8ZhWyLJsRBxfv9GYM2utQ1SChKew==",
"cpu": [
"riscv64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
]
},
"node_modules/@unrs/resolver-binding-linux-s390x-gnu": {
"version": "1.11.1",
"resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-s390x-gnu/-/resolver-binding-linux-s390x-gnu-1.11.1.tgz",
"integrity": "sha512-kELo8ebBVtb9sA7rMe1Cph4QHreByhaZ2QEADd9NzIQsYNQpt9UkM9iqr2lhGr5afh885d/cB5QeTXSbZHTYPg==",
"cpu": [
"s390x"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
]
},
"node_modules/@unrs/resolver-binding-linux-x64-gnu": {
"version": "1.11.1",
"resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-x64-gnu/-/resolver-binding-linux-x64-gnu-1.11.1.tgz",
"integrity": "sha512-C3ZAHugKgovV5YvAMsxhq0gtXuwESUKc5MhEtjBpLoHPLYM+iuwSj3lflFwK3DPm68660rZ7G8BMcwSro7hD5w==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
]
},
"node_modules/@unrs/resolver-binding-linux-x64-musl": {
"version": "1.11.1",
"resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-x64-musl/-/resolver-binding-linux-x64-musl-1.11.1.tgz",
"integrity": "sha512-rV0YSoyhK2nZ4vEswT/QwqzqQXw5I6CjoaYMOX0TqBlWhojUf8P94mvI7nuJTeaCkkds3QE4+zS8Ko+GdXuZtA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
]
},
"node_modules/@unrs/resolver-binding-wasm32-wasi": {
"version": "1.11.1",
"resolved": "https://registry.npmjs.org/@unrs/resolver-binding-wasm32-wasi/-/resolver-binding-wasm32-wasi-1.11.1.tgz",
"integrity": "sha512-5u4RkfxJm+Ng7IWgkzi3qrFOvLvQYnPBmjmZQ8+szTK/b31fQCnleNl1GgEt7nIsZRIf5PLhPwT0WM+q45x/UQ==",
"cpu": [
"wasm32"
],
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"@napi-rs/wasm-runtime": "^0.2.11"
},
"engines": {
"node": ">=14.0.0"
}
},
"node_modules/@unrs/resolver-binding-win32-arm64-msvc": {
"version": "1.11.1",
"resolved": "https://registry.npmjs.org/@unrs/resolver-binding-win32-arm64-msvc/-/resolver-binding-win32-arm64-msvc-1.11.1.tgz",
"integrity": "sha512-nRcz5Il4ln0kMhfL8S3hLkxI85BXs3o8EYoattsJNdsX4YUU89iOkVn7g0VHSRxFuVMdM4Q1jEpIId1Ihim/Uw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
]
},
"node_modules/@unrs/resolver-binding-win32-ia32-msvc": {
"version": "1.11.1",
"resolved": "https://registry.npmjs.org/@unrs/resolver-binding-win32-ia32-msvc/-/resolver-binding-win32-ia32-msvc-1.11.1.tgz",
"integrity": "sha512-DCEI6t5i1NmAZp6pFonpD5m7i6aFrpofcp4LA2i8IIq60Jyo28hamKBxNrZcyOwVOZkgsRp9O2sXWBWP8MnvIQ==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
]
},
"node_modules/@unrs/resolver-binding-win32-x64-msvc": {
"version": "1.11.1",
"resolved": "https://registry.npmjs.org/@unrs/resolver-binding-win32-x64-msvc/-/resolver-binding-win32-x64-msvc-1.11.1.tgz",
"integrity": "sha512-lrW200hZdbfRtztbygyaq/6jP6AKE8qQN2KvPcJ+x7wiD038YtnYtZ82IMNJ69GJibV7bwL3y9FgK+5w/pYt6g==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
]
},
"node_modules/ansi-escapes": { "node_modules/ansi-escapes": {
"version": "4.3.2", "version": "4.3.2",
"resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz", "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz",

View File

@@ -1,7 +1,7 @@
{ {
"name": "@rentall/lambda-shared", "name": "@village-share/lambda-shared",
"version": "1.0.0", "version": "1.0.0",
"description": "Shared utilities for Rentall Lambda functions", "description": "Shared utilities for Village Share Lambda functions",
"main": "index.js", "main": "index.js",
"dependencies": { "dependencies": {
"@aws-sdk/client-ses": "^3.896.0", "@aws-sdk/client-ses": "^3.896.0",