/**
  * This method is pretty heavy ... it should be useing a cached mapped.
  *
  * @param userId
  * @param permission
  */
 protected void validatePermission(Integer userId, Integer permission) {
   UserBL user;
   user = new UserBL(userId);
   UserDTOEx dto = new UserDTOEx();
   dto.setAllPermissions(user.getPermissions());
   if (!dto.isGranted(permission)) {
     throw new SecurityException("Permission " + permission + " not grated for " + userId);
   }
 }
 /**
  * Adds a quantity of items to the given order for the given item id.
  *
  * @param order order to add item to
  * @param itemId id of item to add
  * @param quantity quantity to add
  * @param persist save changes immediately if true
  */
 public static void addItem(OrderDTO order, Integer itemId, BigDecimal quantity, boolean persist) {
   UserBL user = new UserBL(order.getUserId());
   addItem(
       itemId,
       quantity,
       user.getLanguage(),
       order.getUserId(),
       order.getCurrencyId(),
       order,
       null,
       persist);
 }
 /**
  * Adds a quantity of items to the given order for the given item id. Use the given price for the
  * addition.
  *
  * @param order order to add item to
  * @param itemId id of item to add
  * @param quantity quantity to add
  */
 public static void addItem(OrderDTO order, Integer itemId, Integer quantity, BigDecimal price) {
   UserBL user = new UserBL(order.getUserId());
   OrderLineDTO line = new OrderLineDTO();
   line.setItemId(itemId);
   line.setQuantity(quantity);
   line.setPrice(price);
   addItem(
       itemId,
       new BigDecimal(quantity),
       user.getLanguage(),
       order.getUserId(),
       order.getCurrencyId(),
       order,
       line,
       false);
 }
Esempio n. 4
0
  public InvoiceDTO getDTOEx(Integer languageId, boolean forDisplay) {

    if (!forDisplay) {
      return invoice;
    }

    InvoiceDTO invoiceDTO = new InvoiceDTO(invoice);
    // make sure that the lines are properly ordered
    List<InvoiceLineDTO> orderdLines = new ArrayList<InvoiceLineDTO>(invoiceDTO.getInvoiceLines());
    Collections.sort(orderdLines, new InvoiceLineComparator());
    invoiceDTO.setInvoiceLines(orderdLines);

    UserBL userBl = new UserBL(invoice.getBaseUser());
    Locale locale = userBl.getLocale();
    ResourceBundle bundle = ResourceBundle.getBundle("entityNotifications", locale);

    // now add headres and footers if this invoices has subaccount
    // lines
    if (invoiceDTO.hasSubAccounts()) {
      addHeadersFooters(orderdLines, bundle);
    }
    // add a grand total final line
    InvoiceLineDTO total = new InvoiceLineDTO();
    total.setDescription(bundle.getString("invoice.line.total"));
    total.setAmount(invoice.getTotal());
    total.setIsPercentage(0);
    invoiceDTO.getInvoiceLines().add(total);

    // add some currency info for the human
    CurrencyBL currency = new CurrencyBL(invoice.getCurrency().getId());
    if (languageId != null) {
      invoiceDTO.setCurrencyName(currency.getEntity().getDescription(languageId));
    }
    invoiceDTO.setCurrencySymbol(currency.getEntity().getSymbol());

    return invoiceDTO;
  }
  public boolean process(PaymentDTOEx paymentInfo) throws PluggableTaskException {
    FormatLogger log = new FormatLogger(Logger.getLogger(PaymentEmailAuthorizeNetTask.class));
    boolean retValue = super.process(paymentInfo);
    String address = (String) parameters.get(PARAMETER_EMAIL_ADDRESS.getName());
    try {
      UserBL user = new UserBL(paymentInfo.getUserId());
      String message;
      if (new Integer(paymentInfo.getPaymentResult().getId()).equals(Constants.RESULT_OK)) {
        message = "payment.success";
      } else {
        message = "payment.fail";
      }
      String params[] = new String[6];
      params[0] = paymentInfo.getUserId().toString();
      params[1] = user.getEntity().getUserName();
      params[2] = paymentInfo.getId() + "";
      params[3] = paymentInfo.getAmount().toString();
      if (paymentInfo.getAuthorization() != null) {
        params[4] = paymentInfo.getAuthorization().getTransactionId();
        params[5] = paymentInfo.getAuthorization().getApprovalCode();
      } else {
        params[4] = "Not available";
        params[5] = "Not available";
      }
      log.debug(
          "Bkp 6 " + params[0] + " " + params[1] + " " + params[2] + " " + params[3] + " "
              + params[4] + " " + params[5] + " ");
      NotificationBL.sendSapienterEmail(
          address, user.getEntity().getEntity().getId(), message, null, params);
    } catch (Exception e) {

      log.warn("Cant send receit email");
    }

    return retValue;
  }
  public static void addLine(OrderDTO order, OrderLineDTO line, boolean persist) {
    if (persist)
      throw new IllegalArgumentException("persist is oboleted"); // TODO remove the argument
    UserBL user = new UserBL(order.getUserId());
    OrderLineDTO oldLine = order.getLine(line.getItemId());
    if (oldLine != null) {
      // get a copy of the old line
      oldLine = new OrderLineDTO(oldLine);
    }

    addItem(
        line.getItemId(),
        line.getQuantity(),
        user.getLanguage(),
        order.getUserId(),
        order.getCurrencyId(),
        order,
        line,
        persist);

    if (persist) {
      // generate NewQuantityEvent
      OrderLineDTO newLine = order.getLine(line.getItemId());
      OrderBL orderBl = new OrderBL();
      List<OrderLineDTO> oldLines = new ArrayList<OrderLineDTO>(1);
      List<OrderLineDTO> newLines = new ArrayList<OrderLineDTO>(1);
      if (oldLine != null) {
        oldLines.add(oldLine);
      }
      newLines.add(newLine);
      LOG.debug("Old line: %s", oldLine);
      LOG.debug("New line: %s", newLine);
      orderBl.checkOrderLineQuantities(
          oldLines, newLines, user.getEntity().getEntity().getId(), order.getId(), true);
    }
  }
