Skip to content

Commit

Permalink
feat: auto cleanup subscription changes (#68)
Browse files Browse the repository at this point in the history
  • Loading branch information
anbraten committed Nov 7, 2023
1 parent 2a24d85 commit 0b30d13
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 12 deletions.
24 changes: 12 additions & 12 deletions packages/server/src/entities/subscription.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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),
Expand All @@ -65,6 +63,8 @@ export class Subscription {
subscription: this,
}),
);

this.cleanupChanges();
}

getPeriod(start: Date, end: Date): SubscriptionPeriod {
Expand Down
3 changes: 3 additions & 0 deletions packages/server/src/loop.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,9 @@ export async function chargeSubscriptions(): Promise<void> {
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);
Expand Down

0 comments on commit 0b30d13

Please sign in to comment.