public void execute(BillingEngineContext handlerContext) throws BillingException {
buildSubscriptionTree(handlerContext);
}
private void buildSubscriptionTree(BillingEngineContext handlerContext) throws BillingException {
DataAccessObject dataAccessObject = BillingManager.getInstance().getDataAccessObject();
// get the subscription from handler context
List<Subscription> subscriptions = handlerContext.getSubscriptions();
Map<Customer, List<Subscription>> customersSubscriptions =
new HashMap<Customer, List<Subscription>>();
for (Subscription subscription : subscriptions) {
Customer customer = subscription.getCustomer();
List<Subscription> customerSubscriptions = customersSubscriptions.get(customer);
if (customerSubscriptions == null) {
customerSubscriptions = new ArrayList<Subscription>();
}
customerSubscriptions.add(subscription);
customersSubscriptions.put(customer, customerSubscriptions);
}
// so iterating all the customers
for (Map.Entry<Customer, List<Subscription>> entry : customersSubscriptions.entrySet()) {
Customer customer = entry.getKey();
List<Subscription> customerSubscriptions = entry.getValue();
// create an empty invoice
Invoice invoice = new Invoice();
// get the last invoice for the customer
Invoice lastInvoice = dataAccessObject.getLastInvoice(customer);
if (lastInvoice != null) {
invoice.setBoughtForward(lastInvoice.getCarriedForward());
long lastInvoiceEnd = lastInvoice.getEndDate().getTime();
long currentInvoiceStart = lastInvoiceEnd + 1;
invoice.setStartDate(new Date(currentInvoiceStart));
} else {
invoice.setBoughtForward(new Cash("$0"));
// the earliest of the subscriptions
long earliestSubscriptionStart = -1;
for (Subscription subscription : customerSubscriptions) {
long subscriptionStartDate = subscription.getActiveSince().getTime();
if (earliestSubscriptionStart == -1 ||
subscriptionStartDate < earliestSubscriptionStart) {
earliestSubscriptionStart = subscriptionStartDate;
}
}
invoice.setStartDate(new Date(earliestSubscriptionStart));
}
Date currentDate = new Date();
SchedulerContext schedulerContext = handlerContext.getSchedulerContext();
if (schedulerContext != null && schedulerContext.getCurrentDurationEnd() != -1) {
invoice.setEndDate(new Date(schedulerContext.getCurrentDurationEnd()));
} else {
invoice.setEndDate(currentDate);
}
// this is the date the billing is initialized, this can be probably overwritten
invoice.setDate(currentDate);
// and we will count for the subscriptions for the invoice
invoice.setSubscriptions(customerSubscriptions);
// and then we will count on the un-billed purchases of all the subscriptions of the
// customer
Map<Integer, Payment> purchaseOrders = new HashMap<Integer, Payment>();
for (Subscription subscription : customerSubscriptions) {
dataAccessObject.fillUnbilledPayments(subscription, purchaseOrders, invoice );
}
for (Payment payment : purchaseOrders.values()) {
invoice.addPayment(payment);
}
customer.setActiveInvoice(invoice);