Esempio n. 7
0
  public static final AccountTypeWS getWS(AccountTypeDTO dto) {

    return getWS(
        dto.getId(),
        dto.getCompany().getId(),
        dto.getInvoiceDesign(),
        dto.getDateCreated(),
        dto.getCreditNotificationLimit1(),
        dto.getCreditNotificationLimit2(),
        dto.getCreditLimit(),
        dto.getInvoiceDeliveryMethod(),
        dto.getCurrencyId(),
        dto.getLanguageId(),
        dto.getDescription(),
        UserBL.convertMainSubscriptionToWS(dto.getBillingCycle()),
        dto.getInformationTypes(),
        dto.getPaymentMethodTypes(),
        dto.getPreferredNotificationAitId());
  }
Esempio n. 8
0
  public static final AccountTypeDTO getDTO(AccountTypeWS ws, Integer entityId) {

    AccountTypeDTO accountTypeDTO = new AccountTypeDTO();
    if (ws.getId() != null && ws.getId() > 0) {
      accountTypeDTO.setId(ws.getId());
    }

    accountTypeDTO.setCompany(new CompanyDTO(entityId));

    accountTypeDTO.setCreditLimit(ws.getCreditLimitAsDecimal());
    accountTypeDTO.setCreditNotificationLimit1(ws.getCreditNotificationLimit1AsDecimal());
    accountTypeDTO.setCreditNotificationLimit2(ws.getCreditNotificationLimit2AsDecimal());
    accountTypeDTO.setInvoiceDesign(ws.getInvoiceDesign());
    accountTypeDTO.setBillingCycle(
        UserBL.convertMainSubscriptionFromWS(ws.getMainSubscription(), entityId));
    accountTypeDTO.setLanguage(new LanguageDAS().find(ws.getLanguageId()));
    accountTypeDTO.setCurrency(new CurrencyDAS().find(ws.getCurrencyId()));
    accountTypeDTO.setInvoiceDeliveryMethod(
        new InvoiceDeliveryMethodDTO(ws.getInvoiceDeliveryMethodId()));
    accountTypeDTO.setPreferredNotificationAitId(ws.getpreferredNotificationAitId());
    // set payment method types
    if (ws.getPaymentMethodTypeIds() != null) {
      Set<PaymentMethodTypeDTO> paymentMethodTypes = new HashSet<PaymentMethodTypeDTO>(0);
      PaymentMethodTypeDAS das = new PaymentMethodTypeDAS();

      for (Integer paymentMethodTypeId : ws.getPaymentMethodTypeIds()) {
        paymentMethodTypes.add(das.find(paymentMethodTypeId));
      }
      accountTypeDTO.setPaymentMethodTypes(paymentMethodTypes);
    }
    List<PaymentMethodTypeDTO> globalPaymentMethods =
        new PaymentMethodTypeDAS().findByAllAccountType(entityId);
    for (PaymentMethodTypeDTO globalPaymentMethod : globalPaymentMethods) {
      accountTypeDTO.getPaymentMethodTypes().add(globalPaymentMethod);
    }
    return accountTypeDTO;
  }
