public void addExpense(Expense exp) {
   SQLiteDatabase db = this.getWritableDatabase();
   ContentValues values = new ContentValues();
   values.put(KEY_NAME, exp.getName());
   values.put(KEY_DATE, exp.getDate());
   values.put(KEY_SPENT_FOR, exp.getSpentFor());
   values.put(KEY_COMMENT, exp.getComment());
   values.put(KEY_AMT, exp.getAmt());
   db.insert(TABLE_EXPENSES, null, values);
   db.close();
 };
  @Test
  public void shouldGetTotalExpenseWithSameDate() {
    Expense oneHundredDollarInDayOne = new Expense(1, new Money(100, Currency.USD));
    Expense oneHundredEuroInDayOne = new Expense(1, new Money(100, Currency.EUR));
    List<Expense> expenseList = new ArrayList<Expense>();
    expenseList.add(oneHundredDollarInDayOne);
    expenseList.add(oneHundredEuroInDayOne);
    Expense totalExpense = new Expense(1, null);

    Money totalMoney = totalExpense.calculateExpense(expenseList);
    Money expectedMoney = new Money(256, Currency.USD);

    assertThat(totalMoney, is(expectedMoney));
  }
  public static void expenseParticipants(Long id, String query) {
    Expense expense = Expense.findById(id);
    List<User> users = null;
    if (query != null && !query.isEmpty()) {
      users = User.findByNickNameExcludeExpense(query, expense, new Pagination(1, 10));
    }

    render(expense, users, query);
  }
  public List<Expense> getFilteredExpenses(String date_str, String name, String spent_for) {
    String date[] = date_str.split("/");
    long start_date = Expense.toEpoch("01/" + date[1] + "/" + date[2]);
    long end_date = Expense.toEpoch("01/" + (Integer.parseInt(date[1]) + 1) + "/" + date[2]) - 1;
    List<Expense> expenseList = new ArrayList<Expense>();
    String selectQuery =
        "SELECT  * FROM "
            + TABLE_EXPENSES
            + " WHERE "
            + KEY_DATE
            + " BETWEEN "
            + start_date
            + " AND "
            + end_date;
    if (name != null && name != "") selectQuery += " AND " + KEY_NAME + " = '" + name + "'";
    if (spent_for != null && spent_for != "")
      selectQuery += " AND " + KEY_SPENT_FOR + " = '" + spent_for + "'";

    selectQuery += " ORDER BY " + KEY_DATE + " DESC";

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
      do {
        Expense exp =
            new Expense(
                Integer.parseInt(cursor.getString(0)),
                cursor.getString(1),
                Long.parseLong(cursor.getString(2)),
                cursor.getString(3),
                cursor.getString(4),
                Float.parseFloat(cursor.getString(5)));
        expenseList.add(exp);
      } while (cursor.moveToNext());
    }
    return expenseList;
  }
  public static void expense(Long id) {
    Expense expense = Expense.findById(id);
    List<Bill> bills = Bill.generateByExpense(expense);

    render(expense, bills);
  }
