Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
103 changes: 103 additions & 0 deletions src/actions/__tests__/tax-actions.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
/**
* @jest-environment jsdom
*/
import configureStore from "redux-mock-store";
import thunk from "redux-thunk";
import flushPromises from "flush-promises";
import {
postRequest,
putRequest
} from "openstack-uicore-foundation/lib/utils/actions";
import { saveTaxType } from "../tax-actions";
import * as methods from "../../utils/methods";

jest.mock("openstack-uicore-foundation/lib/utils/actions", () => ({
__esModule: true,
...jest.requireActual("openstack-uicore-foundation/lib/utils/actions"),
postRequest: jest.fn(),
putRequest: jest.fn()
}));

const requestMock =
(requestActionCreator, receiveActionCreator) => () => (dispatch) => {
if (requestActionCreator && typeof requestActionCreator === "function") {
dispatch(requestActionCreator({}));
}
return new Promise((resolve) => {
if (typeof receiveActionCreator === "function") {
dispatch(receiveActionCreator({ response: {} }));
} else {
dispatch(receiveActionCreator);
}
resolve({ response: {} });
});
};

const storeState = {
currentSummitState: { currentSummit: { id: 1 } }
};

describe("saveTaxType", () => {
const middlewares = [thunk];
const mockStore = configureStore(middlewares);

beforeEach(() => {
jest.spyOn(methods, "getAccessTokenSafely").mockResolvedValue("TOKEN");
postRequest.mockImplementation(requestMock);
putRequest.mockImplementation(requestMock);
});

afterEach(() => {
jest.restoreAllMocks();
});

describe("create path (entity has no id)", () => {
it("returns a Promise that resolves with the response payload", async () => {
const store = mockStore(storeState);
const result = store.dispatch(
saveTaxType({ name: "VAT", rate: 20, tax_id: "V1" })
);
expect(result).toBeInstanceOf(Promise);
await expect(result).resolves.toEqual({ response: {} });
});

it("dispatches TAX_TYPE_ADDED then STOP_LOADING on success", async () => {
const store = mockStore(storeState);
store.dispatch(saveTaxType({ name: "VAT", rate: 20, tax_id: "V1" }));
await flushPromises();

const actionTypes = store.getActions().map((a) => a.type);
expect(actionTypes).toContain("TAX_TYPE_ADDED");
expect(actionTypes).toContain("STOP_LOADING");
expect(actionTypes.indexOf("STOP_LOADING")).toBeGreaterThan(
actionTypes.indexOf("TAX_TYPE_ADDED")
);
});
});

describe("update path (entity has id)", () => {
it("returns a Promise that resolves with the response payload", async () => {
const store = mockStore(storeState);
const result = store.dispatch(
saveTaxType({ id: 1, name: "VAT", rate: 20, tax_id: "V1" })
);
expect(result).toBeInstanceOf(Promise);
await expect(result).resolves.toEqual({ response: {} });
});

it("dispatches TAX_TYPE_UPDATED then STOP_LOADING on success", async () => {
const store = mockStore(storeState);
store.dispatch(
saveTaxType({ id: 1, name: "VAT", rate: 20, tax_id: "V1" })
);
await flushPromises();

const actionTypes = store.getActions().map((a) => a.type);
expect(actionTypes).toContain("TAX_TYPE_UPDATED");
expect(actionTypes).toContain("STOP_LOADING");
expect(actionTypes.indexOf("STOP_LOADING")).toBeGreaterThan(
actionTypes.indexOf("TAX_TYPE_UPDATED")
);
});
});
});
87 changes: 51 additions & 36 deletions src/actions/tax-actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,9 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
* */