Esempio n. 9
0
  /**
   * @param userId
   * @param newInvoice
   * @param process It can be null.
   */
  public void create(
      Integer userId, NewInvoiceDTO newInvoice, BillingProcessDTO process, Integer executorUserId) {
    // find out the entity id
    PreferenceBL pref = new PreferenceBL();
    UserBL user = null;
    Integer entityId;
    if (process != null) {
      entityId = process.getEntity().getId();
    } else {
      // this is a manual invoice, there's no billing process
      user = new UserBL(userId);
      entityId = user.getEntityId(userId);
    }

    // verify if this entity is using the 'continuous invoice date'
    // preference
    try {
      pref.set(entityId, Constants.PREFERENCE_CONTINUOUS_DATE);

      if (StringUtils.isNotBlank(pref.getString())) {
        Date lastDate = com.sapienter.jbilling.common.Util.parseDate(pref.getString());
        LOG.debug("Last date invoiced: " + lastDate);

        if (lastDate.after(newInvoice.getBillingDate())) {
          LOG.debug(
              "Due date is before the last recorded date. Moving due date forward for continuous invoice dates.");
          newInvoice.setBillingDate(lastDate);

        } else {
          // update the lastest date only if this is not a review
          if (newInvoice.getIsReview() == null || newInvoice.getIsReview() == 0) {
            pref.createUpdateForEntity(
                entityId,
                Constants.PREFERENCE_CONTINUOUS_DATE,
                com.sapienter.jbilling.common.Util.parseDate(newInvoice.getBillingDate()));
          }
        }
      }
    } catch (EmptyResultDataAccessException e) {
      // not interested, ignore
    }

    // in any case, ensure that the due date is => that invoice date
    if (newInvoice.getDueDate().before(newInvoice.getBillingDate())) {
      LOG.debug("Due date before billing date, moving date up to billing date.");
      newInvoice.setDueDate(newInvoice.getBillingDate());
    }

    // ensure that there are only so many decimals in the invoice
    int decimals = Constants.BIGDECIMAL_SCALE;
    try {
      pref.set(entityId, Constants.PREFERENCE_INVOICE_DECIMALS);
      decimals = pref.getInt();
    } catch (EmptyResultDataAccessException e) {
      // not interested, ignore
    }

    LOG.debug("Rounding " + newInvoice.getTotal() + " to " + decimals + " decimals");
    if (newInvoice.getTotal() != null) {
      newInvoice.setTotal(newInvoice.getTotal().setScale(decimals, Constants.BIGDECIMAL_ROUND));
    }
    if (newInvoice.getBalance() != null) {
      newInvoice.setBalance(newInvoice.getBalance().setScale(decimals, Constants.BIGDECIMAL_ROUND));
    }

    // some API calls only accept ID's and do not pass meta-fields
    // update and validate meta-fields if they've been populated
    if (newInvoice.getMetaFields() != null && !newInvoice.getMetaFields().isEmpty()) {
      newInvoice.updateMetaFieldsWithValidation(entityId, newInvoice);
    }

    // create the invoice row
    invoice = invoiceDas.create(userId, newInvoice, process);

    // add delegated/included invoice links
    if (newInvoice.getIsReview() == 0) {
      for (InvoiceDTO dto : newInvoice.getInvoices()) {
        dto.setInvoice(invoice);
      }
    }

    // add the customer notes if it applies
    try {
      pref.set(entityId, Constants.PREFERENCE_SHOW_NOTE_IN_INVOICE);
    } catch (EmptyResultDataAccessException e) {
      // use the default then
    }

    if (pref.getInt() == 1) {
      if (user == null) {
        user = new UserBL(userId);
      }
      if (user.getEntity().getCustomer() != null
          && user.getEntity().getCustomer().getNotes() != null) {
        // append the notes if there's some text already there
        newInvoice.setCustomerNotes(
            (newInvoice.getCustomerNotes() == null)
                ? user.getEntity().getCustomer().getNotes()
                : newInvoice.getCustomerNotes() + " " + user.getEntity().getCustomer().getNotes());
      }
    }
    // notes might come from the customer, the orders, or both
    if (newInvoice.getCustomerNotes() != null && newInvoice.getCustomerNotes().length() > 0) {
      invoice.setCustomerNotes(newInvoice.getCustomerNotes());
    }

    // calculate/compose the number
    String numberStr = null;
    if (newInvoice.getIsReview() != null && newInvoice.getIsReview() == 1) {
      // invoices for review will be seen by the entity employees
      // so the entity locale will be used
      EntityBL entity = new EntityBL(entityId);
      ResourceBundle bundle = ResourceBundle.getBundle("entityNotifications", entity.getLocale());
      numberStr = bundle.getString("invoice.review.number");
    } else if (newInvoice.getPublicNumber() == null || newInvoice.getPublicNumber().length() == 0) {
      String prefix;
      try {
        pref.set(entityId, Constants.PREFERENCE_INVOICE_PREFIX);
        prefix = pref.getString();
        if (prefix == null) {
          prefix = "";
        }
      } catch (EmptyResultDataAccessException e) {
        prefix = "";
      }
      int number;
      try {
        pref.set(entityId, Constants.PREFERENCE_INVOICE_NUMBER);
        number = pref.getInt();
      } catch (EmptyResultDataAccessException e1) {
        number = 1;
      }

      numberStr = prefix + number;
      // update for the next time
      number++;
      pref.createUpdateForEntity(entityId, Constants.PREFERENCE_INVOICE_NUMBER, number);
    } else { // for upload of legacy invoices
      numberStr = newInvoice.getPublicNumber();
    }

    invoice.setPublicNumber(numberStr);

    // set the invoice's contact info with the current user's primary
    ContactBL contact = new ContactBL();
    contact.set(userId);
    contact.createForInvoice(contact.getDTO(), invoice.getId());

    // add a log row for convenience
    if (null != executorUserId) {
      eLogger.audit(
          executorUserId,
          userId,
          Constants.TABLE_INVOICE,
          invoice.getId(),
          EventLogger.MODULE_INVOICE_MAINTENANCE,
          EventLogger.ROW_CREATED,
          null,
          null,
          null);
    } else {
      eLogger.auditBySystem(
          entityId,
          userId,
          Constants.TABLE_INVOICE,
          invoice.getId(),
          EventLogger.MODULE_INVOICE_MAINTENANCE,
          EventLogger.ROW_CREATED,
          null,
          null,
          null);
    }
  }
