text changes
This commit is contained in:
@@ -10,7 +10,7 @@ module.exports = {
|
||||
},
|
||||
|
||||
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", {
|
||||
type: Sequelize.ARRAY(Sequelize.STRING),
|
||||
defaultValue: [],
|
||||
|
||||
@@ -20,7 +20,7 @@ module.exports = {
|
||||
},
|
||||
|
||||
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([
|
||||
queryInterface.changeColumn("Users", "profileImage", {
|
||||
type: Sequelize.STRING,
|
||||
|
||||
@@ -11,7 +11,7 @@ module.exports = {
|
||||
|
||||
down: async (queryInterface, Sequelize) => {
|
||||
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.",
|
||||
);
|
||||
},
|
||||
|
||||
@@ -265,7 +265,7 @@ const User = sequelize.define(
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
User.prototype.comparePassword = async function (password) {
|
||||
@@ -457,7 +457,7 @@ User.prototype.unbanUser = async function () {
|
||||
bannedAt: null,
|
||||
bannedBy: 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
|
||||
User.prototype.storePendingTotpSecret = async function (
|
||||
encryptedSecret,
|
||||
encryptedSecretIv
|
||||
encryptedSecretIv,
|
||||
) {
|
||||
return this.update({
|
||||
twoFactorSetupPendingSecret: encryptedSecret,
|
||||
@@ -478,7 +478,7 @@ User.prototype.storePendingTotpSecret = async function (
|
||||
// Enable TOTP 2FA after verification
|
||||
User.prototype.enableTotp = async function (recoveryCodes) {
|
||||
const hashedCodes = await Promise.all(
|
||||
recoveryCodes.map((code) => bcrypt.hash(code, 12))
|
||||
recoveryCodes.map((code) => bcrypt.hash(code, 12)),
|
||||
);
|
||||
|
||||
// Store in structured format
|
||||
@@ -506,7 +506,7 @@ User.prototype.enableTotp = async function (recoveryCodes) {
|
||||
// Enable Email 2FA
|
||||
User.prototype.enableEmailTwoFactor = async function (recoveryCodes) {
|
||||
const hashedCodes = await Promise.all(
|
||||
recoveryCodes.map((code) => bcrypt.hash(code, 12))
|
||||
recoveryCodes.map((code) => bcrypt.hash(code, 12)),
|
||||
);
|
||||
|
||||
// Store in structured format
|
||||
@@ -563,7 +563,7 @@ User.prototype.verifyEmailOtp = function (inputCode) {
|
||||
return TwoFactorService.verifyEmailOtp(
|
||||
inputCode,
|
||||
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");
|
||||
recentCodes.unshift(codeHash);
|
||||
// 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
|
||||
@@ -615,18 +617,25 @@ User.prototype.verifyTotpCode = function (code) {
|
||||
if (this.hasUsedTotpCode(code)) {
|
||||
return false;
|
||||
}
|
||||
return TwoFactorService.verifyTotpCode(this.totpSecret, this.totpSecretIv, code);
|
||||
return TwoFactorService.verifyTotpCode(
|
||||
this.totpSecret,
|
||||
this.totpSecretIv,
|
||||
code,
|
||||
);
|
||||
};
|
||||
|
||||
// Verify pending TOTP code (during setup)
|
||||
User.prototype.verifyPendingTotpCode = function (code) {
|
||||
if (!this.twoFactorSetupPendingSecret || !this.twoFactorSetupPendingSecretIv) {
|
||||
if (
|
||||
!this.twoFactorSetupPendingSecret ||
|
||||
!this.twoFactorSetupPendingSecretIv
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
return TwoFactorService.verifyTotpCode(
|
||||
this.twoFactorSetupPendingSecret,
|
||||
this.twoFactorSetupPendingSecretIv,
|
||||
code
|
||||
code,
|
||||
);
|
||||
};
|
||||
|
||||
@@ -639,7 +648,7 @@ User.prototype.useRecoveryCode = async function (inputCode) {
|
||||
const recoveryData = JSON.parse(this.recoveryCodesHash);
|
||||
const { valid, index } = await TwoFactorService.verifyRecoveryCode(
|
||||
inputCode,
|
||||
recoveryData
|
||||
recoveryData,
|
||||
);
|
||||
|
||||
if (valid) {
|
||||
@@ -661,7 +670,8 @@ User.prototype.useRecoveryCode = async function (inputCode) {
|
||||
|
||||
return {
|
||||
valid,
|
||||
remainingCodes: TwoFactorService.getRemainingRecoveryCodesCount(recoveryData),
|
||||
remainingCodes:
|
||||
TwoFactorService.getRemainingRecoveryCodesCount(recoveryData),
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
@@ -269,11 +269,11 @@ router.post("/", authenticateToken, requireVerifiedEmail, async (req, res) => {
|
||||
totalAmount = RentalDurationCalculator.calculateRentalCost(
|
||||
rentalStartDateTime,
|
||||
rentalEndDateTime,
|
||||
item
|
||||
item,
|
||||
);
|
||||
|
||||
// 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
|
||||
// Here: existing rental [existingStart, existingEnd], new rental [rentalStartDateTime, rentalEndDateTime]
|
||||
// Overlap: existingStart < rentalEndDateTime AND rentalStartDateTime < existingEnd
|
||||
@@ -352,7 +352,7 @@ router.post("/", authenticateToken, requireVerifiedEmail, async (req, res) => {
|
||||
await emailServices.rentalFlow.sendRentalRequestEmail(
|
||||
rentalWithDetails.owner,
|
||||
rentalWithDetails.renter,
|
||||
rentalWithDetails
|
||||
rentalWithDetails,
|
||||
);
|
||||
const reqLogger = logger.withRequestId(req.id);
|
||||
reqLogger.info("Rental request notification sent to owner", {
|
||||
@@ -374,7 +374,7 @@ router.post("/", authenticateToken, requireVerifiedEmail, async (req, res) => {
|
||||
try {
|
||||
await emailServices.rentalFlow.sendRentalRequestConfirmationEmail(
|
||||
rentalWithDetails.renter,
|
||||
rentalWithDetails
|
||||
rentalWithDetails,
|
||||
);
|
||||
const reqLogger = logger.withRequestId(req.id);
|
||||
reqLogger.info("Rental request confirmation sent to renter", {
|
||||
@@ -474,7 +474,7 @@ router.put("/:id/status", authenticateToken, async (req, res) => {
|
||||
itemName: rental.item.name,
|
||||
renterId: rental.renterId,
|
||||
ownerId: rental.ownerId,
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// Check if 3DS authentication is required
|
||||
@@ -494,7 +494,7 @@ router.put("/:id/status", authenticateToken, async (req, res) => {
|
||||
itemName: rental.item.name,
|
||||
ownerName: rental.owner.firstName,
|
||||
amount: rental.totalAmount,
|
||||
}
|
||||
},
|
||||
);
|
||||
const reqLogger = logger.withRequestId(req.id);
|
||||
reqLogger.info("Authentication required email sent to renter", {
|
||||
@@ -503,15 +503,12 @@ router.put("/:id/status", authenticateToken, async (req, res) => {
|
||||
});
|
||||
} catch (emailError) {
|
||||
const reqLogger = logger.withRequestId(req.id);
|
||||
reqLogger.error(
|
||||
"Failed to send authentication required email",
|
||||
{
|
||||
reqLogger.error("Failed to send authentication required email", {
|
||||
error: emailError.message,
|
||||
stack: emailError.stack,
|
||||
rentalId: rental.id,
|
||||
renterId: rental.renterId,
|
||||
}
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
return res.status(402).json({
|
||||
@@ -557,17 +554,14 @@ router.put("/:id/status", authenticateToken, async (req, res) => {
|
||||
// Create condition check reminder schedules
|
||||
try {
|
||||
await EventBridgeSchedulerService.createConditionCheckSchedules(
|
||||
updatedRental
|
||||
updatedRental,
|
||||
);
|
||||
} catch (schedulerError) {
|
||||
const reqLogger = logger.withRequestId(req.id);
|
||||
reqLogger.error(
|
||||
"Failed to create condition check schedules",
|
||||
{
|
||||
reqLogger.error("Failed to create condition check schedules", {
|
||||
error: schedulerError.message,
|
||||
rentalId: updatedRental.id,
|
||||
}
|
||||
);
|
||||
});
|
||||
// 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(
|
||||
updatedRental.owner,
|
||||
updatedRental.renter,
|
||||
updatedRental
|
||||
updatedRental,
|
||||
);
|
||||
const reqLogger = logger.withRequestId(req.id);
|
||||
reqLogger.info("Rental approval confirmation sent to owner", {
|
||||
@@ -593,7 +587,7 @@ router.put("/:id/status", authenticateToken, async (req, res) => {
|
||||
stack: emailError.stack,
|
||||
rentalId: updatedRental.id,
|
||||
ownerId: updatedRental.ownerId,
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -616,7 +610,7 @@ router.put("/:id/status", authenticateToken, async (req, res) => {
|
||||
renterNotification,
|
||||
updatedRental,
|
||||
renter.firstName,
|
||||
true // isRenter = true to show payment receipt
|
||||
true, // isRenter = true to show payment receipt
|
||||
);
|
||||
const reqLogger = logger.withRequestId(req.id);
|
||||
reqLogger.info("Rental confirmation sent to renter", {
|
||||
@@ -633,7 +627,7 @@ router.put("/:id/status", authenticateToken, async (req, res) => {
|
||||
stack: emailError.stack,
|
||||
rentalId: updatedRental.id,
|
||||
renterId: updatedRental.renterId,
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -670,7 +664,7 @@ router.put("/:id/status", authenticateToken, async (req, res) => {
|
||||
itemName: rental.item.name,
|
||||
declineReason: renterMessage,
|
||||
rentalId: rental.id,
|
||||
}
|
||||
},
|
||||
);
|
||||
reqLogger.info("Payment declined email auto-sent to renter", {
|
||||
rentalId: rental.id,
|
||||
@@ -728,17 +722,14 @@ router.put("/:id/status", authenticateToken, async (req, res) => {
|
||||
// Create condition check reminder schedules
|
||||
try {
|
||||
await EventBridgeSchedulerService.createConditionCheckSchedules(
|
||||
updatedRental
|
||||
updatedRental,
|
||||
);
|
||||
} catch (schedulerError) {
|
||||
const reqLogger = logger.withRequestId(req.id);
|
||||
reqLogger.error(
|
||||
"Failed to create condition check schedules",
|
||||
{
|
||||
reqLogger.error("Failed to create condition check schedules", {
|
||||
error: schedulerError.message,
|
||||
rentalId: updatedRental.id,
|
||||
}
|
||||
);
|
||||
});
|
||||
// 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(
|
||||
updatedRental.owner,
|
||||
updatedRental.renter,
|
||||
updatedRental
|
||||
updatedRental,
|
||||
);
|
||||
const reqLogger = logger.withRequestId(req.id);
|
||||
reqLogger.info("Rental approval confirmation sent to owner", {
|
||||
@@ -764,7 +755,7 @@ router.put("/:id/status", authenticateToken, async (req, res) => {
|
||||
stack: emailError.stack,
|
||||
rentalId: updatedRental.id,
|
||||
ownerId: updatedRental.ownerId,
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -787,7 +778,7 @@ router.put("/:id/status", authenticateToken, async (req, res) => {
|
||||
renterNotification,
|
||||
updatedRental,
|
||||
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);
|
||||
reqLogger.info("Rental confirmation sent to renter", {
|
||||
@@ -804,7 +795,7 @@ router.put("/:id/status", authenticateToken, async (req, res) => {
|
||||
stack: emailError.stack,
|
||||
rentalId: updatedRental.id,
|
||||
renterId: updatedRental.renterId,
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -910,7 +901,7 @@ router.put("/:id/decline", authenticateToken, async (req, res) => {
|
||||
await emailServices.rentalFlow.sendRentalDeclinedEmail(
|
||||
updatedRental.renter,
|
||||
updatedRental,
|
||||
reason
|
||||
reason,
|
||||
);
|
||||
const reqLogger = logger.withRequestId(req.id);
|
||||
reqLogger.info("Rental decline notification sent to renter", {
|
||||
@@ -1130,7 +1121,7 @@ router.post("/cost-preview", authenticateToken, async (req, res) => {
|
||||
const totalAmount = RentalDurationCalculator.calculateRentalCost(
|
||||
rentalStartDateTime,
|
||||
rentalEndDateTime,
|
||||
item
|
||||
item,
|
||||
);
|
||||
|
||||
// Calculate fees
|
||||
@@ -1202,7 +1193,7 @@ router.get("/:id/refund-preview", authenticateToken, async (req, res, next) => {
|
||||
try {
|
||||
const preview = await RefundService.getRefundPreview(
|
||||
req.params.id,
|
||||
req.user.id
|
||||
req.user.id,
|
||||
);
|
||||
res.json(preview);
|
||||
} catch (error) {
|
||||
@@ -1246,7 +1237,7 @@ router.get(
|
||||
|
||||
const lateCalculation = LateReturnService.calculateLateFee(
|
||||
rental,
|
||||
actualReturnDateTime
|
||||
actualReturnDateTime,
|
||||
);
|
||||
|
||||
res.json(lateCalculation);
|
||||
@@ -1260,7 +1251,7 @@ router.get(
|
||||
});
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// Cancel rental with refund processing
|
||||
@@ -1276,7 +1267,7 @@ router.post("/:id/cancel", authenticateToken, async (req, res, next) => {
|
||||
const result = await RefundService.processCancellation(
|
||||
req.params.id,
|
||||
req.user.id,
|
||||
reason.trim()
|
||||
reason.trim(),
|
||||
);
|
||||
|
||||
// Return the updated rental with refund information
|
||||
@@ -1302,7 +1293,7 @@ router.post("/:id/cancel", authenticateToken, async (req, res, next) => {
|
||||
updatedRental.owner,
|
||||
updatedRental.renter,
|
||||
updatedRental,
|
||||
result.refund
|
||||
result.refund,
|
||||
);
|
||||
const reqLogger = logger.withRequestId(req.id);
|
||||
reqLogger.info("Cancellation emails sent", {
|
||||
@@ -1403,7 +1394,7 @@ router.post("/:id/mark-return", authenticateToken, async (req, res, next) => {
|
||||
await emailServices.rentalFlow.sendRentalCompletionEmails(
|
||||
rentalWithDetails.owner,
|
||||
rentalWithDetails.renter,
|
||||
rentalWithDetails
|
||||
rentalWithDetails,
|
||||
);
|
||||
const reqLogger = logger.withRequestId(req.id);
|
||||
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) {
|
||||
const lateReturnDamaged = await LateReturnService.processLateReturn(
|
||||
rentalId,
|
||||
actualReturnDateTime
|
||||
actualReturnDateTime,
|
||||
);
|
||||
damageUpdates.status = "returned_late_and_damaged";
|
||||
damageUpdates.lateFees = lateReturnDamaged.lateCalculation.lateFee;
|
||||
@@ -1463,7 +1454,7 @@ router.post("/:id/mark-return", authenticateToken, async (req, res, next) => {
|
||||
|
||||
const lateReturn = await LateReturnService.processLateReturn(
|
||||
rentalId,
|
||||
actualReturnDateTime
|
||||
actualReturnDateTime,
|
||||
);
|
||||
|
||||
updatedRental = lateReturn.rental;
|
||||
@@ -1484,7 +1475,7 @@ router.post("/:id/mark-return", authenticateToken, async (req, res, next) => {
|
||||
await emailServices.customerService.sendLostItemToCustomerService(
|
||||
updatedRental,
|
||||
owner,
|
||||
renter
|
||||
renter,
|
||||
);
|
||||
break;
|
||||
|
||||
@@ -1562,7 +1553,7 @@ router.post("/:id/report-damage", authenticateToken, async (req, res, next) => {
|
||||
"damage-reports",
|
||||
{
|
||||
maxKeys: IMAGE_LIMITS.damageReports,
|
||||
}
|
||||
},
|
||||
);
|
||||
if (!keyValidation.valid) {
|
||||
return res.status(400).json({
|
||||
@@ -1576,7 +1567,7 @@ router.post("/:id/report-damage", authenticateToken, async (req, res, next) => {
|
||||
const result = await DamageAssessmentService.processDamageAssessment(
|
||||
rentalId,
|
||||
damageInfo,
|
||||
userId
|
||||
userId,
|
||||
);
|
||||
|
||||
const reqLogger = logger.withRequestId(req.id);
|
||||
@@ -1654,7 +1645,7 @@ router.put("/:id/payment-method", authenticateToken, async (req, res, next) => {
|
||||
let paymentMethod;
|
||||
try {
|
||||
paymentMethod = await StripeService.getPaymentMethod(
|
||||
stripePaymentMethodId
|
||||
stripePaymentMethodId,
|
||||
);
|
||||
} catch {
|
||||
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",
|
||||
paymentStatus: "pending",
|
||||
},
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
if (updateCount === 0) {
|
||||
@@ -1725,7 +1716,7 @@ router.put("/:id/payment-method", authenticateToken, async (req, res, next) => {
|
||||
itemName: rental.item.name,
|
||||
rentalId: rental.id,
|
||||
approvalUrl: `${process.env.FRONTEND_URL}/rentals/${rentalId}`,
|
||||
}
|
||||
},
|
||||
);
|
||||
} catch (emailError) {
|
||||
// Don't fail the request if email fails
|
||||
@@ -1781,7 +1772,7 @@ router.get(
|
||||
|
||||
const stripe = require("stripe")(process.env.STRIPE_SECRET_KEY);
|
||||
const paymentIntent = await stripe.paymentIntents.retrieve(
|
||||
rental.stripePaymentIntentId
|
||||
rental.stripePaymentIntentId,
|
||||
);
|
||||
|
||||
return res.json({
|
||||
@@ -1798,7 +1789,7 @@ router.get(
|
||||
});
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
@@ -1812,8 +1803,29 @@ router.post(
|
||||
try {
|
||||
const rental = await Rental.findByPk(req.params.id, {
|
||||
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" },
|
||||
],
|
||||
});
|
||||
@@ -1837,7 +1849,7 @@ router.post(
|
||||
const stripe = require("stripe")(process.env.STRIPE_SECRET_KEY);
|
||||
const paymentIntent = await stripe.paymentIntents.retrieve(
|
||||
rental.stripePaymentIntentId,
|
||||
{ expand: ['latest_charge.payment_method_details'] }
|
||||
{ expand: ["latest_charge.payment_method_details"] },
|
||||
);
|
||||
|
||||
if (paymentIntent.status !== "succeeded") {
|
||||
@@ -1864,7 +1876,8 @@ router.post(
|
||||
paymentMethodLast4 = paymentMethodDetails.card?.last4 || null;
|
||||
} else if (type === "us_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);
|
||||
} catch (schedulerError) {
|
||||
const reqLogger = logger.withRequestId(req.id);
|
||||
reqLogger.error(
|
||||
"Failed to create condition check schedules",
|
||||
{
|
||||
reqLogger.error("Failed to create condition check schedules", {
|
||||
error: schedulerError.message,
|
||||
rentalId: rental.id,
|
||||
}
|
||||
);
|
||||
});
|
||||
// Don't fail the confirmation - schedules are non-critical
|
||||
}
|
||||
|
||||
@@ -1897,13 +1907,16 @@ router.post(
|
||||
await emailServices.rentalFlow.sendRentalApprovalConfirmationEmail(
|
||||
rental.owner,
|
||||
rental.renter,
|
||||
rental
|
||||
rental,
|
||||
);
|
||||
const reqLogger = logger.withRequestId(req.id);
|
||||
reqLogger.info("Rental approval confirmation sent to owner (after 3DS)", {
|
||||
reqLogger.info(
|
||||
"Rental approval confirmation sent to owner (after 3DS)",
|
||||
{
|
||||
rentalId: rental.id,
|
||||
ownerId: rental.ownerId,
|
||||
});
|
||||
},
|
||||
);
|
||||
} catch (emailError) {
|
||||
const reqLogger = logger.withRequestId(req.id);
|
||||
reqLogger.error(
|
||||
@@ -1911,7 +1924,7 @@ router.post(
|
||||
{
|
||||
error: emailError.message,
|
||||
rentalId: rental.id,
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1929,7 +1942,7 @@ router.post(
|
||||
renterNotification,
|
||||
rental,
|
||||
rental.renter.firstName,
|
||||
true
|
||||
true,
|
||||
);
|
||||
const reqLogger = logger.withRequestId(req.id);
|
||||
reqLogger.info("Rental confirmation sent to renter (after 3DS)", {
|
||||
@@ -1938,17 +1951,17 @@ router.post(
|
||||
});
|
||||
} catch (emailError) {
|
||||
const reqLogger = logger.withRequestId(req.id);
|
||||
reqLogger.error(
|
||||
"Failed to send rental confirmation email after 3DS",
|
||||
{
|
||||
reqLogger.error("Failed to send rental confirmation email after 3DS", {
|
||||
error: emailError.message,
|
||||
rentalId: rental.id,
|
||||
}
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
// Trigger payout if owner has payouts enabled
|
||||
if (rental.owner.stripePayoutsEnabled && rental.owner.stripeConnectedAccountId) {
|
||||
if (
|
||||
rental.owner.stripePayoutsEnabled &&
|
||||
rental.owner.stripeConnectedAccountId
|
||||
) {
|
||||
try {
|
||||
await PayoutService.processRentalPayout(rental);
|
||||
const reqLogger = logger.withRequestId(req.id);
|
||||
@@ -1983,7 +1996,7 @@ router.post(
|
||||
});
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
module.exports = router;
|
||||
|
||||
@@ -26,7 +26,7 @@ class LocationService {
|
||||
// distance = 3959 * acos(cos(radians(lat1)) * cos(radians(lat2))
|
||||
// * cos(radians(lng2) - radians(lng1))
|
||||
// + sin(radians(lat1)) * sin(radians(lat2)))
|
||||
// Note: 3959 is Earth's radius in miles
|
||||
// 3959 is Earth's radius in miles
|
||||
const query = `
|
||||
SELECT * FROM (
|
||||
SELECT
|
||||
|
||||
@@ -1,17 +1,24 @@
|
||||
<!DOCTYPE html>
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge">
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
|
||||
<title>Your Alpha Access Code - Village Share</title>
|
||||
<style>
|
||||
/* Reset styles */
|
||||
body, table, td, p, a, li, blockquote {
|
||||
body,
|
||||
table,
|
||||
td,
|
||||
p,
|
||||
a,
|
||||
li,
|
||||
blockquote {
|
||||
-webkit-text-size-adjust: 100%;
|
||||
-ms-text-size-adjust: 100%;
|
||||
}
|
||||
table, td {
|
||||
table,
|
||||
td {
|
||||
mso-table-lspace: 0pt;
|
||||
mso-table-rspace: 0pt;
|
||||
}
|
||||
@@ -27,7 +34,9 @@
|
||||
min-width: 100%;
|
||||
height: 100%;
|
||||
background-color: #f8f9fa;
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
|
||||
font-family:
|
||||
-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu,
|
||||
Cantarell, sans-serif;
|
||||
line-height: 1.6;
|
||||
color: #212529;
|
||||
}
|
||||
@@ -104,7 +113,7 @@
|
||||
}
|
||||
|
||||
.code {
|
||||
font-family: 'Courier New', Courier, monospace;
|
||||
font-family: "Courier New", Courier, monospace;
|
||||
font-size: 32px;
|
||||
font-weight: 700;
|
||||
color: #ffffff;
|
||||
@@ -192,7 +201,9 @@
|
||||
border-radius: 0;
|
||||
}
|
||||
|
||||
.header, .content, .footer {
|
||||
.header,
|
||||
.content,
|
||||
.footer {
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
@@ -227,24 +238,40 @@
|
||||
<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>
|
||||
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>
|
||||
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>
|
||||
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>
|
||||
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 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>
|
||||
@@ -259,23 +286,35 @@
|
||||
</div>
|
||||
|
||||
<p><strong>Important notes:</strong></p>
|
||||
<ul style="color: #6c757d; font-size: 14px;">
|
||||
<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>
|
||||
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>
|
||||
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:support@villageshare.app">support@villageshare.app</a></p>
|
||||
<p>
|
||||
Need help? Contact us at
|
||||
<a href="mailto:community-support@village-share.com"
|
||||
>community-support@village-share.com</a
|
||||
>
|
||||
</p>
|
||||
<p>© 2025 Village Share. All rights reserved.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<!DOCTYPE html>
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
@@ -34,8 +34,9 @@
|
||||
min-width: 100%;
|
||||
height: 100%;
|
||||
background-color: #f8f9fa;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
|
||||
Oxygen, Ubuntu, Cantarell, sans-serif;
|
||||
font-family:
|
||||
-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu,
|
||||
Cantarell, sans-serif;
|
||||
line-height: 1.6;
|
||||
color: #212529;
|
||||
}
|
||||
@@ -260,7 +261,8 @@
|
||||
</p>
|
||||
<p>
|
||||
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>
|
||||
</div>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<!DOCTYPE html>
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
@@ -34,8 +34,9 @@
|
||||
min-width: 100%;
|
||||
height: 100%;
|
||||
background-color: #f8f9fa;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
|
||||
Oxygen, Ubuntu, Cantarell, sans-serif;
|
||||
font-family:
|
||||
-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu,
|
||||
Cantarell, sans-serif;
|
||||
line-height: 1.6;
|
||||
color: #212529;
|
||||
}
|
||||
@@ -246,8 +247,8 @@
|
||||
<p>
|
||||
<strong>Didn't change your password?</strong> If you did not make
|
||||
this change, your account may be compromised. Please contact our
|
||||
support team immediately at support@villageshare.app to secure your
|
||||
account.
|
||||
support team immediately at community-support@village-share.com to
|
||||
secure your account.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -1,17 +1,24 @@
|
||||
<!DOCTYPE html>
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge">
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
|
||||
<title>Personal Information Updated - Village Share</title>
|
||||
<style>
|
||||
/* Reset styles */
|
||||
body, table, td, p, a, li, blockquote {
|
||||
body,
|
||||
table,
|
||||
td,
|
||||
p,
|
||||
a,
|
||||
li,
|
||||
blockquote {
|
||||
-webkit-text-size-adjust: 100%;
|
||||
-ms-text-size-adjust: 100%;
|
||||
}
|
||||
table, td {
|
||||
table,
|
||||
td {
|
||||
mso-table-lspace: 0pt;
|
||||
mso-table-rspace: 0pt;
|
||||
}
|
||||
@@ -27,7 +34,9 @@
|
||||
min-width: 100%;
|
||||
height: 100%;
|
||||
background-color: #f8f9fa;
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
|
||||
font-family:
|
||||
-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu,
|
||||
Cantarell, sans-serif;
|
||||
line-height: 1.6;
|
||||
color: #212529;
|
||||
}
|
||||
@@ -182,7 +191,9 @@
|
||||
border-radius: 0;
|
||||
}
|
||||
|
||||
.header, .content, .footer {
|
||||
.header,
|
||||
.content,
|
||||
.footer {
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
@@ -209,10 +220,18 @@
|
||||
<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>
|
||||
<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>
|
||||
|
||||
<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>
|
||||
<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>
|
||||
|
||||
<table class="details-table">
|
||||
<tr>
|
||||
@@ -226,11 +245,21 @@
|
||||
</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>
|
||||
<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
|
||||
community-support@village-share.com 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>
|
||||
<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>
|
||||
@@ -238,7 +267,11 @@
|
||||
|
||||
<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>
|
||||
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>© 2025 Village Share. All rights reserved.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -6,12 +6,12 @@
|
||||
* cancellation flows.
|
||||
*/
|
||||
|
||||
const request = require('supertest');
|
||||
const express = require('express');
|
||||
const cookieParser = require('cookie-parser');
|
||||
const jwt = require('jsonwebtoken');
|
||||
const { sequelize, User, Item, Rental } = require('../../models');
|
||||
const rentalRoutes = require('../../routes/rentals');
|
||||
const request = require("supertest");
|
||||
const express = require("express");
|
||||
const cookieParser = require("cookie-parser");
|
||||
const jwt = require("jsonwebtoken");
|
||||
const { sequelize, User, Item, Rental } = require("../../models");
|
||||
const rentalRoutes = require("../../routes/rentals");
|
||||
|
||||
// Test app setup
|
||||
const createTestApp = () => {
|
||||
@@ -21,11 +21,11 @@ const createTestApp = () => {
|
||||
|
||||
// Add request ID middleware
|
||||
app.use((req, res, next) => {
|
||||
req.id = 'test-request-id';
|
||||
req.id = "test-request-id";
|
||||
next();
|
||||
});
|
||||
|
||||
app.use('/rentals', rentalRoutes);
|
||||
app.use("/rentals", rentalRoutes);
|
||||
return app;
|
||||
};
|
||||
|
||||
@@ -34,7 +34,7 @@ const generateAuthToken = (user) => {
|
||||
return jwt.sign(
|
||||
{ id: user.id, jwtVersion: user.jwtVersion || 0 },
|
||||
process.env.JWT_ACCESS_SECRET,
|
||||
{ expiresIn: '15m' }
|
||||
{ expiresIn: "15m" },
|
||||
);
|
||||
};
|
||||
|
||||
@@ -42,11 +42,11 @@ const generateAuthToken = (user) => {
|
||||
const createTestUser = async (overrides = {}) => {
|
||||
const defaultData = {
|
||||
email: `user-${Date.now()}-${Math.random().toString(36).slice(2)}@example.com`,
|
||||
password: 'TestPassword123!',
|
||||
firstName: 'Test',
|
||||
lastName: 'User',
|
||||
password: "TestPassword123!",
|
||||
firstName: "Test",
|
||||
lastName: "User",
|
||||
isVerified: true,
|
||||
authProvider: 'local',
|
||||
authProvider: "local",
|
||||
};
|
||||
|
||||
return User.create({ ...defaultData, ...overrides });
|
||||
@@ -54,17 +54,17 @@ const createTestUser = async (overrides = {}) => {
|
||||
|
||||
const createTestItem = async (ownerId, overrides = {}) => {
|
||||
const defaultData = {
|
||||
name: 'Test Item',
|
||||
description: 'A test item for rental',
|
||||
pricePerDay: 25.00,
|
||||
pricePerHour: 5.00,
|
||||
replacementCost: 500.00,
|
||||
condition: 'excellent',
|
||||
name: "Test Item",
|
||||
description: "A test item for rental",
|
||||
pricePerDay: 25.0,
|
||||
pricePerHour: 5.0,
|
||||
replacementCost: 500.0,
|
||||
condition: "excellent",
|
||||
isAvailable: true,
|
||||
pickUpAvailable: true,
|
||||
ownerId,
|
||||
city: 'Test City',
|
||||
state: 'California',
|
||||
city: "Test City",
|
||||
state: "California",
|
||||
};
|
||||
|
||||
return Item.create({ ...defaultData, ...overrides });
|
||||
@@ -84,15 +84,15 @@ const createTestRental = async (itemId, renterId, ownerId, overrides = {}) => {
|
||||
totalAmount: 0,
|
||||
platformFee: 0,
|
||||
payoutAmount: 0,
|
||||
status: 'pending',
|
||||
paymentStatus: 'pending',
|
||||
deliveryMethod: 'pickup',
|
||||
status: "pending",
|
||||
paymentStatus: "pending",
|
||||
deliveryMethod: "pickup",
|
||||
};
|
||||
|
||||
return Rental.create({ ...defaultData, ...overrides });
|
||||
};
|
||||
|
||||
describe('Rental Integration Tests', () => {
|
||||
describe("Rental Integration Tests", () => {
|
||||
let app;
|
||||
let owner;
|
||||
let renter;
|
||||
@@ -100,9 +100,9 @@ describe('Rental Integration Tests', () => {
|
||||
|
||||
beforeAll(async () => {
|
||||
// Set test environment variables
|
||||
process.env.NODE_ENV = 'test';
|
||||
process.env.JWT_ACCESS_SECRET = 'test-access-secret';
|
||||
process.env.JWT_REFRESH_SECRET = 'test-refresh-secret';
|
||||
process.env.NODE_ENV = "test";
|
||||
process.env.JWT_ACCESS_SECRET = "test-access-secret";
|
||||
process.env.JWT_REFRESH_SECRET = "test-refresh-secret";
|
||||
|
||||
// Sync database
|
||||
await sequelize.sync({ force: true });
|
||||
@@ -122,32 +122,32 @@ describe('Rental Integration Tests', () => {
|
||||
|
||||
// Create test users
|
||||
owner = await createTestUser({
|
||||
email: 'owner@example.com',
|
||||
firstName: 'Item',
|
||||
lastName: 'Owner',
|
||||
stripeConnectedAccountId: 'acct_test_owner',
|
||||
email: "owner@example.com",
|
||||
firstName: "Item",
|
||||
lastName: "Owner",
|
||||
stripeConnectedAccountId: "acct_test_owner",
|
||||
});
|
||||
|
||||
renter = await createTestUser({
|
||||
email: 'renter@example.com',
|
||||
firstName: 'Item',
|
||||
lastName: 'Renter',
|
||||
email: "renter@example.com",
|
||||
firstName: "Item",
|
||||
lastName: "Renter",
|
||||
});
|
||||
|
||||
// Create test item
|
||||
item = await createTestItem(owner.id);
|
||||
});
|
||||
|
||||
describe('GET /rentals/renting', () => {
|
||||
it('should return rentals where user is the renter', async () => {
|
||||
describe("GET /rentals/renting", () => {
|
||||
it("should return rentals where user is the renter", async () => {
|
||||
// Create a rental where renter is the renter
|
||||
await createTestRental(item.id, renter.id, owner.id);
|
||||
|
||||
const token = generateAuthToken(renter);
|
||||
|
||||
const response = await request(app)
|
||||
.get('/rentals/renting')
|
||||
.set('Cookie', [`accessToken=${token}`])
|
||||
.get("/rentals/renting")
|
||||
.set("Cookie", [`accessToken=${token}`])
|
||||
.expect(200);
|
||||
|
||||
expect(Array.isArray(response.body)).toBe(true);
|
||||
@@ -155,37 +155,35 @@ describe('Rental Integration Tests', () => {
|
||||
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 response = await request(app)
|
||||
.get('/rentals/renting')
|
||||
.set('Cookie', [`accessToken=${token}`])
|
||||
.get("/rentals/renting")
|
||||
.set("Cookie", [`accessToken=${token}`])
|
||||
.expect(200);
|
||||
|
||||
expect(Array.isArray(response.body)).toBe(true);
|
||||
expect(response.body.length).toBe(0);
|
||||
});
|
||||
|
||||
it('should require authentication', async () => {
|
||||
const response = await request(app)
|
||||
.get('/rentals/renting')
|
||||
.expect(401);
|
||||
it("should require authentication", async () => {
|
||||
const response = await request(app).get("/rentals/renting").expect(401);
|
||||
|
||||
expect(response.body.code).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /rentals/owning', () => {
|
||||
it('should return rentals where user is the owner', async () => {
|
||||
describe("GET /rentals/owning", () => {
|
||||
it("should return rentals where user is the owner", async () => {
|
||||
// Create a rental where owner is the item owner
|
||||
await createTestRental(item.id, renter.id, owner.id);
|
||||
|
||||
const token = generateAuthToken(owner);
|
||||
|
||||
const response = await request(app)
|
||||
.get('/rentals/owning')
|
||||
.set('Cookie', [`accessToken=${token}`])
|
||||
.get("/rentals/owning")
|
||||
.set("Cookie", [`accessToken=${token}`])
|
||||
.expect(200);
|
||||
|
||||
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;
|
||||
|
||||
beforeEach(async () => {
|
||||
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 response = await request(app)
|
||||
.put(`/rentals/${rental.id}/status`)
|
||||
.set('Cookie', [`accessToken=${token}`])
|
||||
.send({ status: 'confirmed' })
|
||||
.set("Cookie", [`accessToken=${token}`])
|
||||
.send({ status: "confirmed" })
|
||||
.expect(200);
|
||||
|
||||
expect(response.body.status).toBe('confirmed');
|
||||
expect(response.body.status).toBe("confirmed");
|
||||
|
||||
// Verify in database
|
||||
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 response = await request(app)
|
||||
.put(`/rentals/${rental.id}/status`)
|
||||
.set('Cookie', [`accessToken=${token}`])
|
||||
.send({ status: 'confirmed' })
|
||||
.set("Cookie", [`accessToken=${token}`])
|
||||
.send({ status: "confirmed" })
|
||||
.expect(200);
|
||||
|
||||
// Note: API currently allows both owner and renter to update status
|
||||
// Owner-specific logic (payment processing) only runs for owner
|
||||
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
|
||||
await rental.update({ status: 'confirmed' });
|
||||
await rental.update({ status: "confirmed" });
|
||||
|
||||
const token = generateAuthToken(owner);
|
||||
|
||||
// API allows re-confirming (idempotent operation)
|
||||
const response = await request(app)
|
||||
.put(`/rentals/${rental.id}/status`)
|
||||
.set('Cookie', [`accessToken=${token}`])
|
||||
.send({ status: 'confirmed' })
|
||||
.set("Cookie", [`accessToken=${token}`])
|
||||
.send({ status: "confirmed" })
|
||||
.expect(200);
|
||||
|
||||
// Status should remain confirmed
|
||||
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;
|
||||
|
||||
beforeEach(async () => {
|
||||
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 response = await request(app)
|
||||
.put(`/rentals/${rental.id}/decline`)
|
||||
.set('Cookie', [`accessToken=${token}`])
|
||||
.send({ reason: 'Item not available for those dates' })
|
||||
.set("Cookie", [`accessToken=${token}`])
|
||||
.send({ reason: "Item not available for those dates" })
|
||||
.expect(200);
|
||||
|
||||
expect(response.body.status).toBe('declined');
|
||||
expect(response.body.status).toBe("declined");
|
||||
|
||||
// Verify in database
|
||||
await rental.reload();
|
||||
expect(rental.status).toBe('declined');
|
||||
expect(rental.declineReason).toBe('Item not available for those dates');
|
||||
expect(rental.status).toBe("declined");
|
||||
expect(rental.declineReason).toBe("Item not available for those dates");
|
||||
});
|
||||
|
||||
it('should not allow declining already declined rental', async () => {
|
||||
await rental.update({ status: 'declined' });
|
||||
it("should not allow declining already declined rental", async () => {
|
||||
await rental.update({ status: "declined" });
|
||||
|
||||
const token = generateAuthToken(owner);
|
||||
|
||||
const response = await request(app)
|
||||
.put(`/rentals/${rental.id}/decline`)
|
||||
.set('Cookie', [`accessToken=${token}`])
|
||||
.send({ reason: 'Already declined' })
|
||||
.set("Cookie", [`accessToken=${token}`])
|
||||
.send({ reason: "Already declined" })
|
||||
.expect(400);
|
||||
|
||||
expect(response.body.error).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /rentals/:id/cancel', () => {
|
||||
describe("POST /rentals/:id/cancel", () => {
|
||||
let rental;
|
||||
|
||||
beforeEach(async () => {
|
||||
rental = await createTestRental(item.id, renter.id, owner.id, {
|
||||
status: 'confirmed',
|
||||
paymentStatus: 'paid',
|
||||
status: "confirmed",
|
||||
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 response = await request(app)
|
||||
.post(`/rentals/${rental.id}/cancel`)
|
||||
.set('Cookie', [`accessToken=${token}`])
|
||||
.send({ reason: 'Change of plans' })
|
||||
.set("Cookie", [`accessToken=${token}`])
|
||||
.send({ reason: "Change of plans" })
|
||||
.expect(200);
|
||||
|
||||
// Response format is { rental: {...}, refund: {...} }
|
||||
expect(response.body.rental.status).toBe('cancelled');
|
||||
expect(response.body.rental.cancelledBy).toBe('renter');
|
||||
expect(response.body.rental.status).toBe("cancelled");
|
||||
expect(response.body.rental.cancelledBy).toBe("renter");
|
||||
|
||||
// Verify in database
|
||||
await rental.reload();
|
||||
expect(rental.status).toBe('cancelled');
|
||||
expect(rental.cancelledBy).toBe('renter');
|
||||
expect(rental.status).toBe("cancelled");
|
||||
expect(rental.cancelledBy).toBe("renter");
|
||||
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 response = await request(app)
|
||||
.post(`/rentals/${rental.id}/cancel`)
|
||||
.set('Cookie', [`accessToken=${token}`])
|
||||
.send({ reason: 'Item broken' })
|
||||
.set("Cookie", [`accessToken=${token}`])
|
||||
.send({ reason: "Item broken" })
|
||||
.expect(200);
|
||||
|
||||
expect(response.body.rental.status).toBe('cancelled');
|
||||
expect(response.body.rental.cancelledBy).toBe('owner');
|
||||
expect(response.body.rental.status).toBe("cancelled");
|
||||
expect(response.body.rental.cancelledBy).toBe("owner");
|
||||
});
|
||||
|
||||
it('should not allow cancelling completed rental', async () => {
|
||||
await rental.update({ status: 'completed', paymentStatus: 'paid' });
|
||||
it("should not allow cancelling completed rental", async () => {
|
||||
await rental.update({ status: "completed", paymentStatus: "paid" });
|
||||
|
||||
const token = generateAuthToken(renter);
|
||||
|
||||
// RefundService throws error which becomes 500 via next(error)
|
||||
const response = await request(app)
|
||||
.post(`/rentals/${rental.id}/cancel`)
|
||||
.set('Cookie', [`accessToken=${token}`])
|
||||
.send({ reason: 'Too late' });
|
||||
.set("Cookie", [`accessToken=${token}`])
|
||||
.send({ reason: "Too late" });
|
||||
|
||||
// Expect error (could be 400 or 500 depending on error middleware)
|
||||
expect(response.status).toBeGreaterThanOrEqual(400);
|
||||
});
|
||||
|
||||
it('should not allow unauthorized user to cancel rental', async () => {
|
||||
const otherUser = await createTestUser({ email: 'other@example.com' });
|
||||
it("should not allow unauthorized user to cancel rental", async () => {
|
||||
const otherUser = await createTestUser({ email: "other@example.com" });
|
||||
const token = generateAuthToken(otherUser);
|
||||
|
||||
const response = await request(app)
|
||||
.post(`/rentals/${rental.id}/cancel`)
|
||||
.set('Cookie', [`accessToken=${token}`])
|
||||
.send({ reason: 'Not my rental' });
|
||||
.set("Cookie", [`accessToken=${token}`])
|
||||
.send({ reason: "Not my rental" });
|
||||
|
||||
// Expect error (could be 403 or 500 depending on error middleware)
|
||||
expect(response.status).toBeGreaterThanOrEqual(400);
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /rentals/pending-requests-count', () => {
|
||||
it('should return count of pending rental requests for owner', async () => {
|
||||
describe("GET /rentals/pending-requests-count", () => {
|
||||
it("should return count of pending rental requests for owner", async () => {
|
||||
// Create multiple pending rentals
|
||||
await createTestRental(item.id, renter.id, owner.id, { status: 'pending' });
|
||||
await createTestRental(item.id, renter.id, owner.id, { 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: "pending",
|
||||
});
|
||||
await createTestRental(item.id, renter.id, owner.id, {
|
||||
status: "confirmed",
|
||||
});
|
||||
|
||||
const token = generateAuthToken(owner);
|
||||
|
||||
const response = await request(app)
|
||||
.get('/rentals/pending-requests-count')
|
||||
.set('Cookie', [`accessToken=${token}`])
|
||||
.get("/rentals/pending-requests-count")
|
||||
.set("Cookie", [`accessToken=${token}`])
|
||||
.expect(200);
|
||||
|
||||
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 response = await request(app)
|
||||
.get('/rentals/pending-requests-count')
|
||||
.set('Cookie', [`accessToken=${token}`])
|
||||
.get("/rentals/pending-requests-count")
|
||||
.set("Cookie", [`accessToken=${token}`])
|
||||
.expect(200);
|
||||
|
||||
expect(response.body.count).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Rental Lifecycle', () => {
|
||||
it('should complete full rental lifecycle: pending -> confirmed -> active -> completed', async () => {
|
||||
describe("Rental Lifecycle", () => {
|
||||
it("should complete full rental lifecycle: pending -> confirmed -> active -> completed", async () => {
|
||||
// Create pending free rental (totalAmount: 0 is default)
|
||||
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
|
||||
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)
|
||||
let response = await request(app)
|
||||
.put(`/rentals/${rental.id}/status`)
|
||||
.set('Cookie', [`accessToken=${ownerToken}`])
|
||||
.send({ status: 'confirmed' })
|
||||
.set("Cookie", [`accessToken=${ownerToken}`])
|
||||
.send({ status: "confirmed" })
|
||||
.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
|
||||
// Note: "active" is a computed status, not stored. The stored status remains "confirmed"
|
||||
// Step 2: Rental is now "active" because status is confirmed and startDateTime has passed.
|
||||
// "active" is a computed status, not stored. The stored status remains "confirmed"
|
||||
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
|
||||
|
||||
// Step 3: Owner marks rental as completed (via mark-return with status='returned')
|
||||
response = await request(app)
|
||||
.post(`/rentals/${rental.id}/mark-return`)
|
||||
.set('Cookie', [`accessToken=${ownerToken}`])
|
||||
.send({ status: 'returned' })
|
||||
.set("Cookie", [`accessToken=${ownerToken}`])
|
||||
.send({ status: "returned" })
|
||||
.expect(200);
|
||||
|
||||
expect(response.body.rental.status).toBe('completed');
|
||||
expect(response.body.rental.status).toBe("completed");
|
||||
|
||||
// Verify final state
|
||||
await rental.reload();
|
||||
expect(rental.status).toBe('completed');
|
||||
expect(rental.status).toBe("completed");
|
||||
});
|
||||
});
|
||||
|
||||
describe('Review System', () => {
|
||||
describe("Review System", () => {
|
||||
let completedRental;
|
||||
|
||||
beforeEach(async () => {
|
||||
completedRental = await createTestRental(item.id, renter.id, owner.id, {
|
||||
status: 'completed',
|
||||
paymentStatus: 'paid',
|
||||
status: "completed",
|
||||
paymentStatus: "paid",
|
||||
});
|
||||
});
|
||||
|
||||
it('should allow renter to review item', async () => {
|
||||
it("should allow renter to review item", async () => {
|
||||
const token = generateAuthToken(renter);
|
||||
|
||||
const response = await request(app)
|
||||
.post(`/rentals/${completedRental.id}/review-item`)
|
||||
.set('Cookie', [`accessToken=${token}`])
|
||||
.set("Cookie", [`accessToken=${token}`])
|
||||
.send({
|
||||
rating: 5,
|
||||
review: 'Great item, worked perfectly!',
|
||||
review: "Great item, worked perfectly!",
|
||||
})
|
||||
.expect(200);
|
||||
|
||||
@@ -459,19 +462,19 @@ describe('Rental Integration Tests', () => {
|
||||
// Verify in database
|
||||
await completedRental.reload();
|
||||
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();
|
||||
});
|
||||
|
||||
it('should allow owner to review renter', async () => {
|
||||
it("should allow owner to review renter", async () => {
|
||||
const token = generateAuthToken(owner);
|
||||
|
||||
const response = await request(app)
|
||||
.post(`/rentals/${completedRental.id}/review-renter`)
|
||||
.set('Cookie', [`accessToken=${token}`])
|
||||
.set("Cookie", [`accessToken=${token}`])
|
||||
.send({
|
||||
rating: 4,
|
||||
review: 'Good renter, returned on time.',
|
||||
review: "Good renter, returned on time.",
|
||||
})
|
||||
.expect(200);
|
||||
|
||||
@@ -480,33 +483,40 @@ describe('Rental Integration Tests', () => {
|
||||
// Verify in database
|
||||
await completedRental.reload();
|
||||
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 () => {
|
||||
const pendingRental = await createTestRental(item.id, renter.id, owner.id, {
|
||||
status: 'pending',
|
||||
});
|
||||
it("should not allow review of non-completed rental", async () => {
|
||||
const pendingRental = await createTestRental(
|
||||
item.id,
|
||||
renter.id,
|
||||
owner.id,
|
||||
{
|
||||
status: "pending",
|
||||
},
|
||||
);
|
||||
|
||||
const token = generateAuthToken(renter);
|
||||
|
||||
const response = await request(app)
|
||||
.post(`/rentals/${pendingRental.id}/review-item`)
|
||||
.set('Cookie', [`accessToken=${token}`])
|
||||
.set("Cookie", [`accessToken=${token}`])
|
||||
.send({
|
||||
rating: 5,
|
||||
review: 'Cannot review yet',
|
||||
review: "Cannot review yet",
|
||||
})
|
||||
.expect(400);
|
||||
|
||||
expect(response.body.error).toBeDefined();
|
||||
});
|
||||
|
||||
it('should not allow duplicate reviews', async () => {
|
||||
it("should not allow duplicate reviews", async () => {
|
||||
// First review
|
||||
await completedRental.update({
|
||||
itemRating: 5,
|
||||
itemReview: 'First review',
|
||||
itemReview: "First review",
|
||||
itemReviewSubmittedAt: new Date(),
|
||||
});
|
||||
|
||||
@@ -514,31 +524,39 @@ describe('Rental Integration Tests', () => {
|
||||
|
||||
const response = await request(app)
|
||||
.post(`/rentals/${completedRental.id}/review-item`)
|
||||
.set('Cookie', [`accessToken=${token}`])
|
||||
.set("Cookie", [`accessToken=${token}`])
|
||||
.send({
|
||||
rating: 3,
|
||||
review: 'Second review attempt',
|
||||
review: "Second review attempt",
|
||||
})
|
||||
.expect(400);
|
||||
|
||||
expect(response.body.error).toContain('already');
|
||||
expect(response.body.error).toContain("already");
|
||||
});
|
||||
});
|
||||
|
||||
describe('Database Constraints', () => {
|
||||
it('should not allow rental with invalid item ID', async () => {
|
||||
describe("Database Constraints", () => {
|
||||
it("should not allow rental with invalid item ID", async () => {
|
||||
await expect(
|
||||
createTestRental('00000000-0000-0000-0000-000000000000', renter.id, owner.id)
|
||||
createTestRental(
|
||||
"00000000-0000-0000-0000-000000000000",
|
||||
renter.id,
|
||||
owner.id,
|
||||
),
|
||||
).rejects.toThrow();
|
||||
});
|
||||
|
||||
it('should not allow rental with invalid user IDs', async () => {
|
||||
it("should not allow rental with invalid user IDs", async () => {
|
||||
await expect(
|
||||
createTestRental(item.id, '00000000-0000-0000-0000-000000000000', owner.id)
|
||||
createTestRental(
|
||||
item.id,
|
||||
"00000000-0000-0000-0000-000000000000",
|
||||
owner.id,
|
||||
),
|
||||
).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);
|
||||
|
||||
// Delete the item
|
||||
@@ -550,10 +568,10 @@ describe('Rental Integration Tests', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('Concurrent Operations', () => {
|
||||
it('should handle concurrent status updates (last write wins)', async () => {
|
||||
describe("Concurrent Operations", () => {
|
||||
it("should handle concurrent status updates (last write wins)", async () => {
|
||||
const rental = await createTestRental(item.id, renter.id, owner.id, {
|
||||
status: 'pending',
|
||||
status: "pending",
|
||||
});
|
||||
|
||||
const ownerToken = generateAuthToken(owner);
|
||||
@@ -562,22 +580,22 @@ describe('Rental Integration Tests', () => {
|
||||
const [confirmResult, declineResult] = await Promise.allSettled([
|
||||
request(app)
|
||||
.put(`/rentals/${rental.id}/status`)
|
||||
.set('Cookie', [`accessToken=${ownerToken}`])
|
||||
.send({ status: 'confirmed' }),
|
||||
.set("Cookie", [`accessToken=${ownerToken}`])
|
||||
.send({ status: "confirmed" }),
|
||||
request(app)
|
||||
.put(`/rentals/${rental.id}/decline`)
|
||||
.set('Cookie', [`accessToken=${ownerToken}`])
|
||||
.send({ reason: 'Declining instead' }),
|
||||
.set("Cookie", [`accessToken=${ownerToken}`])
|
||||
.send({ reason: "Declining instead" }),
|
||||
]);
|
||||
|
||||
// Both requests may succeed (no optimistic locking)
|
||||
// Verify rental ends up in a valid state
|
||||
await rental.reload();
|
||||
expect(['confirmed', 'declined']).toContain(rental.status);
|
||||
expect(["confirmed", "declined"]).toContain(rental.status);
|
||||
|
||||
// At least one should have succeeded
|
||||
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);
|
||||
});
|
||||
|
||||
@@ -98,7 +98,7 @@ describe("Stripe Routes", () => {
|
||||
StripeService.getCheckoutSession.mockResolvedValue(mockSession);
|
||||
|
||||
const response = await request(app).get(
|
||||
"/stripe/checkout-session/cs_123456789"
|
||||
"/stripe/checkout-session/cs_123456789",
|
||||
);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
@@ -116,7 +116,7 @@ describe("Stripe Routes", () => {
|
||||
});
|
||||
|
||||
expect(StripeService.getCheckoutSession).toHaveBeenCalledWith(
|
||||
"cs_123456789"
|
||||
"cs_123456789",
|
||||
);
|
||||
});
|
||||
|
||||
@@ -132,7 +132,7 @@ describe("Stripe Routes", () => {
|
||||
StripeService.getCheckoutSession.mockResolvedValue(mockSession);
|
||||
|
||||
const response = await request(app).get(
|
||||
"/stripe/checkout-session/cs_123456789"
|
||||
"/stripe/checkout-session/cs_123456789",
|
||||
);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
@@ -150,7 +150,7 @@ describe("Stripe Routes", () => {
|
||||
StripeService.getCheckoutSession.mockRejectedValue(error);
|
||||
|
||||
const response = await request(app).get(
|
||||
"/stripe/checkout-session/invalid_session"
|
||||
"/stripe/checkout-session/invalid_session",
|
||||
);
|
||||
|
||||
expect(response.status).toBe(500);
|
||||
@@ -261,7 +261,6 @@ describe("Stripe Routes", () => {
|
||||
|
||||
expect(response.status).toBe(500);
|
||||
expect(response.body).toEqual({ error: "Invalid email address" });
|
||||
// Note: route uses logger instead of console.error
|
||||
});
|
||||
|
||||
it("should handle database update errors", async () => {
|
||||
@@ -313,7 +312,7 @@ describe("Stripe Routes", () => {
|
||||
expect(StripeService.createAccountLink).toHaveBeenCalledWith(
|
||||
"acct_123456789",
|
||||
"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.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(
|
||||
"acct_123456789"
|
||||
"acct_123456789",
|
||||
);
|
||||
});
|
||||
|
||||
@@ -516,7 +514,6 @@ describe("Stripe Routes", () => {
|
||||
|
||||
expect(response.status).toBe(500);
|
||||
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.body).toEqual({ error: "Invalid email address" });
|
||||
// Note: route uses logger.withRequestId().error() instead of console.error
|
||||
});
|
||||
|
||||
it("should handle database update errors", async () => {
|
||||
@@ -785,7 +781,7 @@ describe("Stripe Routes", () => {
|
||||
StripeService.getCheckoutSession.mockRejectedValue(error);
|
||||
|
||||
const response = await request(app).get(
|
||||
`/stripe/checkout-session/${longSessionId}`
|
||||
`/stripe/checkout-session/${longSessionId}`,
|
||||
);
|
||||
|
||||
expect(response.status).toBe(500);
|
||||
|
||||
@@ -159,7 +159,7 @@ describe("EmailClient", () => {
|
||||
);
|
||||
|
||||
expect(SendEmailCommand).toHaveBeenCalledWith({
|
||||
Source: "Village Share <noreply@villageshare.app>",
|
||||
Source: "Village Share <noreply@email.com>",
|
||||
Destination: {
|
||||
ToAddresses: ["test@example.com"],
|
||||
},
|
||||
@@ -253,7 +253,7 @@ describe("EmailClient", () => {
|
||||
|
||||
expect(SendEmailCommand).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
ReplyToAddresses: ["support@villageshare.app"],
|
||||
ReplyToAddresses: ["support@email.com"],
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -123,7 +123,7 @@ describe("UserEngagementEmailService", () => {
|
||||
ownerName: "John",
|
||||
itemName: "Power Drill",
|
||||
deletionReason: "Violated community guidelines",
|
||||
supportEmail: "support@villageshare.com",
|
||||
supportEmail: "support@email.com",
|
||||
dashboardUrl: "http://localhost:3000/owning",
|
||||
}),
|
||||
);
|
||||
@@ -183,7 +183,7 @@ describe("UserEngagementEmailService", () => {
|
||||
expect.objectContaining({
|
||||
userName: "John",
|
||||
banReason: "Multiple policy violations",
|
||||
supportEmail: "support@villageshare.com",
|
||||
supportEmail: "support@email.com",
|
||||
}),
|
||||
);
|
||||
expect(service.emailClient.sendEmail).toHaveBeenCalledWith(
|
||||
|
||||
@@ -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 can’t go back!**
|
||||
|
||||
If you aren’t 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 you’re on your own.
|
||||
|
||||
You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t 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/).
|
||||
@@ -5,19 +5,25 @@
|
||||
* automatic token verification and manual code entry.
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { render, screen, waitFor, fireEvent, act } from '@testing-library/react';
|
||||
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';
|
||||
import React from "react";
|
||||
import {
|
||||
render,
|
||||
screen,
|
||||
waitFor,
|
||||
fireEvent,
|
||||
act,
|
||||
} from "@testing-library/react";
|
||||
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
|
||||
vi.mock('../../contexts/AuthContext');
|
||||
vi.mock('../../services/api', () => ({
|
||||
vi.mock("../../contexts/AuthContext");
|
||||
vi.mock("../../services/api", () => ({
|
||||
authAPI: {
|
||||
verifyEmail: vi.fn(),
|
||||
resendVerification: vi.fn(),
|
||||
@@ -25,8 +31,8 @@ vi.mock('../../services/api', () => ({
|
||||
}));
|
||||
|
||||
const mockNavigate = vi.fn();
|
||||
vi.mock('react-router', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('react-router')>();
|
||||
vi.mock("react-router", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("react-router")>();
|
||||
return {
|
||||
...actual,
|
||||
useNavigate: () => mockNavigate,
|
||||
@@ -34,16 +40,23 @@ vi.mock('react-router', async (importOriginal) => {
|
||||
});
|
||||
|
||||
const mockedUseAuth = useAuth as MockedFunction<typeof useAuth>;
|
||||
const mockedVerifyEmail = authAPI.verifyEmail as MockedFunction<typeof authAPI.verifyEmail>;
|
||||
const mockedResendVerification = authAPI.resendVerification as MockedFunction<typeof authAPI.resendVerification>;
|
||||
const mockedVerifyEmail = authAPI.verifyEmail as MockedFunction<
|
||||
typeof authAPI.verifyEmail
|
||||
>;
|
||||
const mockedResendVerification = authAPI.resendVerification as MockedFunction<
|
||||
typeof authAPI.resendVerification
|
||||
>;
|
||||
|
||||
// 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({
|
||||
user: mockUnverifiedUser,
|
||||
loading: false,
|
||||
showAuthModal: false,
|
||||
authModalMode: 'login',
|
||||
authModalMode: "login",
|
||||
login: vi.fn(),
|
||||
register: vi.fn(),
|
||||
googleLogin: vi.fn(),
|
||||
@@ -60,11 +73,11 @@ const renderVerifyEmail = (searchParams: string = '', authOverrides: Partial<Ret
|
||||
<Routes>
|
||||
<Route path="/verify-email" element={<VerifyEmail />} />
|
||||
</Routes>
|
||||
</MemoryRouter>
|
||||
</MemoryRouter>,
|
||||
);
|
||||
};
|
||||
|
||||
describe('VerifyEmail', () => {
|
||||
describe("VerifyEmail", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.useFakeTimers({ shouldAdvanceTime: true });
|
||||
@@ -76,77 +89,85 @@ describe('VerifyEmail', () => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe('Initial Loading State', () => {
|
||||
it('shows loading state while auth is initializing', async () => {
|
||||
renderVerifyEmail('', { loading: true });
|
||||
describe("Initial Loading State", () => {
|
||||
it("shows loading state while auth is initializing", async () => {
|
||||
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
|
||||
expect(screen.getAllByText('Loading...').length).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Authentication Check', () => {
|
||||
it('redirects unauthenticated users to login', async () => {
|
||||
renderVerifyEmail('', { user: null });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockNavigate).toHaveBeenCalledWith(
|
||||
expect.stringContaining('/?login=true&redirect='),
|
||||
{ replace: true }
|
||||
expect(screen.getAllByText("Loading...").length).toBeGreaterThanOrEqual(
|
||||
1,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it('redirects unauthenticated users with token to login with return URL', async () => {
|
||||
renderVerifyEmail('?token=test-token-123', { user: null });
|
||||
describe("Authentication Check", () => {
|
||||
it("redirects unauthenticated users to login", async () => {
|
||||
renderVerifyEmail("", { user: null });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockNavigate).toHaveBeenCalledWith(
|
||||
expect.stringContaining('login=true'),
|
||||
{ replace: true }
|
||||
expect.stringContaining("/?login=true&redirect="),
|
||||
{ replace: true },
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it("redirects unauthenticated users with token to login with return URL", async () => {
|
||||
renderVerifyEmail("?token=test-token-123", { user: null });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockNavigate).toHaveBeenCalledWith(
|
||||
expect.stringContaining("login=true"),
|
||||
{ replace: true },
|
||||
);
|
||||
expect(mockNavigate).toHaveBeenCalledWith(
|
||||
expect.stringContaining('verify-email'),
|
||||
{ replace: true }
|
||||
expect.stringContaining("verify-email"),
|
||||
{ replace: true },
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Auto-Verification with Token', () => {
|
||||
it('auto-verifies when token present in URL', async () => {
|
||||
renderVerifyEmail('?token=valid-token-123');
|
||||
describe("Auto-Verification with Token", () => {
|
||||
it("auto-verifies when token present in URL", async () => {
|
||||
renderVerifyEmail("?token=valid-token-123");
|
||||
|
||||
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();
|
||||
renderVerifyEmail('?token=valid-token', { checkAuth: mockCheckAuth });
|
||||
renderVerifyEmail("?token=valid-token", { checkAuth: mockCheckAuth });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Email Verified Successfully!')).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText("Email Verified Successfully!"),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
expect(mockCheckAuth).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('shows success state immediately for already verified user', async () => {
|
||||
renderVerifyEmail('', { user: mockUser });
|
||||
it("shows success state immediately for already verified user", async () => {
|
||||
renderVerifyEmail("", { user: mockUser });
|
||||
|
||||
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 () => {
|
||||
renderVerifyEmail('?token=valid-token');
|
||||
it("auto-redirects to home after successful verification", async () => {
|
||||
renderVerifyEmail("?token=valid-token");
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Email Verified Successfully!')).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText("Email Verified Successfully!"),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Advance timers to trigger auto-redirect (3 seconds)
|
||||
@@ -155,215 +176,228 @@ describe('VerifyEmail', () => {
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockNavigate).toHaveBeenCalledWith('/', { replace: true });
|
||||
expect(mockNavigate).toHaveBeenCalledWith("/", { replace: true });
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Manual Code Entry', () => {
|
||||
it('shows manual code entry form when no token in URL', async () => {
|
||||
describe("Manual Code Entry", () => {
|
||||
it("shows manual code entry form when no token in URL", async () => {
|
||||
renderVerifyEmail();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Enter Verification Code')).toBeInTheDocument();
|
||||
expect(screen.getByText('Enter the 6-digit code sent to your email')).toBeInTheDocument();
|
||||
expect(screen.getByText("Enter Verification Code")).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText("Enter the 6-digit code sent to your email"),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Check for 6 input fields
|
||||
const inputs = screen.getAllByRole('textbox');
|
||||
const inputs = screen.getAllByRole("textbox");
|
||||
expect(inputs).toHaveLength(6);
|
||||
});
|
||||
|
||||
it('handles 6-digit input with auto-focus', async () => {
|
||||
it("handles 6-digit input with auto-focus", async () => {
|
||||
renderVerifyEmail();
|
||||
|
||||
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
|
||||
fireEvent.change(inputs[0], { target: { value: '1' } });
|
||||
expect(inputs[0]).toHaveValue('1');
|
||||
fireEvent.change(inputs[0], { target: { value: "1" } });
|
||||
expect(inputs[0]).toHaveValue("1");
|
||||
|
||||
// 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();
|
||||
|
||||
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
|
||||
fireEvent.change(inputs[0], { target: { value: 'a' } });
|
||||
expect(inputs[0]).toHaveValue('');
|
||||
fireEvent.change(inputs[0], { target: { value: "a" } });
|
||||
expect(inputs[0]).toHaveValue("");
|
||||
|
||||
// Try typing numbers
|
||||
fireEvent.change(inputs[0], { target: { value: '5' } });
|
||||
expect(inputs[0]).toHaveValue('5');
|
||||
fireEvent.change(inputs[0], { target: { value: "5" } });
|
||||
expect(inputs[0]).toHaveValue("5");
|
||||
});
|
||||
|
||||
it('handles paste of 6-digit code', async () => {
|
||||
it("handles paste of 6-digit code", async () => {
|
||||
renderVerifyEmail();
|
||||
|
||||
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
|
||||
const pasteEvent = new Event('paste', { bubbles: true, cancelable: true }) as any;
|
||||
const pasteEvent = new Event("paste", {
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
}) as any;
|
||||
pasteEvent.clipboardData = {
|
||||
getData: () => '123456',
|
||||
getData: () => "123456",
|
||||
};
|
||||
|
||||
fireEvent(container!, pasteEvent);
|
||||
|
||||
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
|
||||
mockedVerifyEmail.mockImplementation(() => new Promise(() => {}));
|
||||
|
||||
renderVerifyEmail();
|
||||
|
||||
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)
|
||||
fireEvent.change(inputs[0], { target: { value: '1' } });
|
||||
fireEvent.change(inputs[1], { target: { value: '2' } });
|
||||
fireEvent.change(inputs[2], { target: { value: '3' } });
|
||||
fireEvent.change(inputs[3], { target: { value: '4' } });
|
||||
fireEvent.change(inputs[4], { target: { value: '5' } });
|
||||
fireEvent.change(inputs[0], { target: { value: "1" } });
|
||||
fireEvent.change(inputs[1], { target: { value: "2" } });
|
||||
fireEvent.change(inputs[2], { target: { value: "3" } });
|
||||
fireEvent.change(inputs[3], { target: { value: "4" } });
|
||||
fireEvent.change(inputs[4], { target: { value: "5" } });
|
||||
|
||||
// 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();
|
||||
|
||||
// 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
|
||||
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();
|
||||
|
||||
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();
|
||||
});
|
||||
|
||||
it('backspace moves focus to previous input', async () => {
|
||||
it("backspace moves focus to previous input", async () => {
|
||||
renderVerifyEmail();
|
||||
|
||||
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
|
||||
fireEvent.change(inputs[0], { target: { value: '1' } });
|
||||
fireEvent.change(inputs[1], { target: { value: '2' } });
|
||||
fireEvent.change(inputs[0], { target: { value: "1" } });
|
||||
fireEvent.change(inputs[1], { target: { value: "2" } });
|
||||
|
||||
// Clear second input and press backspace
|
||||
fireEvent.change(inputs[1], { target: { value: '' } });
|
||||
fireEvent.keyDown(inputs[1], { key: 'Backspace' });
|
||||
fireEvent.change(inputs[1], { target: { value: "" } });
|
||||
fireEvent.keyDown(inputs[1], { key: "Backspace" });
|
||||
|
||||
// The component handles this by focusing previous input
|
||||
});
|
||||
});
|
||||
|
||||
describe('Error Handling', () => {
|
||||
it('displays EXPIRED error message', async () => {
|
||||
describe("Error Handling", () => {
|
||||
it("displays EXPIRED error message", async () => {
|
||||
mockedVerifyEmail.mockRejectedValue({
|
||||
response: { data: { code: 'VERIFICATION_EXPIRED' } },
|
||||
response: { data: { code: "VERIFICATION_EXPIRED" } },
|
||||
});
|
||||
|
||||
renderVerifyEmail('?token=expired-token');
|
||||
renderVerifyEmail("?token=expired-token");
|
||||
|
||||
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({
|
||||
response: { data: { code: 'VERIFICATION_INVALID' } },
|
||||
response: { data: { code: "VERIFICATION_INVALID" } },
|
||||
});
|
||||
|
||||
renderVerifyEmail('?token=invalid-token');
|
||||
renderVerifyEmail("?token=invalid-token");
|
||||
|
||||
await waitFor(() => {
|
||||
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({
|
||||
response: { data: { code: 'TOO_MANY_ATTEMPTS' } },
|
||||
response: { data: { code: "TOO_MANY_ATTEMPTS" } },
|
||||
});
|
||||
|
||||
renderVerifyEmail('?token=blocked-token');
|
||||
renderVerifyEmail("?token=blocked-token");
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/too many attempts/i)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('displays ALREADY_VERIFIED error message', async () => {
|
||||
it("displays ALREADY_VERIFIED error message", async () => {
|
||||
mockedVerifyEmail.mockRejectedValue({
|
||||
response: { data: { code: 'ALREADY_VERIFIED' } },
|
||||
response: { data: { code: "ALREADY_VERIFIED" } },
|
||||
});
|
||||
|
||||
renderVerifyEmail('?token=already-verified-token');
|
||||
renderVerifyEmail("?token=already-verified-token");
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/already verified/i)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('clears input on error', async () => {
|
||||
it("clears input on error", async () => {
|
||||
mockedVerifyEmail.mockRejectedValue({
|
||||
response: { data: { code: 'VERIFICATION_INVALID' } },
|
||||
response: { data: { code: "VERIFICATION_INVALID" } },
|
||||
});
|
||||
|
||||
renderVerifyEmail();
|
||||
|
||||
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
|
||||
fireEvent.change(inputs[0], { target: { value: '1' } });
|
||||
fireEvent.change(inputs[1], { target: { value: '2' } });
|
||||
fireEvent.change(inputs[2], { target: { value: '3' } });
|
||||
fireEvent.change(inputs[3], { target: { value: '4' } });
|
||||
fireEvent.change(inputs[4], { target: { value: '5' } });
|
||||
fireEvent.change(inputs[5], { target: { value: '6' } });
|
||||
fireEvent.change(inputs[0], { target: { value: "1" } });
|
||||
fireEvent.change(inputs[1], { target: { value: "2" } });
|
||||
fireEvent.change(inputs[2], { target: { value: "3" } });
|
||||
fireEvent.change(inputs[3], { target: { value: "4" } });
|
||||
fireEvent.change(inputs[4], { target: { value: "5" } });
|
||||
fireEvent.change(inputs[5], { target: { value: "6" } });
|
||||
|
||||
// Wait for error message to appear
|
||||
await waitFor(() => {
|
||||
@@ -372,33 +406,35 @@ describe('VerifyEmail', () => {
|
||||
|
||||
// Inputs should be cleared after error
|
||||
await waitFor(() => {
|
||||
const updatedInputs = screen.getAllByRole('textbox');
|
||||
const updatedInputs = screen.getAllByRole("textbox");
|
||||
updatedInputs.forEach((input) => {
|
||||
expect(input).toHaveValue('');
|
||||
expect(input).toHaveValue("");
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Resend Verification', () => {
|
||||
it('shows resend button', async () => {
|
||||
describe("Resend Verification", () => {
|
||||
it("shows resend button", async () => {
|
||||
renderVerifyEmail();
|
||||
|
||||
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();
|
||||
|
||||
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);
|
||||
|
||||
await waitFor(() => {
|
||||
@@ -408,32 +444,32 @@ describe('VerifyEmail', () => {
|
||||
expect(mockedResendVerification).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('disables resend during cooldown', async () => {
|
||||
it("disables resend during cooldown", async () => {
|
||||
renderVerifyEmail();
|
||||
|
||||
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);
|
||||
|
||||
await waitFor(() => {
|
||||
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();
|
||||
});
|
||||
|
||||
it('shows success message after resend', async () => {
|
||||
it("shows success message after resend", async () => {
|
||||
renderVerifyEmail();
|
||||
|
||||
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);
|
||||
|
||||
await waitFor(() => {
|
||||
@@ -441,14 +477,14 @@ describe('VerifyEmail', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('counts down timer', async () => {
|
||||
it("counts down timer", async () => {
|
||||
renderVerifyEmail();
|
||||
|
||||
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);
|
||||
|
||||
await waitFor(() => {
|
||||
@@ -457,25 +493,30 @@ describe('VerifyEmail', () => {
|
||||
|
||||
// With shouldAdvanceTime: true, the timer will automatically count down
|
||||
// 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;
|
||||
const resendText = screen.getByRole("button", {
|
||||
name: /resend in \d+s/i,
|
||||
}).textContent;
|
||||
expect(resendText).toMatch(/Resend in [0-5][0-9]s/);
|
||||
}, { timeout: 3000 });
|
||||
},
|
||||
{ timeout: 3000 },
|
||||
);
|
||||
});
|
||||
|
||||
it('handles resend error for already verified', async () => {
|
||||
it("handles resend error for already verified", async () => {
|
||||
mockedResendVerification.mockRejectedValue({
|
||||
response: { data: { code: 'ALREADY_VERIFIED' } },
|
||||
response: { data: { code: "ALREADY_VERIFIED" } },
|
||||
});
|
||||
|
||||
renderVerifyEmail();
|
||||
|
||||
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);
|
||||
|
||||
await waitFor(() => {
|
||||
@@ -483,7 +524,7 @@ describe('VerifyEmail', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('handles rate limit error (429)', async () => {
|
||||
it("handles rate limit error (429)", async () => {
|
||||
mockedResendVerification.mockRejectedValue({
|
||||
response: { status: 429 },
|
||||
});
|
||||
@@ -491,39 +532,43 @@ describe('VerifyEmail', () => {
|
||||
renderVerifyEmail();
|
||||
|
||||
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);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/please wait before requesting/i)).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText(/please wait before requesting/i),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('Navigation', () => {
|
||||
it('has return to home link', async () => {
|
||||
describe("Navigation", () => {
|
||||
it("has return to home link", async () => {
|
||||
renderVerifyEmail();
|
||||
|
||||
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 });
|
||||
expect(homeLink).toHaveAttribute('href', '/');
|
||||
const homeLink = screen.getByRole("link", { name: /return to home/i });
|
||||
expect(homeLink).toHaveAttribute("href", "/");
|
||||
});
|
||||
|
||||
it('has go to home link on success', async () => {
|
||||
renderVerifyEmail('?token=valid-token');
|
||||
it("has go to home link on success", async () => {
|
||||
renderVerifyEmail("?token=valid-token");
|
||||
|
||||
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 });
|
||||
expect(homeLink).toHaveAttribute('href', '/');
|
||||
const homeLink = screen.getByRole("link", { name: /go to home page/i });
|
||||
expect(homeLink).toHaveAttribute("href", "/");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -5,8 +5,8 @@
|
||||
* direct uploads, and signed URL generation for private content.
|
||||
*/
|
||||
|
||||
import { vi, type Mocked } from 'vitest';
|
||||
import api from '../../services/api';
|
||||
import { vi, type Mocked } from "vitest";
|
||||
import api from "../../services/api";
|
||||
import {
|
||||
getPublicImageUrl,
|
||||
getPresignedUrl,
|
||||
@@ -16,10 +16,10 @@ import {
|
||||
uploadFile,
|
||||
getSignedUrl,
|
||||
PresignedUrlResponse,
|
||||
} from '../../services/uploadService';
|
||||
} from "../../services/uploadService";
|
||||
|
||||
// Mock the api module
|
||||
vi.mock('../../services/api');
|
||||
vi.mock("../../services/api");
|
||||
|
||||
const mockedApi = api as Mocked<typeof api>;
|
||||
|
||||
@@ -29,16 +29,22 @@ class MockXMLHttpRequest {
|
||||
|
||||
status = 200;
|
||||
readyState = 4;
|
||||
responseText = '';
|
||||
responseText = "";
|
||||
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;
|
||||
onerror: (() => void) | null = null;
|
||||
|
||||
private headers: Record<string, string> = {};
|
||||
private method = '';
|
||||
private url = '';
|
||||
private method = "";
|
||||
private url = "";
|
||||
|
||||
constructor() {
|
||||
MockXMLHttpRequest.instances.push(this);
|
||||
@@ -58,8 +64,16 @@ class MockXMLHttpRequest {
|
||||
// This allows promises to resolve without real delays
|
||||
Promise.resolve().then(() => {
|
||||
if (this.upload.onprogress) {
|
||||
this.upload.onprogress({ lengthComputable: true, loaded: 50, total: 100 });
|
||||
this.upload.onprogress({ lengthComputable: true, loaded: 100, total: 100 });
|
||||
this.upload.onprogress({
|
||||
lengthComputable: true,
|
||||
loaded: 50,
|
||||
total: 100,
|
||||
});
|
||||
this.upload.onprogress({
|
||||
lengthComputable: true,
|
||||
loaded: 100,
|
||||
total: 100,
|
||||
});
|
||||
}
|
||||
if (this.onload) {
|
||||
this.onload();
|
||||
@@ -84,181 +98,222 @@ class MockXMLHttpRequest {
|
||||
}
|
||||
|
||||
static getLastInstance() {
|
||||
return MockXMLHttpRequest.instances[MockXMLHttpRequest.instances.length - 1];
|
||||
return MockXMLHttpRequest.instances[
|
||||
MockXMLHttpRequest.instances.length - 1
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
// Store original XMLHttpRequest
|
||||
const originalXMLHttpRequest = global.XMLHttpRequest;
|
||||
|
||||
describe('Upload Service', () => {
|
||||
describe("Upload Service", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
MockXMLHttpRequest.reset();
|
||||
// Reset environment variables using stubEnv for Vitest
|
||||
vi.stubEnv('VITE_S3_BUCKET', 'test-bucket');
|
||||
vi.stubEnv('VITE_AWS_REGION', 'us-east-1');
|
||||
vi.stubEnv("VITE_S3_BUCKET", "test-bucket");
|
||||
vi.stubEnv("VITE_AWS_REGION", "us-east-1");
|
||||
// Mock XMLHttpRequest globally
|
||||
(global as unknown as { XMLHttpRequest: typeof MockXMLHttpRequest }).XMLHttpRequest = MockXMLHttpRequest;
|
||||
(
|
||||
global as unknown as { XMLHttpRequest: typeof MockXMLHttpRequest }
|
||||
).XMLHttpRequest = MockXMLHttpRequest;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
// Restore original XMLHttpRequest
|
||||
(global as unknown as { XMLHttpRequest: typeof XMLHttpRequest }).XMLHttpRequest = originalXMLHttpRequest;
|
||||
(
|
||||
global as unknown as { XMLHttpRequest: typeof XMLHttpRequest }
|
||||
).XMLHttpRequest = originalXMLHttpRequest;
|
||||
});
|
||||
|
||||
describe('getPublicImageUrl', () => {
|
||||
it('should return empty string for null input', () => {
|
||||
expect(getPublicImageUrl(null)).toBe('');
|
||||
describe("getPublicImageUrl", () => {
|
||||
it("should return empty string for null input", () => {
|
||||
expect(getPublicImageUrl(null)).toBe("");
|
||||
});
|
||||
|
||||
it('should return empty string for undefined input', () => {
|
||||
expect(getPublicImageUrl(undefined)).toBe('');
|
||||
it("should return empty string for undefined input", () => {
|
||||
expect(getPublicImageUrl(undefined)).toBe("");
|
||||
});
|
||||
|
||||
it('should return empty string for empty string input', () => {
|
||||
expect(getPublicImageUrl('')).toBe('');
|
||||
it("should return empty string for empty string input", () => {
|
||||
expect(getPublicImageUrl("")).toBe("");
|
||||
});
|
||||
|
||||
it('should return full S3 URL unchanged', () => {
|
||||
const fullUrl = 'https://bucket.s3.us-east-1.amazonaws.com/items/uuid.jpg';
|
||||
it("should return full S3 URL unchanged", () => {
|
||||
const fullUrl =
|
||||
"https://bucket.s3.us-east-1.amazonaws.com/items/uuid.jpg";
|
||||
expect(getPublicImageUrl(fullUrl)).toBe(fullUrl);
|
||||
});
|
||||
|
||||
it('should construct S3 URL from key', () => {
|
||||
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';
|
||||
it("should construct S3 URL from key", () => {
|
||||
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";
|
||||
expect(getPublicImageUrl(key)).toBe(expectedUrl);
|
||||
});
|
||||
|
||||
it('should handle profiles folder', () => {
|
||||
const key = 'profiles/550e8400-e29b-41d4-a716-446655440000.jpg';
|
||||
expect(getPublicImageUrl(key)).toContain('profiles/');
|
||||
it("should handle profiles folder", () => {
|
||||
const key = "profiles/550e8400-e29b-41d4-a716-446655440000.jpg";
|
||||
expect(getPublicImageUrl(key)).toContain("profiles/");
|
||||
});
|
||||
|
||||
it('should handle forum folder', () => {
|
||||
const key = 'forum/550e8400-e29b-41d4-a716-446655440000.jpg';
|
||||
expect(getPublicImageUrl(key)).toContain('forum/');
|
||||
it("should handle forum folder", () => {
|
||||
const key = "forum/550e8400-e29b-41d4-a716-446655440000.jpg";
|
||||
expect(getPublicImageUrl(key)).toContain("forum/");
|
||||
});
|
||||
});
|
||||
|
||||
describe('getPresignedUrl', () => {
|
||||
const mockFile = new File(['test content'], 'photo.jpg', { type: 'image/jpeg' });
|
||||
describe("getPresignedUrl", () => {
|
||||
const mockFile = new File(["test content"], "photo.jpg", {
|
||||
type: "image/jpeg",
|
||||
});
|
||||
const mockResponse: PresignedUrlResponse = {
|
||||
uploadUrl: 'https://presigned-url.s3.amazonaws.com/items/uuid.jpg?signature=abc',
|
||||
key: 'items/550e8400-e29b-41d4-a716-446655440000.jpg',
|
||||
uploadUrl:
|
||||
"https://presigned-url.s3.amazonaws.com/items/uuid.jpg?signature=abc",
|
||||
key: "items/550e8400-e29b-41d4-a716-446655440000.jpg",
|
||||
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(),
|
||||
};
|
||||
|
||||
it('should request presigned URL with correct parameters', async () => {
|
||||
it("should request presigned URL with correct parameters", async () => {
|
||||
mockedApi.post.mockResolvedValue({ data: mockResponse });
|
||||
|
||||
const result = await getPresignedUrl('item', mockFile);
|
||||
const result = await getPresignedUrl("item", mockFile);
|
||||
|
||||
expect(mockedApi.post).toHaveBeenCalledWith('/upload/presign', {
|
||||
uploadType: 'item',
|
||||
contentType: 'image/jpeg',
|
||||
fileName: 'photo.jpg',
|
||||
expect(mockedApi.post).toHaveBeenCalledWith("/upload/presign", {
|
||||
uploadType: "item",
|
||||
contentType: "image/jpeg",
|
||||
fileName: "photo.jpg",
|
||||
fileSize: mockFile.size,
|
||||
});
|
||||
expect(result).toEqual(mockResponse);
|
||||
});
|
||||
|
||||
it('should handle different upload types', async () => {
|
||||
it("should handle different upload types", async () => {
|
||||
mockedApi.post.mockResolvedValue({ data: mockResponse });
|
||||
|
||||
await getPresignedUrl('profile', mockFile);
|
||||
expect(mockedApi.post).toHaveBeenCalledWith('/upload/presign', expect.objectContaining({
|
||||
uploadType: 'profile',
|
||||
}));
|
||||
await getPresignedUrl("profile", mockFile);
|
||||
expect(mockedApi.post).toHaveBeenCalledWith(
|
||||
"/upload/presign",
|
||||
expect.objectContaining({
|
||||
uploadType: "profile",
|
||||
}),
|
||||
);
|
||||
|
||||
await getPresignedUrl('message', mockFile);
|
||||
expect(mockedApi.post).toHaveBeenCalledWith('/upload/presign', expect.objectContaining({
|
||||
uploadType: 'message',
|
||||
}));
|
||||
await getPresignedUrl("message", mockFile);
|
||||
expect(mockedApi.post).toHaveBeenCalledWith(
|
||||
"/upload/presign",
|
||||
expect.objectContaining({
|
||||
uploadType: "message",
|
||||
}),
|
||||
);
|
||||
|
||||
await getPresignedUrl('forum', mockFile);
|
||||
expect(mockedApi.post).toHaveBeenCalledWith('/upload/presign', expect.objectContaining({
|
||||
uploadType: 'forum',
|
||||
}));
|
||||
await getPresignedUrl("forum", mockFile);
|
||||
expect(mockedApi.post).toHaveBeenCalledWith(
|
||||
"/upload/presign",
|
||||
expect.objectContaining({
|
||||
uploadType: "forum",
|
||||
}),
|
||||
);
|
||||
|
||||
await getPresignedUrl('condition-check', mockFile);
|
||||
expect(mockedApi.post).toHaveBeenCalledWith('/upload/presign', expect.objectContaining({
|
||||
uploadType: 'condition-check',
|
||||
}));
|
||||
await getPresignedUrl("condition-check", mockFile);
|
||||
expect(mockedApi.post).toHaveBeenCalledWith(
|
||||
"/upload/presign",
|
||||
expect.objectContaining({
|
||||
uploadType: "condition-check",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('should propagate API errors', async () => {
|
||||
const error = new Error('API error');
|
||||
it("should propagate API errors", async () => {
|
||||
const error = new Error("API 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 = [
|
||||
new File(['test1'], 'photo1.jpg', { type: 'image/jpeg' }),
|
||||
new File(['test2'], 'photo2.png', { type: 'image/png' }),
|
||||
new File(["test1"], "photo1.jpg", { type: "image/jpeg" }),
|
||||
new File(["test2"], "photo2.png", { type: "image/png" }),
|
||||
];
|
||||
|
||||
const mockResponses: PresignedUrlResponse[] = [
|
||||
{
|
||||
uploadUrl: 'https://presigned-url1.s3.amazonaws.com',
|
||||
key: 'items/uuid1.jpg',
|
||||
uploadUrl: "https://presigned-url1.s3.amazonaws.com",
|
||||
key: "items/uuid1.jpg",
|
||||
stagingKey: null,
|
||||
publicUrl: 'https://bucket.s3.amazonaws.com/items/uuid1.jpg',
|
||||
publicUrl: "https://bucket.s3.amazonaws.com/items/uuid1.jpg",
|
||||
expiresAt: new Date().toISOString(),
|
||||
},
|
||||
{
|
||||
uploadUrl: 'https://presigned-url2.s3.amazonaws.com',
|
||||
key: 'items/uuid2.png',
|
||||
uploadUrl: "https://presigned-url2.s3.amazonaws.com",
|
||||
key: "items/uuid2.png",
|
||||
stagingKey: null,
|
||||
publicUrl: 'https://bucket.s3.amazonaws.com/items/uuid2.png',
|
||||
publicUrl: "https://bucket.s3.amazonaws.com/items/uuid2.png",
|
||||
expiresAt: new Date().toISOString(),
|
||||
},
|
||||
];
|
||||
|
||||
it('should request batch presigned URLs', async () => {
|
||||
mockedApi.post.mockResolvedValue({ data: { uploads: mockResponses, baseKey: 'base-key' } });
|
||||
it("should request batch presigned URLs", async () => {
|
||||
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', {
|
||||
uploadType: 'item',
|
||||
expect(mockedApi.post).toHaveBeenCalledWith("/upload/presign-batch", {
|
||||
uploadType: "item",
|
||||
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 () => {
|
||||
mockedApi.post.mockResolvedValue({ data: { uploads: [], baseKey: undefined } });
|
||||
it("should handle empty file array", async () => {
|
||||
mockedApi.post.mockResolvedValue({
|
||||
data: { uploads: [], baseKey: undefined },
|
||||
});
|
||||
|
||||
const result = await getPresignedUrls('item', []);
|
||||
const result = await getPresignedUrls("item", []);
|
||||
|
||||
expect(result).toEqual({ uploads: [], baseKey: undefined });
|
||||
});
|
||||
});
|
||||
|
||||
describe('uploadToS3', () => {
|
||||
const mockFile = new File(['test content'], 'photo.jpg', { type: 'image/jpeg' });
|
||||
const mockUploadUrl = 'https://presigned-url.s3.amazonaws.com/items/uuid.jpg?signature=abc';
|
||||
describe("uploadToS3", () => {
|
||||
const mockFile = new File(["test content"], "photo.jpg", {
|
||||
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);
|
||||
|
||||
const instance = MockXMLHttpRequest.getLastInstance();
|
||||
expect(instance.getMethod()).toBe('PUT');
|
||||
expect(instance.getMethod()).toBe("PUT");
|
||||
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();
|
||||
|
||||
await uploadToS3(mockFile, mockUploadUrl, { onProgress });
|
||||
@@ -269,37 +324,37 @@ describe('Upload Service', () => {
|
||||
expect(onProgress).toHaveBeenCalledWith(expect.any(Number));
|
||||
});
|
||||
|
||||
it('should export uploadToS3 function with correct signature', () => {
|
||||
expect(typeof uploadToS3).toBe('function');
|
||||
it("should export uploadToS3 function with correct signature", () => {
|
||||
expect(typeof uploadToS3).toBe("function");
|
||||
// Function accepts file, url, and optional options
|
||||
expect(uploadToS3.length).toBeGreaterThanOrEqual(2);
|
||||
});
|
||||
|
||||
it('should set correct content-type header', async () => {
|
||||
const pngFile = new File(['test'], 'image.png', { type: 'image/png' });
|
||||
it("should set correct content-type header", async () => {
|
||||
const pngFile = new File(["test"], "image.png", { type: "image/png" });
|
||||
await uploadToS3(pngFile, mockUploadUrl);
|
||||
|
||||
const instance = MockXMLHttpRequest.getLastInstance();
|
||||
expect(instance.getHeaders()['Content-Type']).toBe('image/png');
|
||||
expect(instance.getHeaders()["Content-Type"]).toBe("image/png");
|
||||
});
|
||||
});
|
||||
|
||||
describe('confirmUploads', () => {
|
||||
it('should confirm uploaded keys', async () => {
|
||||
const keys = ['items/uuid1.jpg', 'items/uuid2.jpg'];
|
||||
describe("confirmUploads", () => {
|
||||
it("should confirm uploaded keys", async () => {
|
||||
const keys = ["items/uuid1.jpg", "items/uuid2.jpg"];
|
||||
const mockResponse = { confirmed: keys, total: 2 };
|
||||
|
||||
mockedApi.post.mockResolvedValue({ data: mockResponse });
|
||||
|
||||
const result = await confirmUploads(keys);
|
||||
|
||||
expect(mockedApi.post).toHaveBeenCalledWith('/upload/confirm', { keys });
|
||||
expect(mockedApi.post).toHaveBeenCalledWith("/upload/confirm", { keys });
|
||||
expect(result).toEqual(mockResponse);
|
||||
});
|
||||
|
||||
it('should handle partial confirmation', async () => {
|
||||
const keys = ['items/uuid1.jpg', 'items/uuid2.jpg'];
|
||||
const mockResponse = { confirmed: ['items/uuid1.jpg'], total: 2 };
|
||||
it("should handle partial confirmation", async () => {
|
||||
const keys = ["items/uuid1.jpg", "items/uuid2.jpg"];
|
||||
const mockResponse = { confirmed: ["items/uuid1.jpg"], total: 2 };
|
||||
|
||||
mockedApi.post.mockResolvedValue({ data: mockResponse });
|
||||
|
||||
@@ -310,17 +365,19 @@ describe('Upload Service', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('uploadFile', () => {
|
||||
const mockFile = new File(['test content'], 'photo.jpg', { type: 'image/jpeg' });
|
||||
describe("uploadFile", () => {
|
||||
const mockFile = new File(["test content"], "photo.jpg", {
|
||||
type: "image/jpeg",
|
||||
});
|
||||
const presignResponse: PresignedUrlResponse = {
|
||||
uploadUrl: 'https://presigned.s3.amazonaws.com/items/uuid.jpg',
|
||||
key: 'items/uuid.jpg',
|
||||
uploadUrl: "https://presigned.s3.amazonaws.com/items/uuid.jpg",
|
||||
key: "items/uuid.jpg",
|
||||
stagingKey: null,
|
||||
publicUrl: 'https://bucket.s3.amazonaws.com/items/uuid.jpg',
|
||||
publicUrl: "https://bucket.s3.amazonaws.com/items/uuid.jpg",
|
||||
expiresAt: new Date().toISOString(),
|
||||
};
|
||||
|
||||
it('should complete full upload flow successfully', async () => {
|
||||
it("should complete full upload flow successfully", async () => {
|
||||
// Mock presign response
|
||||
mockedApi.post.mockResolvedValueOnce({ data: presignResponse });
|
||||
// Mock confirm response
|
||||
@@ -328,7 +385,7 @@ describe('Upload Service', () => {
|
||||
data: { confirmed: [presignResponse.key], total: 1 },
|
||||
});
|
||||
|
||||
const result = await uploadFile('item', mockFile);
|
||||
const result = await uploadFile("item", mockFile);
|
||||
|
||||
expect(result).toEqual({
|
||||
key: presignResponse.key,
|
||||
@@ -336,30 +393,32 @@ describe('Upload Service', () => {
|
||||
});
|
||||
|
||||
// Verify presign was called
|
||||
expect(mockedApi.post).toHaveBeenCalledWith('/upload/presign', {
|
||||
uploadType: 'item',
|
||||
contentType: 'image/jpeg',
|
||||
fileName: 'photo.jpg',
|
||||
expect(mockedApi.post).toHaveBeenCalledWith("/upload/presign", {
|
||||
uploadType: "item",
|
||||
contentType: "image/jpeg",
|
||||
fileName: "photo.jpg",
|
||||
fileSize: mockFile.size,
|
||||
});
|
||||
|
||||
// Verify confirm was called
|
||||
expect(mockedApi.post).toHaveBeenCalledWith('/upload/confirm', {
|
||||
expect(mockedApi.post).toHaveBeenCalledWith("/upload/confirm", {
|
||||
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 });
|
||||
// Mock confirm returning empty confirmed array
|
||||
mockedApi.post.mockResolvedValueOnce({
|
||||
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();
|
||||
|
||||
mockedApi.post.mockResolvedValueOnce({ data: presignResponse });
|
||||
@@ -367,16 +426,16 @@ describe('Upload Service', () => {
|
||||
data: { confirmed: [presignResponse.key], total: 1 },
|
||||
});
|
||||
|
||||
await uploadFile('item', mockFile, { onProgress });
|
||||
await uploadFile("item", mockFile, { onProgress });
|
||||
|
||||
// onProgress should have been called during XHR upload
|
||||
expect(onProgress).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should work with different upload types', async () => {
|
||||
it("should work with different upload types", async () => {
|
||||
const messagePresignResponse = {
|
||||
...presignResponse,
|
||||
key: 'messages/uuid.jpg',
|
||||
key: "messages/uuid.jpg",
|
||||
publicUrl: null, // Messages are private
|
||||
};
|
||||
|
||||
@@ -385,49 +444,54 @@ describe('Upload Service', () => {
|
||||
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(mockedApi.post).toHaveBeenCalledWith('/upload/presign', expect.objectContaining({
|
||||
uploadType: 'message',
|
||||
}));
|
||||
expect(result.key).toBe("messages/uuid.jpg");
|
||||
expect(mockedApi.post).toHaveBeenCalledWith(
|
||||
"/upload/presign",
|
||||
expect.objectContaining({
|
||||
uploadType: "message",
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
// Note: uploadFiles function was removed from uploadService and replaced with uploadImagesWithVariants
|
||||
// Tests for batch uploads would need to be updated to test the new function
|
||||
|
||||
describe('getSignedUrl', () => {
|
||||
it('should request signed URL for private content', async () => {
|
||||
const key = 'messages/uuid.jpg';
|
||||
const signedUrl = 'https://bucket.s3.amazonaws.com/messages/uuid.jpg?signature=abc';
|
||||
describe("getSignedUrl", () => {
|
||||
it("should request signed URL for private content", async () => {
|
||||
const key = "messages/uuid.jpg";
|
||||
const signedUrl =
|
||||
"https://bucket.s3.amazonaws.com/messages/uuid.jpg?signature=abc";
|
||||
|
||||
mockedApi.get.mockResolvedValue({ data: { url: signedUrl } });
|
||||
|
||||
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);
|
||||
});
|
||||
|
||||
it('should encode key in URL', async () => {
|
||||
const key = 'condition-checks/uuid with spaces.jpg';
|
||||
const signedUrl = 'https://bucket.s3.amazonaws.com/signed';
|
||||
it("should encode key in URL", async () => {
|
||||
const key = "condition-checks/uuid with spaces.jpg";
|
||||
const signedUrl = "https://bucket.s3.amazonaws.com/signed";
|
||||
|
||||
mockedApi.get.mockResolvedValue({ data: { url: signedUrl } });
|
||||
|
||||
await getSignedUrl(key);
|
||||
|
||||
expect(mockedApi.get).toHaveBeenCalledWith(
|
||||
`/upload/signed-url/${encodeURIComponent(key)}`
|
||||
`/upload/signed-url/${encodeURIComponent(key)}`,
|
||||
);
|
||||
});
|
||||
|
||||
it('should propagate API errors', async () => {
|
||||
const error = new Error('Unauthorized');
|
||||
it("should propagate API errors", async () => {
|
||||
const error = new Error("Unauthorized");
|
||||
mockedApi.get.mockRejectedValue(error);
|
||||
|
||||
await expect(getSignedUrl('messages/uuid.jpg')).rejects.toThrow('Unauthorized');
|
||||
await expect(getSignedUrl("messages/uuid.jpg")).rejects.toThrow(
|
||||
"Unauthorized",
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -34,7 +34,7 @@ const AlphaGate: React.FC = () => {
|
||||
const response = await axios.post(
|
||||
`${API_URL}/alpha/validate-code`,
|
||||
{ code: fullCode },
|
||||
{ withCredentials: true }
|
||||
{ withCredentials: true },
|
||||
);
|
||||
|
||||
if (response.data.success) {
|
||||
@@ -115,7 +115,7 @@ const AlphaGate: React.FC = () => {
|
||||
<p className="text-center text-muted small mb-0">
|
||||
Have an alpha code? Get started below! <br></br> Want to join?{" "}
|
||||
<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"
|
||||
style={{ color: "#667eea" }}
|
||||
>
|
||||
|
||||
@@ -77,9 +77,13 @@ const Owning: React.FC = () => {
|
||||
const [itemToDelete, setItemToDelete] = useState<Item | null>(null);
|
||||
const [showPaymentFailedModal, setShowPaymentFailedModal] = useState(false);
|
||||
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 [authRequiredRental, setAuthRequiredRental] = useState<Rental | null>(null);
|
||||
const [authRequiredRental, setAuthRequiredRental] = useState<Rental | null>(
|
||||
null,
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
fetchListings();
|
||||
@@ -89,7 +93,7 @@ const Owning: React.FC = () => {
|
||||
useEffect(() => {
|
||||
// Only fetch condition checks for rentals that will be displayed (pending/confirmed/active)
|
||||
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) {
|
||||
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
|
||||
const myItems = response.data.items.filter(
|
||||
(item: Item) => item.ownerId === user.id
|
||||
(item: Item) => item.ownerId === user.id,
|
||||
);
|
||||
setListings(myItems);
|
||||
} catch (err: any) {
|
||||
@@ -152,8 +156,8 @@ const Owning: React.FC = () => {
|
||||
});
|
||||
setListings(
|
||||
listings.map((i) =>
|
||||
i.id === item.id ? { ...i, isAvailable: !i.isAvailable } : i
|
||||
)
|
||||
i.id === item.id ? { ...i, isAvailable: !i.isAvailable } : i,
|
||||
),
|
||||
);
|
||||
} catch (err: any) {
|
||||
alert("Failed to update availability");
|
||||
@@ -189,7 +193,8 @@ const Owning: React.FC = () => {
|
||||
return;
|
||||
}
|
||||
const rentalIds = rentalsToFetch.map((r) => r.id);
|
||||
const response = await conditionCheckAPI.getBatchConditionChecks(rentalIds);
|
||||
const response =
|
||||
await conditionCheckAPI.getBatchConditionChecks(rentalIds);
|
||||
setConditionChecks(response.data.conditionChecks || []);
|
||||
} catch (err) {
|
||||
console.error("Failed to fetch condition checks:", err);
|
||||
@@ -203,7 +208,7 @@ const Owning: React.FC = () => {
|
||||
setIsProcessingPayment(rentalId);
|
||||
const response = await rentalAPI.updateRentalStatus(
|
||||
rentalId,
|
||||
"confirmed"
|
||||
"confirmed",
|
||||
);
|
||||
|
||||
// Check if payment processing was successful
|
||||
@@ -216,7 +221,6 @@ const Owning: React.FC = () => {
|
||||
}
|
||||
|
||||
fetchOwnerRentals();
|
||||
// Note: fetchAvailableChecks() removed - it will be triggered via ownerRentals useEffect
|
||||
|
||||
// Notify Navbar to update pending count
|
||||
window.dispatchEvent(new CustomEvent("rentalStatusChanged"));
|
||||
@@ -246,7 +250,7 @@ const Owning: React.FC = () => {
|
||||
alert(
|
||||
err.response?.data?.error ||
|
||||
err.response?.data?.details ||
|
||||
"Failed to accept rental request"
|
||||
"Failed to accept rental request",
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
@@ -263,8 +267,8 @@ const Owning: React.FC = () => {
|
||||
// Update the rental in the owner rentals list
|
||||
setOwnerRentals((prev) =>
|
||||
prev.map((rental) =>
|
||||
rental.id === updatedRental.id ? updatedRental : rental
|
||||
)
|
||||
rental.id === updatedRental.id ? updatedRental : rental,
|
||||
),
|
||||
);
|
||||
setShowDeclineModal(false);
|
||||
setRentalToDecline(null);
|
||||
@@ -279,8 +283,8 @@ const Owning: React.FC = () => {
|
||||
// Update the rental in the list
|
||||
setOwnerRentals((prev) =>
|
||||
prev.map((rental) =>
|
||||
rental.id === updatedRental.id ? updatedRental : rental
|
||||
)
|
||||
rental.id === updatedRental.id ? updatedRental : rental,
|
||||
),
|
||||
);
|
||||
|
||||
// Close the return status modal
|
||||
@@ -306,8 +310,8 @@ const Owning: React.FC = () => {
|
||||
// Update the rental in the owner rentals list
|
||||
setOwnerRentals((prev) =>
|
||||
prev.map((rental) =>
|
||||
rental.id === updatedRental.id ? updatedRental : rental
|
||||
)
|
||||
rental.id === updatedRental.id ? updatedRental : rental,
|
||||
),
|
||||
);
|
||||
setShowCancelModal(false);
|
||||
setRentalToCancel(null);
|
||||
@@ -321,7 +325,7 @@ const Owning: React.FC = () => {
|
||||
const handleConditionCheckSuccess = () => {
|
||||
// Refetch condition checks for displayed rentals
|
||||
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);
|
||||
fetchAvailableChecks(rentalIds);
|
||||
@@ -337,7 +341,7 @@ const Owning: React.FC = () => {
|
||||
if (!Array.isArray(availableChecks)) return [];
|
||||
return availableChecks.filter(
|
||||
(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)
|
||||
// Use displayStatus for filtering/sorting as it includes computed "active" status
|
||||
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) => {
|
||||
const statusOrder = { pending: 0, confirmed: 1, active: 2 };
|
||||
const aStatus = a.displayStatus || a.status;
|
||||
@@ -396,14 +402,20 @@ const Owning: React.FC = () => {
|
||||
{rental.item?.imageFilenames &&
|
||||
rental.item.imageFilenames[0] && (
|
||||
<img
|
||||
src={getImageUrl(rental.item.imageFilenames[0], 'thumbnail')}
|
||||
src={getImageUrl(
|
||||
rental.item.imageFilenames[0],
|
||||
"thumbnail",
|
||||
)}
|
||||
className="card-img-top"
|
||||
alt={rental.item.name}
|
||||
onError={(e) => {
|
||||
const target = e.currentTarget;
|
||||
if (!target.dataset.fallback && rental.item) {
|
||||
target.dataset.fallback = 'true';
|
||||
target.src = getImageUrl(rental.item.imageFilenames[0], 'original');
|
||||
target.dataset.fallback = "true";
|
||||
target.src = getImageUrl(
|
||||
rental.item.imageFilenames[0],
|
||||
"original",
|
||||
);
|
||||
}
|
||||
}}
|
||||
style={{
|
||||
@@ -435,14 +447,18 @@ const Owning: React.FC = () => {
|
||||
className={`badge ${
|
||||
(rental.displayStatus || rental.status) === "active"
|
||||
? "bg-success"
|
||||
: (rental.displayStatus || rental.status) === "pending"
|
||||
: (rental.displayStatus || rental.status) ===
|
||||
"pending"
|
||||
? "bg-warning"
|
||||
: (rental.displayStatus || rental.status) === "confirmed"
|
||||
: (rental.displayStatus || rental.status) ===
|
||||
"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)}
|
||||
</span>
|
||||
</div>
|
||||
@@ -478,7 +494,7 @@ const Owning: React.FC = () => {
|
||||
<small className="d-block text-muted mt-1">
|
||||
Processed:{" "}
|
||||
{new Date(
|
||||
rental.refundProcessedAt
|
||||
rental.refundProcessedAt,
|
||||
).toLocaleDateString()}
|
||||
</small>
|
||||
)}
|
||||
@@ -556,7 +572,8 @@ const Owning: React.FC = () => {
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{(rental.displayStatus || rental.status) === "confirmed" && (
|
||||
{(rental.displayStatus || rental.status) ===
|
||||
"confirmed" && (
|
||||
<button
|
||||
className="btn btn-sm btn-outline-danger"
|
||||
onClick={() => handleCancelClick(rental)}
|
||||
@@ -564,7 +581,8 @@ const Owning: React.FC = () => {
|
||||
Cancel
|
||||
</button>
|
||||
)}
|
||||
{(rental.displayStatus || rental.status) === "active" && (
|
||||
{(rental.displayStatus || rental.status) ===
|
||||
"active" && (
|
||||
<button
|
||||
className="btn btn-sm btn-success"
|
||||
onClick={() => handleCompleteClick(rental)}
|
||||
@@ -593,11 +611,11 @@ const Owning: React.FC = () => {
|
||||
: "Post-Rental Condition"}
|
||||
<small className="text-muted ms-2">
|
||||
{new Date(
|
||||
check.createdAt
|
||||
check.createdAt,
|
||||
).toLocaleDateString()}
|
||||
</small>
|
||||
</button>
|
||||
)
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
@@ -660,14 +678,17 @@ const Owning: React.FC = () => {
|
||||
>
|
||||
{item.imageFilenames && item.imageFilenames[0] && (
|
||||
<img
|
||||
src={getImageUrl(item.imageFilenames[0], 'thumbnail')}
|
||||
src={getImageUrl(item.imageFilenames[0], "thumbnail")}
|
||||
className="card-img-top"
|
||||
alt={item.name}
|
||||
onError={(e) => {
|
||||
const target = e.currentTarget;
|
||||
if (!target.dataset.fallback) {
|
||||
target.dataset.fallback = 'true';
|
||||
target.src = getImageUrl(item.imageFilenames[0], 'original');
|
||||
target.dataset.fallback = "true";
|
||||
target.src = getImageUrl(
|
||||
item.imageFilenames[0],
|
||||
"original",
|
||||
);
|
||||
}
|
||||
}}
|
||||
style={{
|
||||
|
||||
@@ -15,7 +15,7 @@ let failedQueue: Array<{
|
||||
|
||||
const processQueue = (
|
||||
error: AxiosError | null,
|
||||
token: string | null = null
|
||||
token: string | null = null,
|
||||
) => {
|
||||
failedQueue.forEach((prom) => {
|
||||
if (error) {
|
||||
@@ -95,7 +95,7 @@ api.interceptors.response.use(
|
||||
methods: errorData.methods,
|
||||
originalRequest,
|
||||
},
|
||||
})
|
||||
}),
|
||||
);
|
||||
return Promise.reject(error);
|
||||
}
|
||||
@@ -128,7 +128,6 @@ api.interceptors.response.use(
|
||||
const errorData = error.response?.data as any;
|
||||
|
||||
// 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
|
||||
if (
|
||||
(errorData?.code === "TOKEN_EXPIRED" ||
|
||||
@@ -167,7 +166,7 @@ api.interceptors.response.use(
|
||||
}
|
||||
|
||||
return Promise.reject(error);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
export const authAPI = {
|
||||
@@ -279,7 +278,7 @@ export const rentalAPI = {
|
||||
// Return status marking
|
||||
markReturn: (
|
||||
id: string,
|
||||
data: { status: string; actualReturnDateTime?: string }
|
||||
data: { status: string; actualReturnDateTime?: string },
|
||||
) => api.post(`/rentals/${id}/mark-return`, data),
|
||||
reportDamage: (id: string, data: any) =>
|
||||
api.post(`/rentals/${id}/report-damage`, data),
|
||||
@@ -338,7 +337,7 @@ export const forumAPI = {
|
||||
content: string;
|
||||
parentId?: string;
|
||||
imageFilenames?: string[];
|
||||
}
|
||||
},
|
||||
) => api.post(`/forum/posts/${postId}/comments`, data),
|
||||
updateComment: (commentId: string, data: any) =>
|
||||
api.put(`/forum/comments/${commentId}`, data),
|
||||
@@ -388,7 +387,7 @@ export const mapsAPI = {
|
||||
export const conditionCheckAPI = {
|
||||
submitConditionCheck: (
|
||||
rentalId: string,
|
||||
data: { checkType: string; imageFilenames: string[]; notes?: string }
|
||||
data: { checkType: string; imageFilenames: string[]; notes?: string },
|
||||
) => api.post(`/condition-checks/${rentalId}`, data),
|
||||
getBatchConditionChecks: (rentalIds: string[]) =>
|
||||
api.get(`/condition-checks/batch`, {
|
||||
|
||||
6088
lambdas/conditionCheckReminder/package-lock.json
generated
6088
lambdas/conditionCheckReminder/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -5,7 +5,7 @@
|
||||
"main": "index.js",
|
||||
"dependencies": {
|
||||
"@aws-sdk/client-scheduler": "^3.896.0",
|
||||
"@rentall/lambda-shared": "file:../shared"
|
||||
"@village-share/lambda-shared": "file:../shared"
|
||||
},
|
||||
"devDependencies": {
|
||||
"dotenv": "^17.2.3",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<!DOCTYPE html>
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
@@ -34,8 +34,9 @@
|
||||
min-width: 100%;
|
||||
height: 100%;
|
||||
background-color: #f8f9fa;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
|
||||
Oxygen, Ubuntu, Cantarell, sans-serif;
|
||||
font-family:
|
||||
-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu,
|
||||
Cantarell, sans-serif;
|
||||
line-height: 1.6;
|
||||
color: #212529;
|
||||
}
|
||||
@@ -257,7 +258,8 @@
|
||||
</p>
|
||||
<p>
|
||||
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>
|
||||
</div>
|
||||
|
||||
6494
lambdas/imageProcessor/package-lock.json
generated
6494
lambdas/imageProcessor/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -5,7 +5,7 @@
|
||||
"main": "index.js",
|
||||
"dependencies": {
|
||||
"@aws-sdk/client-s3": "^3.400.0",
|
||||
"@rentall/lambda-shared": "file:../shared",
|
||||
"@village-share/lambda-shared": "file:../shared",
|
||||
"exif-reader": "^2.0.0",
|
||||
"sharp": "^0.33.0"
|
||||
},
|
||||
|
||||
@@ -7,14 +7,15 @@
|
||||
* Example:
|
||||
* 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");
|
||||
|
||||
async function main() {
|
||||
// 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
|
||||
const stagingKey = args[0] || "staging/items/test-image.jpg";
|
||||
|
||||
5009
lambdas/payoutRetryProcessor/package-lock.json
generated
5009
lambdas/payoutRetryProcessor/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -4,7 +4,7 @@
|
||||
"description": "Lambda function to retry failed payouts via Stripe Connect",
|
||||
"main": "index.js",
|
||||
"dependencies": {
|
||||
"@rentall/lambda-shared": "file:../shared"
|
||||
"@village-share/lambda-shared": "file:../shared"
|
||||
},
|
||||
"devDependencies": {
|
||||
"dotenv": "^16.4.5"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* Shared utilities for Rentall Lambda functions.
|
||||
* Shared utilities for Village Share Lambda functions.
|
||||
*/
|
||||
|
||||
const db = require("./db/connection");
|
||||
|
||||
317
lambdas/shared/package-lock.json
generated
317
lambdas/shared/package-lock.json
generated
@@ -1,11 +1,11 @@
|
||||
{
|
||||
"name": "@rentall/lambda-shared",
|
||||
"name": "@village-share/lambda-shared",
|
||||
"version": "1.0.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@rentall/lambda-shared",
|
||||
"name": "@village-share/lambda-shared",
|
||||
"version": "1.0.0",
|
||||
"dependencies": {
|
||||
"@aws-sdk/client-scheduler": "^3.896.0",
|
||||
@@ -1216,40 +1216,6 @@
|
||||
"dev": true,
|
||||
"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": {
|
||||
"version": "8.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz",
|
||||
@@ -1687,19 +1653,6 @@
|
||||
"@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": {
|
||||
"version": "0.11.0",
|
||||
"resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz",
|
||||
@@ -2345,17 +2298,6 @@
|
||||
"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": {
|
||||
"version": "7.20.5",
|
||||
"resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz",
|
||||
@@ -2468,48 +2410,6 @@
|
||||
"dev": true,
|
||||
"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": {
|
||||
"version": "1.11.1",
|
||||
"resolved": "https://registry.npmjs.org/@unrs/resolver-binding-darwin-x64/-/resolver-binding-darwin-x64-1.11.1.tgz",
|
||||
@@ -2524,219 +2424,6 @@
|
||||
"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": {
|
||||
"version": "4.3.2",
|
||||
"resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@rentall/lambda-shared",
|
||||
"name": "@village-share/lambda-shared",
|
||||
"version": "1.0.0",
|
||||
"description": "Shared utilities for Rentall Lambda functions",
|
||||
"description": "Shared utilities for Village Share Lambda functions",
|
||||
"main": "index.js",
|
||||
"dependencies": {
|
||||
"@aws-sdk/client-ses": "^3.896.0",
|
||||
|
||||
Reference in New Issue
Block a user