private void verify(Expectation expected) throws AssertionFailedError {
      user = api.getUserWS(user.getUserId());
      order = api.getOrder(order.getId());

      logger.info(S("user: {}", userDetailsAsString(user)));
      logger.info(S("order: {}", orderDetailsAsString(order)));
      boolean isOk;
      isOk =
          assertEqualsBilling(
              S("userId: {}.", user.getId()), expected.nextInvoiceDate, user.getNextInvoiceDate());
      if (!isOk) {
        failed = true;
        return;
      }
      isOk =
          assertEqualsBilling(
              S("orderId: {}.", order.getId()),
              expected.nextBillableDay,
              order.getNextBillableDay());
      if (!isOk) {
        failed = true;
        return;
      }

      if (null != expected.invoiceTotal) {
        verifyInvoice(expected);
      }
    }
  /**
   * To add a line to an order
   *
   * @param order
   * @param lineQty
   * @param lineTypeId
   * @param lineItemId
   * @param linePrice
   * @param description
   * @return
   */
  public static OrderWS addLine(
      OrderWS order,
      Integer lineQty,
      Integer lineTypeId,
      Integer lineItemId,
      BigDecimal linePrice,
      String description) {

    // store the existing lines
    OrderLineWS[] existingLines = order.getOrderLines();
    List<OrderLineWS> finalLines = new ArrayList<OrderLineWS>();
    // iterate over the array and add to the ArrayList
    if (null != existingLines) {
      for (OrderLineWS oneItem : existingLines) {
        finalLines.add(oneItem);
      }
    }
    // Now add some 1 line
    OrderLineWS line;
    line = new OrderLineWS();
    line.setTypeId(lineTypeId);
    line.setItemId(lineItemId);
    if (null != linePrice) {
      line.setPrice(linePrice);
    }
    line.setAmount(linePrice);
    line.setQuantity(lineQty);
    line.setDescription(description);
    finalLines.add(line);
    OrderLineWS[] simpleArray = new OrderLineWS[finalLines.size()];
    finalLines.toArray(simpleArray);
    order.setOrderLines(simpleArray);
    return order;
  }
 public void verify(Date date) throws AssertionFailedError {
   if (failed) {
     logger.debug(
         S("userId: {}, orderId: {}. skip failed scenario", user.getId(), order.getId()));
     return;
   }
   if (expectations.containsKey(date)) {
     verify(expectations.get(date));
   } else {
     logger.debug(
         S(
             "userId: {}, orderId: {}. no expectation for billing at {}",
             user.getId(),
             order.getId(),
             date));
   }
 }
  public static OrderWS createOrderObject(
      Integer userId,
      Integer currencyId,
      Integer billingType,
      Integer orderPeriod,
      Date activeSince) {
    /*
     * Create
     */
    OrderWS newOrder = new OrderWS();

    newOrder.setUserId(userId);
    newOrder.setCurrencyId(currencyId);
    newOrder.setBillingTypeId(billingType);
    newOrder.setPeriod(orderPeriod);

    // Defaults
    newOrder.setNotes("Domain: www.test.com");

    newOrder.setActiveSince(activeSince);
    //         On some branches this field is present, please uncomment if required
    //        newOrder.setCycleStarts(cal.getTime());

    return newOrder;
  }