Esempio n. 10
0
  private boolean processOrdersForUser(
      UserDTO user,
      Integer entityId,
      BillingProcessDTO process,
      boolean isReview,
      boolean onlyRecurring,
      boolean useProcessDateForInvoice,
      int maximumPeriods,
      Hashtable<TimePeriod, NewInvoiceDTO> newInvoices) {

    boolean includedOrders = false;
    Integer userId = user.getUserId();

    LOG.debug("Processing orders for user " + userId);

    // initialize the subaccounts iterator if this user is a parent
    Iterator subAccountsIt = null;
    if (user.getCustomer().getIsParent() != null
        && user.getCustomer().getIsParent().intValue() == 1) {
      UserBL parent = new UserBL(userId);
      subAccountsIt = parent.getEntity().getCustomer().getChildren().iterator();
    }

    // get the orders that might be processable for this user
    OrderDAS orderDas = new OrderDAS();
    Collection<OrderDTO> orders = orderDas.findByUser_Status(userId, Constants.ORDER_STATUS_ACTIVE);

    // go through each of them, and update the DTO if it applies
    for (OrderDTO order : orders) {
      LOG.debug("Processing order :" + order.getId());
      // apply any order processing filter pluggable task
      try {
        PluggableTaskManager taskManager =
            new PluggableTaskManager(entityId, Constants.PLUGGABLE_TASK_ORDER_FILTER);
        OrderFilterTask task = (OrderFilterTask) taskManager.getNextClass();
        boolean isProcessable = true;
        while (task != null) {
          isProcessable = task.isApplicable(order, process);
          if (!isProcessable) {
            break; // no need to keep doing more tests
          }
          task = (OrderFilterTask) taskManager.getNextClass();
        }

        // include this order only if it complies with all the
        // rules
        if (isProcessable) {

          LOG.debug("Order processable");

          if (onlyRecurring) {
            if (order.getOrderPeriod().getId() != Constants.ORDER_PERIOD_ONCE) {
              includedOrders = true;
              LOG.debug("It is not one-timer. " + "Generating invoice");
            }
          } else {
            includedOrders = true;
          }
          /*
           * now find if there is already an invoice being
           * generated for the given due date period
           */
          // find the due date that applies to this order
          OrderBL orderBl = new OrderBL();
          orderBl.set(order);
          TimePeriod dueDatePeriod = orderBl.getDueDate();
          // look it up in the hashtable
          NewInvoiceDTO thisInvoice = (NewInvoiceDTO) newInvoices.get(dueDatePeriod);
          if (thisInvoice == null) {
            LOG.debug(
                "Adding new invoice for period "
                    + dueDatePeriod
                    + " process date:"
                    + process.getBillingDate());
            // we need a new one with this period
            // define the invoice date
            thisInvoice = new NewInvoiceDTO();
            if (useProcessDateForInvoice) {
              thisInvoice.setDate(process.getBillingDate());
            } else {
              thisInvoice.setDate(
                  orderBl.getInvoicingDate(),
                  order.getOrderPeriod().getId() != Constants.ORDER_PERIOD_ONCE);
            }
            thisInvoice.setIsReview(isReview ? new Integer(1) : new Integer(0));
            thisInvoice.setCarriedBalance(BigDecimal.ZERO);
            thisInvoice.setDueDatePeriod(dueDatePeriod);
          } else {
            LOG.debug("invoice found for period " + dueDatePeriod);
            if (!useProcessDateForInvoice) {
              thisInvoice.setDate(
                  orderBl.getInvoicingDate(),
                  order.getOrderPeriod().getId() != Constants.ORDER_PERIOD_ONCE);
            }
          }
          /*
           * The order periods plug-in might not add any period. This should not happen
           * but if it does, the invoice should not be included
           */
          if (addOrderToInvoice(
              entityId, order, thisInvoice, process.getBillingDate(), maximumPeriods)) {
            // add or replace
            newInvoices.put(dueDatePeriod, thisInvoice);
          }
          LOG.debug("After putting period there are " + newInvoices.size() + " periods.");

          // here it would be easy to update this order
          // to_process and
          // next_billable_time. I can't do that because these
          // fields
          // will be read by the following tasks, and they
          // will asume
          // they are not modified.
        }

      } catch (PluggableTaskException e) {
        LOG.fatal("Problems handling order filter task.", e);
        throw new SessionInternalError("Problems handling order filter task.");
      } catch (TaskException e) {
        LOG.fatal("Problems excecuting order filter task.", e);
        throw new SessionInternalError("Problems executing order filter task.");
      }
    } // for - all the orders for this user

    // see if there is any subaccounts to include in this invoice
    while (subAccountsIt != null) { // until there are no more subaccounts (subAccountsIt != null) {
      CustomerDTO customer = null;
      while (subAccountsIt.hasNext()) {
        customer = (CustomerDTO) subAccountsIt.next();
        if (customer.getInvoiceChild() == null || customer.getInvoiceChild().intValue() == 0) {
          break;
        } else {
          LOG.debug("Subaccount not included in parent's invoice " + customer.getId());
          customer = null;
        }
      }
      if (customer != null) {
        userId = customer.getBaseUser().getUserId();
        // if the child does not have any orders to invoice, this should
        // not affect the current value of includedOrders
        if (processOrdersForUser(
            customer.getBaseUser(),
            entityId,
            process,
            isReview,
            onlyRecurring,
            useProcessDateForInvoice,
            maximumPeriods,
            newInvoices)) {
          // if ANY child has orders to invoice, it is enough for includedOrders to be true
          includedOrders = true;
        }
        LOG.debug("Now processing subaccount " + userId);

      } else {
        subAccountsIt = null;
        LOG.debug("No more subaccounts to process");
      }
    }

    return includedOrders;
  }