Ejemplo n.º 6
0
  /**
   * Method to ALWAYS USED IN SALE MAKE (PERSIST AND DRAFT MODE) We can't pass by cascading persist
   * of SaleProductServices, Payments and Installments because GWT does not support (serialize)
   * PersistentBag and Proxy/Lazy hibernate objects
   *
   * @param sale Sale object from GWT client (navigator/JS world)
   * @param payments List of Payment from GWT client (navigator/JS world)
   * @param installments List of Installments from GWT client (navigator/JS world)
   */
  @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
  public synchronized Sale save(
      boolean isDraft,
      Sale sale,
      List<SaleProductService> productsServices,
      List<Expense> expenses,
      List<Payment> payments,
      List<Installment> installments)
      throws IabakoActionForbiddenException, IabakoPackageForbiddenException,
          IabakoUniqueConstraintException, IabakoStockException {

    Enterprise enterprise = getEnterpriseFromSessionUser();

    if (enterprise != null && enterprise.isDemo()) {
      throw new IabakoActionForbiddenException(
          "action_forbidden_for_demo_title", "action_forbidden_for_demo_text", true);
    }

    if (!getDAO().isUniqueNumber(sale)) {
      throw new IabakoUniqueConstraintException(
          messages.getLabel("validation_sale_unique_constraint_error_title"),
          messages.getLabel("validation_sale_unique_constraint_error_text", sale.getNumber()),
          true,
          true);
    }

    if (sale.getEnterprise() == null) {
      sale.setEnterprise(enterprise);
    }

    if (sale.getClient() != null && sale.getClient().getEnterprise() == null) {
      sale.getClient().setEnterprise(enterprise);
    }

    sale.setDate(GenericTools.getDateFromString(sale.getDateString()));

    addProductsServicesToSale(isDraft, sale, productsServices);
    addCustomInstallmentsDefinition(sale, installments);

    sale.setExpenses(expenses);
    // This is because expenses is @GWTTransient and It should not be used too much (so it helps to
    // avoid unnecessary server calls).
    sale.setSaleWithExpenses(!expenses.isEmpty());

    if (!isDraft) {
      addClientTag(sale);
      addPaymentsInstallments(sale, payments, installments);
      sale.setRecalculatedTotal(
          ServerTools.round(sale.calculateAmountFromPaymentsAndInstalments()));
      sale.setTaxPercent(sale.getPonderedTaxPercent());
    } else {
      sale.setTaxPercent(sale.getPonderedTaxPercent());
      sale.setRecalculatedTotal(sale.calculateAmountFromProductsServices());
    }
    sale.setTotalBeforeTax(
        sale.getTaxPercent() > 0
            ? ServerTools.round(sale.getRecalculatedTotal() / (1 + sale.getTaxPercent() / 100))
            : null);
    sale.setTotalAfterTax(sale.getTaxPercent() > 0 ? sale.getRecalculatedTotal() : null);
    sale.setTotalNoTax(sale.getTaxPercent() > 0 ? null : sale.getRecalculatedTotal());

    boolean isCreation = sale.getId() == null;
    sale = calculateStatusAndSave(sale, isDraft);
    setBusinessInfo(sale);

    for (Expense e : expenses) {
      // Sale.expenses is a detached relationship. It must be merge manually (not by cascade
      // hibernate function)
      e.setSale(sale);
      e.setPaymentDate(GenericTools.getDateFromString(e.getPaymentDateString()));
      e.setEnterprise(enterprise);
      expenseService.save(e);
    }

    Sale quote = checkIfQuote(sale);

    if (isCreation && quote != null) {
      trackingService.addTrackingToUserSession(TrackingType.quoteTransformed, quote);

    } else if (isDraft) {
      trackingService.addTrackingToUserSession(TrackingType.saleDraft, sale);

    } else {
      trackingService.addTrackingToUserSession(TrackingType.saleNew, sale);
      userService.addInvoiceReceiptToEnterpriseBalance(sale, null);
    }

    return sale;
  }
  public Expense bindExpense(ExpenseDTO dto) throws ServiceException, ServiceProviderException {
    Expense expense = new Expense();
    Currency currency = null;
    Currency originalCurrency = null;
    Category category = null;
    Beneficiary beneficiary = null;
    Account account = null;
    Plan plan = null;

    // TODO: This all to CommonBinder!

    category = getCategory(dto.getCategoryAbbr());
    account = getAccount(dto.getSrcAccountNo());

    if (account == null) {
      logger.error("Account [" + dto.getSrcAccountNo() + "] is not in database");
      throw new ServiceProviderException(
          "Account [" + dto.getSrcAccountNo() + "] is not in database");
    }

    Date expDate = null;

    if (dto.getDate() != null) {
      expDate = dto.getDate();

    } else {
      expDate = new Date();
    }
    plan = facade.getCurrentAccountPlan(expDate, dto.getSrcAccountNo());

    if (plan == null) {
      logger.error("Plan must be defined for date " + expDate);
      throw new ServiceProviderException("Plan must be defined for date " + expDate);
    }

    if (dto.getBeneficiaryInitials() != null && !dto.getBeneficiaryInitials().equals("")) {
      beneficiary = facade.getBeneficiaryByInitials(dto.getBeneficiaryInitials());

    } else {
      logger.error("Beneficiary initials cannot be null nor an empty string");
      throw new ServiceProviderException("Beneficiary initials cannot be null nor an empty string");
    }

    if (beneficiary == null) {
      logger.error("Beneficiary [" + dto.getBeneficiaryInitials() + "] is not in database");
      throw new ServiceProviderException(
          "Beneficiary [" + dto.getBeneficiaryInitials() + "] is not in database");
    }

    currency = account.getCurrency();
    originalCurrency = getOriginalCurrency(dto.getOriginalCurrencyISO(), account);

    expense.setAmount(getAmount(dto.getAmount().doubleValue()));
    expense.setOriginalAmount(
        getOriginalAmount(dto.getOriginalAmount()) != 0
            ? dto.getOriginalAmount()
            : dto.getAmount().doubleValue());
    expense.setCleared(dto.isCleared());
    expense.setRefundable(dto.isRefundable());
    expense.setCurrency(currency);
    expense.setOriginalCurrency(originalCurrency);
    expense.setCategory(category);
    expense.setSrcAccount(account);
    expense.setBeneficiary(beneficiary);
    expense.setPlan(plan);
    expense.setDate(expDate);
    expense.setLocation(dto.getLocation());
    expense.setDescription(dto.getDescription());

    return expense;
  }
 public String getFormattedAmount() {
   return currency.format(expense.getAmount());
 }