Example #5
0
  public void testCreateInvoiceFromOrder() throws Exception {
    JbillingAPI api = JbillingAPIFactory.getAPI();

    final Integer USER_ID = 10730; // user has no orders

    // setup orders
    OrderWS order = new OrderWS();
    order.setUserId(USER_ID);
    order.setBillingTypeId(Constants.ORDER_BILLING_PRE_PAID);
    order.setPeriod(1); // once
    order.setCurrencyId(1);
    order.setActiveSince(new Date());

    OrderLineWS line = new OrderLineWS();
    line.setTypeId(Constants.ORDER_LINE_TYPE_ITEM);
    line.setDescription("Order line");
    line.setItemId(1);
    line.setQuantity(1);
    line.setPrice(new BigDecimal("10.00"));
    line.setAmount(new BigDecimal("10.00"));

    order.setOrderLines(new OrderLineWS[] {line});

    // create orders
    Integer orderId1 = api.createOrder(order);
    Integer orderId2 = api.createOrder(order);

    // generate invoice using first order
    Integer invoiceId = api.createInvoiceFromOrder(orderId1, null);

    assertNotNull("Order 1 created", orderId1);
    assertNotNull("Order 2 created", orderId2);
    assertNotNull("Invoice created", invoiceId);

    Integer[] invoiceIds = api.getLastInvoices(USER_ID, 2);
    assertEquals("Only 1 invoice was generated", 1, invoiceIds.length);

    InvoiceWS invoice = api.getInvoiceWS(invoiceId);
    assertEquals("Invoice total is $10.00", new BigDecimal("10.00"), invoice.getTotalAsDecimal());
    assertEquals("Only 1 order invoiced", 1, invoice.getOrders().length);
    assertEquals("Invoice generated from 1st order", orderId1, invoice.getOrders()[0]);

    // add second order to invoice
    Integer invoiceId2 = api.createInvoiceFromOrder(orderId2, invoiceId);
    assertEquals("Order added to the same invoice", invoiceId, invoiceId2);

    invoiceIds = api.getLastInvoices(USER_ID, 2);
    assertEquals("Still only 1 invoice generated", 1, invoiceIds.length);

    invoice = api.getInvoiceWS(invoiceId);
    assertEquals("Invoice total is $20.00", new BigDecimal("20.00"), invoice.getTotalAsDecimal());
    assertEquals("2 orders invoiced", 2, invoice.getOrders().length);

    // cleanup
    api.deleteInvoice(invoiceId);
    api.deleteOrder(orderId1);
    api.deleteOrder(orderId2);
  }
 public void applyChanges(Date date) {
   if (failed) {
     logger.debug(
         S("userId: {}, orderId: {}. skip failed scenario", user.getId(), order.getId()));
     return;
   }
   if (changes.containsKey(date)) {
     for (TestOrderChangeBuilder change : changes.get(date)) {
       change.buildNewAndApply();
     }
   } else {
     logger.debug(
         S(
             "userId: {}, orderId: {}. no changes before billing at {}",
             user.getId(),
             order.getId(),
             date));
   }
 }
  public void testWrongPluginParameters() throws JbillingAPIException, IOException {
    long currentTimeMillis = System.currentTimeMillis();
    UserWS user = SureTaxCompositionTaskTest.createUser(currentTimeMillis, "");
    // Create an item with wrong Transaction Type code
    Integer itemId1 =
        CreateObjectUtil.createItem(
            "Long Distance Call intra-state", "1.5", currentTimeMillis + "", "2201", api);
    ItemDTOEx item1 = api.getItem(itemId1, null, null);
    MetaFieldValueWS[] metaFields = new MetaFieldValueWS[1];
    MetaFieldValueWS transTypeMetaField = new MetaFieldValueWS();
    transTypeMetaField.setStringValue("010101");
    transTypeMetaField.setFieldName("Transaction Type Code");
    metaFields[0] = transTypeMetaField;
    item1.setMetaFields(metaFields);
    api.updateItem(item1);
    // purchase order with taxable items
    Calendar cal = Calendar.getInstance();
    // I want to set the active since to 07 June 2012 , so the billing
    // process sees it and invoices it
    // set the calendar to 06/07
    cal.set(2010, 5, 7);
    OrderWS order =
        CreateObjectUtil.createOrderObject(
            user.getUserId(), 1, ServerConstants.ORDER_BILLING_POST_PAID, 1, cal.getTime());

    CreateObjectUtil.addLine(
        order,
        10,
        ServerConstants.ORDER_LINE_TYPE_ITEM,
        itemId1,
        new BigDecimal(1.5),
        "Long Distance Call-intra state");

    order.setDueDateUnitId(PeriodUnitDTO.DAY);
    order.setDueDateValue(0); // order due

    order.setId(api.createOrder(order)); // create order
    order = api.getOrder(order.getId());
    assertNotNull("order created", order.getId());

    Integer[] invoiceIds = null;
    try {
      invoiceIds =
          api.createInvoiceWithDate(
              user.getUserId(),
              new Date(),
              PeriodUnitDTO.DAY,
              45,
              false); // getAllInvoicesForUser(user.getUserId());
    } catch (Exception e) {
      if (e instanceof SessionInternalError && e.getMessage().contains("Invalid Validation Key")) {
        // do nothing
      } else {
        assertTrue("Wrong exception raised", false);
      }
    }
    assertNull("No invoices must be generated", invoiceIds);
  }
 private String orderDetailsAsString(OrderWS order) {
   order = api.getOrder(order.getId());
   return S(
       "order[{}]:type: {}, period: {}, activeSince: {}, nextBillableDay: {}",
       order.getId(),
       order.getBillingTypeStr(),
       order.getPeriodStr(),
       order.getActiveSince(),
       order.getNextBillableDay());
 }
    private void verifyInvoice(Expectation expected) throws AssertionFailedError {
      if (failed) {
        return;
      }
      Integer[] invoiceIds = api.getLastInvoices(order.getUserId(), 1);
      InvoiceWS invoice = api.getInvoiceWS(invoiceIds[0]);

      boolean isOk;
      isOk =
          assertEqualsBilling(
              S("invoiceId: {}.", invoice.getId()),
              expected.invoiceTotal,
              invoice.getBalanceAsDecimal().setScale(2));
      if (!isOk) {
        failed = true;
        return;
      }

      InvoiceLineDTO[] lines = invoice.getInvoiceLines();
      // TODO verify invoice line content
    }
