From 0b30d137af1a8514e06b1f52063353354c35512b Mon Sep 17 00:00:00 2001 From: Anbraten Date: Tue, 7 Nov 2023 16:49:23 +0100 Subject: [PATCH] feat: auto cleanup subscription changes (#68) --- packages/server/src/entities/subscription.ts | 24 ++++++++++---------- packages/server/src/loop.ts | 3 +++ 2 files changed, 15 insertions(+), 12 deletions(-) diff --git a/packages/server/src/entities/subscription.ts b/packages/server/src/entities/subscription.ts index 422a28f..1b16e20 100644 --- a/packages/server/src/entities/subscription.ts +++ b/packages/server/src/entities/subscription.ts @@ -28,25 +28,15 @@ export class Subscription { Object.assign(this, data); } - /** - * End the current plan and start with a new one - * @param data.pricePerUnit Price per unit for the new plan - * @param data.units Units for the new plan - * @param data.changeDate Date when to end the current plan and start with a new one - */ - changePlan(data: { pricePerUnit: number; units: number; changeDate?: Date }): void { + cleanupChanges(): void { const changes = this.changes.getItems(); // set end date of existing changes if (changes.length > 0) { - if (!data.changeDate) { - throw new Error('changeDate is required if you already have a change'); - } - // sort changes in reverse order by start date changes.sort((a, b) => b.start.getTime() - a.start.getTime()); - let lastEnd = data.changeDate; + let lastEnd: Date | undefined = undefined; for (const change of changes) { if (!change.end) { change.end = lastEnd; @@ -56,7 +46,15 @@ export class Subscription { this.changes.set(changes); } + } + /** + * End the current plan and start with a new one + * @param data.pricePerUnit Price per unit for the new plan + * @param data.units Units for the new plan + * @param data.changeDate Date when to end the current plan and start with a new one + */ + changePlan(data: { pricePerUnit: number; units: number; changeDate?: Date }): void { this.changes.add( new SubscriptionChange({ start: this.changes.count() === 0 ? this.anchorDate : (data.changeDate as Date), @@ -65,6 +63,8 @@ export class Subscription { subscription: this, }), ); + + this.cleanupChanges(); } getPeriod(start: Date, end: Date): SubscriptionPeriod { diff --git a/packages/server/src/loop.ts b/packages/server/src/loop.ts index 80bedb5..883e33d 100644 --- a/packages/server/src/loop.ts +++ b/packages/server/src/loop.ts @@ -149,6 +149,9 @@ export async function chargeSubscriptions(): Promise { date: new Date(), }); + subscription.cleanupChanges(); + await database.em.persistAndFlush([subscription]); + const period = new SubscriptionPeriod(subscription, billingPeriod.start, billingPeriod.end); period.getInvoiceItems().forEach((item) => { invoice.items.add(item);