3 final class PhortuneSubscriptionWorker
extends PhabricatorWorker
{
5 protected function doWork() {
6 $subscription = $this->loadSubscription();
8 $range = $this->getBillingPeriodRange($subscription);
9 list($last_epoch, $next_epoch) = $range;
11 $should_invoice = $subscription->shouldInvoiceForBillingPeriod(
14 if (!$should_invoice) {
18 $currency = $subscription->getCostForBillingPeriodAsCurrency(
21 if (!$currency->isPositive()) {
26 $account = $subscription->getAccount();
27 $merchant = $subscription->getMerchant();
29 $viewer = PhabricatorUser
::getOmnipotentUser();
31 $product = id(new PhortuneProductQuery())
33 ->withClassAndRef('PhortuneSubscriptionProduct', $subscription->getPHID())
36 $cart_implementation = id(new PhortuneSubscriptionCart())
37 ->setSubscription($subscription);
39 // TODO: This isn't really ideal. It would be better to use an application
40 // actor than a fairly arbitrary account member.
42 // However, for now, some of the stuff later in the pipeline requires a
43 // valid actor with a real PHID. The subscription should eventually be
44 // able to create these invoices "as" the application it is acting on
47 $members = id(new PhabricatorPeopleQuery())
49 ->withPHIDs($account->getMemberPHIDs())
53 $any_disabled = false;
54 foreach ($members as $member) {
56 // Don't act as a disabled user. If all of the users on the account are
57 // disabled this means we won't charge the subscription, but that's
58 // probably correct since it means no one can cancel or pay it anyway.
59 if ($member->getIsDisabled()) {
64 // For now, just pick the first valid user we encounter as the actor.
72 'All members of the account ("%s") for this subscription ("%s") '.
75 $subscription->getPHID());
76 } else if ($account->getMemberPHIDs()) {
78 'Unable to load any of the members of the account ("%s") for this '.
79 'subscription ("%s").',
81 $subscription->getPHID());
84 'The account ("%s") for this subscription ("%s") has no '.
87 $subscription->getPHID());
89 throw new PhabricatorWorkerPermanentFailureException($message);
92 $cart = $account->newCart($actor, $cart_implementation, $merchant);
94 $purchase = $cart->newPurchase($actor, $product);
97 ->setBasePriceAsCurrency($currency)
98 ->setMetadataValue('subscriptionPHID', $subscription->getPHID())
99 ->setMetadataValue('epoch.start', $last_epoch)
100 ->setMetadataValue('epoch.end', $next_epoch)
104 ->setSubscriptionPHID($subscription->getPHID())
108 $cart->activateCart();
111 $issues = $this->chargeSubscription($actor, $subscription, $cart);
112 } catch (Exception
$ex) {
115 'There was a technical error while trying to automatically bill '.
116 'this subscription: %s',
122 // We're all done; charging the cart sends a billing email as a side
127 // We're shoving this through the CartEditor because it has all the logic
128 // for sending mail about carts. This doesn't really affect the state of
129 // the cart, but reduces the amount of code duplication.
132 $xactions[] = id(new PhortuneCartTransaction())
133 ->setTransactionType(PhortuneCartTransaction
::TYPE_INVOICED
)
136 $content_source = PhabricatorContentSource
::newForSource(
137 PhabricatorPhortuneContentSource
::SOURCECONST
);
139 $acting_phid = id(new PhabricatorPhortuneApplication())->getPHID();
140 $editor = id(new PhortuneCartEditor())
142 ->setActingAsPHID($acting_phid)
143 ->setContentSource($content_source)
144 ->setContinueOnMissingFields(true)
145 ->setInvoiceIssues($issues)
146 ->applyTransactions($cart, $xactions);
150 private function chargeSubscription(
151 PhabricatorUser
$viewer,
152 PhortuneSubscription
$subscription,
153 PhortuneCart
$cart) {
156 if (!$subscription->getDefaultPaymentMethodPHID()) {
158 'There is no payment method associated with this subscription, so '.
159 'it could not be billed automatically. Add a default payment method '.
160 'to enable automatic billing.');
164 $method = id(new PhortunePaymentMethodQuery())
166 ->withPHIDs(array($subscription->getDefaultPaymentMethodPHID()))
169 PhortunePaymentMethod
::STATUS_ACTIVE
,
174 'The payment method associated with this subscription is invalid '.
175 'or out of date, so it could not be automatically billed. Update '.
176 'the default payment method to enable automatic billing.');
180 $provider = $method->buildPaymentProvider();
181 $charge = $cart->willApplyCharge($viewer, $provider, $method);
184 $provider->applyCharge($method, $charge);
185 } catch (Exception
$ex) {
186 $cart->didFailCharge($charge);
188 'Automatic billing failed: %s',
193 $cart->didApplyCharge($charge);
198 * Load the subscription to generate an invoice for.
200 * @return PhortuneSubscription The subscription to invoice.
202 private function loadSubscription() {
203 $viewer = PhabricatorUser
::getOmnipotentUser();
205 $data = $this->getTaskData();
206 $subscription_phid = idx($data, 'subscriptionPHID');
208 $subscription = id(new PhortuneSubscriptionQuery())
210 ->withPHIDs(array($subscription_phid))
212 if (!$subscription) {
213 throw new PhabricatorWorkerPermanentFailureException(
215 'Failed to load subscription with PHID "%s".',
216 $subscription_phid));
219 return $subscription;
224 * Get the start and end epoch timestamps for this billing period.
226 * @param PhortuneSubscription The subscription being billed.
227 * @return pair<int, int> Beginning and end of the billing range.
229 private function getBillingPeriodRange(PhortuneSubscription
$subscription) {
230 $data = $this->getTaskData();
232 $last_epoch = idx($data, 'trigger.last-epoch');
234 // If this is the first time the subscription is firing, use the
235 // creation date as the start of the billing period.
236 $last_epoch = $subscription->getDateCreated();
238 $this_epoch = idx($data, 'trigger.this-epoch');
240 if (!$last_epoch ||
!$this_epoch) {
241 throw new PhabricatorWorkerPermanentFailureException(
242 pht('Subscription is missing billing period information.'));
245 $period_length = ($this_epoch - $last_epoch);
246 if ($period_length <= 0) {
247 throw new PhabricatorWorkerPermanentFailureException(
249 'Subscription has invalid billing period.'));
252 if (empty($data['manual'])) {
253 if (PhabricatorTime
::getNow() < $this_epoch) {
256 'Refusing to generate a subscription invoice for a billing period '.
257 'which ends in the future.'));
261 return array($last_epoch, $this_epoch);