func CreateExpense(rw http.ResponseWriter, r *http.Request, c *ctx.Context) error {
	form, err := form.New(r)
	if err != nil {
		return httperr.BadRequest(err.Error())
	}

	params := service.CreateExpenseParams{
		Description: form.ReqString("description"),
		Amount:      form.ReqInt("amount"),
	}

	if err := form.Err(); err != nil {
		return err
	}

	con, err := c.TxManager.Begin()
	if err != nil {
		return err
	}

	expense, err := service.CreateExpense(c.Logger, con, params)
	if err != nil {
		return err
	}

	rw.WriteHeader(http.StatusCreated)
	return serialize.Expense(rw, expense)
}
func CreateExpense(rw http.ResponseWriter, r *http.Request, c *ctx.Context) error {
	form, err := form.New(r)
	if err != nil {
		return httperr.BadRequest(err.Error())
	}

	params := service.CreateExpenseParams{
		Description: form.ReqString("description"),
		Amount:      form.ReqInt("amount"),
	}

	con, err := c.TxManager.Begin()
	if err != nil {
		return err
	}

	_, err = service.CreateExpense(c.Logger, con, params)
	if err != nil {
		ve, ok := apperrors.IsValidationError(err)
		if !ok {
			return err
		}
		view := &views.ExpenseForm{
			Description: params.Description,
			Amount:      params.Amount,
			Errors:      ve.FieldErrors,
		}
		return views.RenderWithLayout(rw, view)
	}

	http.Redirect(rw, r, "/expenses", 302)
	return nil
}
func TestCreateExpense_Validation(t *testing.T) {
	tx := dbtest.BeginTx()
	defer tx.Rollback()

	_, err := service.CreateExpense(logger.Discard, tx, service.CreateExpenseParams{
		Description: "",
		Amount:      0,
	})

	assert.MustBeEqual(t, "ValidationError: Description: must be present, Amount: must be greater than 0", err.Error())

	cnt, err := db.CountExpenses(tx)
	assert.MustBeNil(t, err)
	assert.Equal(t, 0, cnt)
}
func TestCreateExpense_Success(t *testing.T) {
	tx := dbtest.BeginTx()
	defer tx.Rollback()

	expense, err := service.CreateExpense(logger.Discard, tx, service.CreateExpenseParams{
		Description: "Peter Lustig",
		Amount:      42,
	})

	assert.MustBeNil(t, err)
	assert.Equal(t, "Peter Lustig", expense.Description)
	assert.Equal(t, 42, expense.Amount)

	cnt, err := db.CountExpenses(tx)
	assert.MustBeNil(t, err)
	assert.Equal(t, 1, cnt)
}