import T from "i18n-react/dist/i18n-react";
import history from "../history";
import {
getRequest,
putRequest,
Expand All @@ -21,11 +20,16 @@ import {
createAction,
stopLoading,
startLoading,
showMessage,
showSuccessMessage,
authErrorHandler
authErrorHandler,
escapeFilterValue
} from "openstack-uicore-foundation/lib/utils/actions";
import { getAccessTokenSafely } from "../utils/methods";
import {
DEFAULT_CURRENT_PAGE,
DEFAULT_ORDER_DIR,
DEFAULT_PER_PAGE
} from "../utils/constants";

export const REQUEST_TAX_TYPES = "REQUEST_TAX_TYPES";
export const RECEIVE_TAX_TYPES = "RECEIVE_TAX_TYPES";
Expand All @@ -37,35 +41,55 @@ export const TAX_TYPE_ADDED = "TAX_TYPE_ADDED";
export const TAX_TYPE_DELETED = "TAX_TYPE_DELETED";
export const TAX_TICKET_ADDED = "TAX_TICKET_ADDED";
export const TAX_TICKET_REMOVED = "TAX_TICKET_REMOVED";
const ALLOWED_TAX_TYPE_SORT_FIELDS = ["name", "rate"];

export const getTaxTypes =
(order = "name", orderDir = 1) =>
(
term = "",
page = DEFAULT_CURRENT_PAGE,
perPage = DEFAULT_PER_PAGE,
order = "name",
orderDir = DEFAULT_ORDER_DIR
) =>
async (dispatch, getState) => {
const { currentSummitState } = getState();
const accessToken = await getAccessTokenSafely();
const { currentSummit } = currentSummitState;
const filter = [];
const normalizedOrder = ALLOWED_TAX_TYPE_SORT_FIELDS.includes(order)
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no need for this check, just define what columns are sortable in the table config

? order
: "name";

dispatch(startLoading());

if (term) {
const escapedTerm = escapeFilterValue(term);
filter.push(`name=@${escapedTerm}`);
}

const params = {
page: 1,
per_page: 100,
page,
per_page: perPage,
access_token: accessToken,
expand: "ticket_types"
};

if (filter.length > 0) {
params["filter[]"] = filter;
}

// order
if (order != null && orderDir != null) {
const orderDirSign = orderDir === 1 ? "+" : "-";
params["order"] = `${orderDirSign}${order}`;
if (normalizedOrder != null && orderDir != null) {
const orderDirSign = orderDir === 1 ? "" : "-";
params.order = `${orderDirSign}${normalizedOrder}`;
}

return getRequest(
createAction(REQUEST_TAX_TYPES),
createAction(RECEIVE_TAX_TYPES),
`${window.API_BASE_URL}/api/v1/summits/${currentSummit.id}/tax-types`,
authErrorHandler,
{ order, orderDir }
{ order, orderDir, page, perPage, term }
)(params)(dispatch).then(() => {
dispatch(stopLoading());
});
Expand Down Expand Up @@ -93,7 +117,7 @@ export const getTaxType = (taxTypeId) => async (dispatch, getState) => {
});
};

export const resetTaxTypeForm = () => (dispatch, getState) => {
export const resetTaxTypeForm = () => (dispatch) => {
dispatch(createAction(RESET_TAX_TYPE_FORM)({}));
};

Expand All @@ -111,40 +135,31 @@ export const saveTaxType = (entity) => async (dispatch, getState) => {
const normalizedEntity = normalizeEntity(entity);

if (entity.id) {
putRequest(
return putRequest(
createAction(UPDATE_TAX_TYPE),
createAction(TAX_TYPE_UPDATED),
`${window.API_BASE_URL}/api/v1/summits/${currentSummit.id}/tax-types/${entity.id}`,
normalizedEntity,
authErrorHandler,
entity
)(params)(dispatch).then((payload) => {
dispatch(stopLoading());
dispatch(showSuccessMessage(T.translate("edit_tax_type.tax_type_saved")));
});
} else {
const success_message = {
title: T.translate("general.done"),
html: T.translate("edit_tax_type.tax_type_created"),
type: "success"
};

postRequest(
createAction(UPDATE_TAX_TYPE),
createAction(TAX_TYPE_ADDED),
`${window.API_BASE_URL}/api/v1/summits/${currentSummit.id}/tax-types`,
normalizedEntity,
authErrorHandler,
entity
)(params)(dispatch).then((payload) => {
dispatch(
showMessage(success_message, () => {
history.push(
`/app/summits/${currentSummit.id}/tax-types/${payload.response.id}`
);
})
);
return payload;
});
}
return postRequest(
createAction(UPDATE_TAX_TYPE),
createAction(TAX_TYPE_ADDED),
`${window.API_BASE_URL}/api/v1/summits/${currentSummit.id}/tax-types`,
normalizedEntity,
authErrorHandler,
entity
)(params)(dispatch).then((payload) => {
dispatch(stopLoading());
dispatch(showSuccessMessage(T.translate("edit_tax_type.tax_type_created")));
return payload;
});
};

export const deleteTaxType = (taxTypeId) => async (dispatch, getState) => {
Expand Down
Loading
Loading