Example #10
0
  public OrderWS buildOrder(int userId, List<Integer> itemIds, BigDecimal linePrice) {
    OrderWS order = new OrderWS();
    order.setUserId(userId);
    order.setBillingTypeId(Constants.ORDER_BILLING_POST_PAID);
    order.setPeriod(ORDER_PERIOD_ONCE); // once
    order.setCurrencyId(CURRENCY_USD);
    order.setActiveSince(new Date());
    order.setProrateFlag(Boolean.FALSE);

    ArrayList<OrderLineWS> lines = new ArrayList<OrderLineWS>(itemIds.size());
    for (int i = 0; i < itemIds.size(); i++) {
      OrderLineWS nextLine = new OrderLineWS();
      nextLine.setTypeId(Constants.ORDER_LINE_TYPE_ITEM);
      nextLine.setDescription("Order line: " + i);
      nextLine.setItemId(itemIds.get(i));
      nextLine.setQuantity(1);
      nextLine.setPrice(linePrice);
      nextLine.setAmount(nextLine.getQuantityAsDecimal().multiply(linePrice));

      lines.add(nextLine);
    }
    order.setOrderLines(lines.toArray(new OrderLineWS[lines.size()]));
    return order;
  }
Example #11
0
  /** Tests the PaymentRouterCurrencyTask. */
  @Test
  public void testPaymentRouterCurrencyTask() {
    // prepare
    UserWS userUSD = buildUser(PRANCING_PONY_ACCOUNT_TYPE);
    userUSD.setCurrencyId(CURRENCY_USD);
    userUSD.setId(api.createUser(userUSD));

    UserWS userAUD = buildUser(PRANCING_PONY_ACCOUNT_TYPE);
    userAUD.setCurrencyId(CURRENCY_AUD);
    userAUD.setId(api.createUser(userAUD));

    ItemTypeWS itemType = buildItemType();
    itemType.setId(api.createItemCategory(itemType));

    ItemDTOEx item = buildItem(itemType.getId(), api.getCallerCompanyId());
    item.setId(api.createItem(item));

    // testing
    OrderWS order = buildOrder(userUSD.getId(), Arrays.asList(item.getId()), new BigDecimal("10"));
    order.setCurrencyId(userUSD.getCurrencyId());

    // create the order and invoice it
    System.out.println("Creating and invoicing order ...");
    Integer invoiceIdUSD =
        api.createOrderAndInvoice(
            order, OrderChangeBL.buildFromOrder(order, ORDER_CHANGE_STATUS_APPLY));
    Integer orderIdUSD = api.getLastOrders(userUSD.getId(), 1)[0];

    // try paying the invoice in USD
    System.out.println("Making payment in USD...");
    PaymentAuthorizationDTOEx authInfo = api.payInvoice(invoiceIdUSD);

    assertTrue("USD Payment should be successful", authInfo.getResult().booleanValue());
    assertEquals(
        "Should be processed by 'first_fake_processor'",
        authInfo.getProcessor(),
        "first_fake_processor");

    // create a new order in AUD and invoice it
    order.setUserId(userAUD.getId());
    order.setCurrencyId(userAUD.getCurrencyId());

    System.out.println("Creating and invoicing order ...");
    Integer invoiceIdAUD =
        api.createOrderAndInvoice(
            order, OrderChangeBL.buildFromOrder(order, ORDER_CHANGE_STATUS_APPLY));
    Integer orderIdAUD = api.getLastOrders(userAUD.getId(), 1)[0];

    // try paying the invoice in AUD
    System.out.println("Making payment in AUD...");
    authInfo = api.payInvoice(invoiceIdAUD);

    assertTrue("AUD Payment should be successful", authInfo.getResult().booleanValue());
    assertEquals(
        "Should be processed by 'second_fake_processor'",
        authInfo.getProcessor(),
        "second_fake_processor");

    // remove invoices and orders
    System.out.println("Deleting invoices and orders.");
    api.deleteInvoice(invoiceIdUSD);
    api.deleteInvoice(invoiceIdAUD);
    api.deleteOrder(orderIdUSD);
    api.deleteOrder(orderIdAUD);
    api.deleteUser(userUSD.getId());
    api.deleteUser(userAUD.getId());
    api.deleteItem(item.getId());
    api.deleteItemCategory(itemType.getId());
  }
