{"size": 1393, "ext": "js", "max_stars_repo_path": "private/lib/subscriptions/cancel_stripe_subscription_service.js", "max_stars_repo_name": "rohithreddy/MoonMail", "max_stars_repo_stars_event_min_datetime": "2019-04-15T12:04:13.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-15T12:04:13.000Z", "max_issues_repo_path": "private/lib/subscriptions/cancel_stripe_subscription_service.js", "max_issues_repo_name": "rohithreddy/MoonMail", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "private/lib/subscriptions/cancel_stripe_subscription_service.js", "max_forks_repo_name": "rohithreddy/MoonMail", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 1, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 31.6590909091, "max_line_length": 94, "alphanum_fraction": 0.704235463}
import { Promise } from 'bluebird';
import { logger } from '../index';
import { User } from '../models/user';

const stripe = require('stripe')(process.env.STRIPE_API_KEY);

export default class CancelStripeSubscriptionService {

  static cancel(userId) {
    return new CancelStripeSubscriptionService(userId).cancel();
  }

  constructor(userId) {
    this.userId = userId;
  }

  cancel() {
    return User.get(this.userId)
      .then(user => this._doCancel(user))
      .then(userSubscription => this._updateUserDetails(userSubscription))
      .catch((error) => {
        logger().error('= CancelStripeSubscriptionService.cancel', error);
        return Promise.reject(error);
      });
  }

  _doCancel(user) {
    return this._cancelStripeSubscription(user.stripeAccount.customerId)
      .then(subscription => Object.assign({}, { subscription }, { user }));
  }

  _cancelStripeSubscription(customerId) {
    logger().debug('= CancelStripeSubscriptionService._cancelStripeSubscription', customerId);
    // TODO: Improve this!
    // return stripe.customers.cancelSubscription(customerId, { at_period_end: true });
    return stripe.customers.cancelSubscription(customerId);
  }

  _updateUserDetails(userSubscription) {
    const { subscriptionId, ...newStripeData } = userSubscription.user.stripeAccount;
    return User.update({ stripeAccount: newStripeData }, this.userId);
  }
}
