Skip to content

Commit

Permalink
Merge pull request #29 from beabee-communityrm/fix/dont-update-cancel…
Browse files Browse the repository at this point in the history
…ed-subs

fix: don't update cancelled or expired subscriptions
  • Loading branch information
wpf500 authored Jul 26, 2024
2 parents ad2615d + ba7d6b6 commit 1338001
Showing 1 changed file with 28 additions and 14 deletions.
42 changes: 28 additions & 14 deletions apps/backend/src/webhooks/handlers/stripe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,22 +170,36 @@ async function handleInvoiceCreated(invoice: Stripe.Invoice) {

const taxRateObj = getSalesTaxRateObject();
const invoiceTaxRateObj = invoice.default_tax_rates.map((rate) => rate.id);
// If they don't match, update the invoice and subscription (for next time)

// If tax rates match then there's nothing to do
if (
invoiceTaxRateObj.length !== taxRateObj.length ||
invoiceTaxRateObj.every((rate) => !taxRateObj.includes(rate))
invoiceTaxRateObj.length === taxRateObj.length &&
invoiceTaxRateObj.every((rate) => taxRateObj.includes(rate))
) {
const updateTaxRateObj = taxRateObj.length > 0 ? taxRateObj : "";
log.info("Updating tax rate on invoice " + invoice.id, {
oldTaxRate: invoiceTaxRateObj,
newTaxRate: updateTaxRateObj
});
await stripe.invoices.update(invoice.id, {
default_tax_rates: updateTaxRateObj
});
if (invoice.subscription) {
log.info("Updating tax rate on subscription " + invoice.subscription);
await stripe.subscriptions.update(invoice.subscription as string, {
return;
}

const updateTaxRateObj = taxRateObj.length > 0 ? taxRateObj : "";
log.info("Updating tax rate on invoice " + invoice.id, {
oldTaxRate: invoiceTaxRateObj,
newTaxRate: updateTaxRateObj
});
await stripe.invoices.update(invoice.id, {
default_tax_rates: updateTaxRateObj
});

// Update the subscription if it exists
if (invoice.subscription) {
const subscriptionId = invoice.subscription as string;
const subscription = await stripe.subscriptions.retrieve(subscriptionId);
if (
subscription.status !== "canceled" &&
subscription.status !== "incomplete_expired"
) {
log.info(
`Updating tax rate on subscription ${subscriptionId} with status ${subscription.status}`
);
await stripe.subscriptions.update(subscriptionId, {
default_tax_rates: updateTaxRateObj
});
}
Expand Down

0 comments on commit 1338001

Please sign in to comment.