Example #12
0
  /**
   * Tests that when a past due invoice is processed it will generate a new invoice for the current
   * period that contains all previously un-paid balances as the carried balance.
   *
   * <p>Invoices that have been carried still show the original balance for reporting/paper-trail
   * purposes, but will not be re-processed by the system as part of the normal billing process.
   *
   * @throws Exception
   */
  public void testCreateWithCarryOver() throws Exception {
    final Integer USER_ID = 10743; // user has one past-due invoice to be carried forward
    final Integer OVERDUE_INVOICE_ID = 70; // holds a $20 balance

    JbillingAPI api = JbillingAPIFactory.getAPI();

    // new order witha  single line item
    OrderWS order = new OrderWS();
    order.setUserId(USER_ID);
    order.setBillingTypeId(Constants.ORDER_BILLING_PRE_PAID);
    order.setPeriod(1); // once
    order.setCurrencyId(1);
    order.setActiveSince(new Date());

    OrderLineWS line = new OrderLineWS();
    line.setTypeId(Constants.ORDER_LINE_TYPE_ITEM);
    line.setDescription("Order line");
    line.setItemId(1);
    line.setQuantity(1);
    line.setPrice(new BigDecimal("10.00"));
    line.setAmount(new BigDecimal("10.00"));

    order.setOrderLines(new OrderLineWS[] {line});

    // create order
    Integer orderId = api.createOrder(order);

    // create invoice
    Integer invoiceId = api.createInvoice(USER_ID, false)[0];

    // validate that the overdue invoice has been carried forward to the newly created invoice
    InvoiceWS overdue = api.getInvoiceWS(OVERDUE_INVOICE_ID);

    assertEquals(
        "Status updated to 'unpaid and carried'",
        Constants.INVOICE_STATUS_UNPAID_AND_CARRIED,
        overdue.getStatusId());
    assertEquals("Carried invoice will not be re-processed", 0, overdue.getToProcess().intValue());
    assertEquals(
        "Overdue invoice holds original balance",
        new BigDecimal("20.00"),
        overdue.getBalanceAsDecimal());

    assertEquals(
        "Overdue invoice delegated to the newly created invoice",
        invoiceId,
        overdue.getDelegatedInvoiceId());

    // validate that the newly created invoice contains the carried balance
    InvoiceWS invoice = api.getInvoiceWS(invoiceId);

    assertEquals(
        "New invoice balance is equal to the current period charges",
        new BigDecimal("10.00"),
        invoice.getBalanceAsDecimal());
    assertEquals(
        "New invoice holds the carried balance equal to the old invoice balance",
        overdue.getBalanceAsDecimal(),
        invoice.getCarriedBalanceAsDecimal());
    assertEquals(
        "New invoice total is equal to the current charges plus the carried total",
        new BigDecimal("30.00"),
        invoice.getTotalAsDecimal());
  }
