Persist nextBillingDate on subscription create/update; unset on cancel or downgrade to free. Account page displays the cached date and lazily refreshes from Helcim when the cached value is within 24h of now (or missing).
59 lines
1.7 KiB
JavaScript
59 lines
1.7 KiB
JavaScript
// Cancel member subscription
|
|
import Member from "../../models/member.js";
|
|
import { cancelHelcimSubscription } from "../../utils/helcim.js";
|
|
|
|
export default defineEventHandler(async (event) => {
|
|
try {
|
|
const member = await requireAuth(event);
|
|
|
|
// If already on free tier, nothing to cancel
|
|
if (member.contributionTier === "0" || !member.helcimSubscriptionId) {
|
|
return {
|
|
success: true,
|
|
message: "No active subscription to cancel",
|
|
status: member.status,
|
|
contributionTier: member.contributionTier,
|
|
};
|
|
}
|
|
|
|
try {
|
|
await cancelHelcimSubscription(member.helcimSubscriptionId);
|
|
} catch (cancelError) {
|
|
console.error("Error canceling Helcim subscription:", cancelError);
|
|
// Continue anyway - we'll update the member record
|
|
}
|
|
|
|
// Update member status — pending_payment (not cancelled) so member can re-subscribe
|
|
await Member.findByIdAndUpdate(
|
|
member._id,
|
|
{
|
|
$set: {
|
|
status: 'pending_payment',
|
|
contributionTier: '0',
|
|
helcimSubscriptionId: null,
|
|
paymentMethod: 'none',
|
|
subscriptionEndDate: new Date(),
|
|
},
|
|
$unset: { nextBillingDate: 1 },
|
|
},
|
|
{ runValidators: false }
|
|
);
|
|
|
|
logActivity(member._id, 'subscription_cancelled', {
|
|
effectiveDate: new Date().toISOString()
|
|
})
|
|
|
|
return {
|
|
success: true,
|
|
message: "Subscription cancelled successfully",
|
|
status: 'pending_payment',
|
|
contributionTier: '0',
|
|
};
|
|
} catch (error) {
|
|
console.error("Error cancelling subscription:", error);
|
|
throw createError({
|
|
statusCode: error.statusCode || 500,
|
|
statusMessage: error.message || "Failed to cancel subscription",
|
|
});
|
|
}
|
|
});
|