Example #13
0
  public void testCreateInvoice() {
    try {
      final Integer USER_ID = 10730; // user has no orders
      JbillingAPI api = JbillingAPIFactory.getAPI();

      // setup order
      OrderWS order = new OrderWS();
      order.setUserId(USER_ID);
      order.setBillingTypeId(Constants.ORDER_BILLING_PRE_PAID);
      order.setPeriod(1); // once
      order.setCurrencyId(1);
      order.setActiveSince(new Date());

      OrderLineWS line = new OrderLineWS();
      line.setTypeId(Constants.ORDER_LINE_TYPE_ITEM);
      line.setDescription("Order line");
      line.setItemId(1);
      line.setQuantity(1);
      line.setPrice(new BigDecimal("10.00"));
      line.setAmount(new BigDecimal("10.00"));

      order.setOrderLines(new OrderLineWS[] {line});

      /*
       * Test invoicing of one-time and recurring orders
       */

      // create 1st order
      Integer orderId1 = api.createOrder(order);

      // create 2nd order
      line.setPrice(new BigDecimal("20.00"));
      line.setAmount(new BigDecimal("20.00"));
      Integer orderId2 = api.createOrder(order);

      // create invoice
      Integer[] invoices = api.createInvoice(USER_ID, false);

      assertEquals("Number of invoices returned", 1, invoices.length);
      InvoiceWS invoice = api.getInvoiceWS(invoices[0]);

      assertNull("Invoice is not delegated.", invoice.getDelegatedInvoiceId());
      assertEquals(
          "Invoice does not have a carried balance.",
          BigDecimal.ZERO,
          invoice.getCarriedBalanceAsDecimal());

      Integer[] invoicedOrderIds = invoice.getOrders();
      assertEquals("Number of orders invoiced", 2, invoicedOrderIds.length);
      Arrays.sort(invoicedOrderIds);
      assertEquals("Order 1 invoiced", orderId1, invoicedOrderIds[0]);
      assertEquals("Order 2 invoiced", orderId2, invoicedOrderIds[1]);
      assertEquals("Total is 30.0", new BigDecimal("30.00"), invoice.getTotalAsDecimal());

      // clean up
      api.deleteInvoice(invoices[0]);
      api.deleteOrder(orderId1);
      api.deleteOrder(orderId2);

      /*
       * Test only recurring order can generate invoice.
       */

      // one-time order
      line.setPrice(new BigDecimal("2.00"));
      line.setAmount(new BigDecimal("2.00"));
      orderId1 = api.createOrder(order);

      // try to create invoice, but none should be returned
      invoices = api.createInvoice(USER_ID, true);

      // Note: CXF returns null for empty array
      if (invoices != null) {
        assertEquals("Number of invoices returned", 0, invoices.length);
      }

      // recurring order
      order.setPeriod(2); // monthly
      line.setPrice(new BigDecimal("3.00"));
      line.setAmount(new BigDecimal("3.00"));
      orderId2 = api.createOrder(order);

      // create invoice
      invoices = api.createInvoice(USER_ID, true);

      assertEquals("Number of invoices returned", 1, invoices.length);
      invoice = api.getInvoiceWS(invoices[0]);
      invoicedOrderIds = invoice.getOrders();
      assertEquals("Number of orders invoiced", 2, invoicedOrderIds.length);
      Arrays.sort(invoicedOrderIds);
      assertEquals("Order 1 invoiced", orderId1, invoicedOrderIds[0]);
      assertEquals("Order 2 invoiced", orderId2, invoicedOrderIds[1]);
      assertEquals("Total is 5.0", new BigDecimal("5.00"), invoice.getTotalAsDecimal());

      // clean up
      api.deleteInvoice(invoices[0]);
      api.deleteOrder(orderId1);
      api.deleteOrder(orderId2);

    } catch (Exception e) {
      e.printStackTrace();
      fail("Exception caught:" + e);
    }
  }