Skip to content
Merged
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
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
"@mui/icons-material": "^6.4.3",
"@mui/material": "^6.4.3",
"@mui/x-date-pickers": "^7.26.0",
"@react-pdf/renderer": "4.3.0",
"@react-pdf/renderer": "^4.4.1",
"@sentry/react": "^8.32.0",
"@sentry/webpack-plugin": "^2.22.4",
"@stripe/react-stripe-js": "^5.4.1",
Expand Down Expand Up @@ -93,7 +93,7 @@
"moment-duration-format": "^2.3.2",
"moment-timezone": "^0.5.33",
"mui-color-input": "^9.0.0",
"openstack-uicore-foundation": "5.0.43",
"openstack-uicore-foundation": "5.0.44",
Comment thread
smarcet marked this conversation as resolved.
"p-limit": "^6.1.0",
"path-browserify": "^1.0.1",
"postcss-loader": "^6.2.1",
Expand Down Expand Up @@ -180,7 +180,7 @@
"src/**/*.{js,jsx,mjs}"
],
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/src/__mocks__/fileMock.js",
"\\.(css)$": "identity-obj-proxy"
},
"transformIgnorePatterns": [
Expand Down
115 changes: 115 additions & 0 deletions src/actions/__tests__/sponsor-purchases-actions.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
/**
* Copyright 2024 OpenStack Foundation
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* 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 configureStore from "redux-mock-store";
import thunk from "redux-thunk";
import flushPromises from "flush-promises";
import {
getRequest,
snackbarErrorMsg
} from "openstack-uicore-foundation/lib/utils/actions";
import { generateInvoicePDF } from "openstack-uicore-foundation/lib/components/order-invoice-pdf";
import { downloadSponsorInvoice } from "../sponsor-purchases-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"),
getRequest: jest.fn(),
snackbarErrorMsg: jest.fn((payload) => ({
type: "SNACKBAR_ERROR_MSG_MOCK",
payload
}))
}));

jest.mock(
"openstack-uicore-foundation/lib/components/order-invoice-pdf",
() => ({
generateInvoicePDF: jest.fn(() => Promise.resolve())
})
);

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

beforeEach(() => {
jest.clearAllMocks();
capturedUrl = null;
window.PURCHASES_API_URL = "https://purchases.example.com";
jest.spyOn(methods, "getAccessTokenSafely").mockResolvedValue("TOKEN");
});

afterEach(() => {
jest.restoreAllMocks();
delete window.PURCHASES_API_URL;
});

const buildStore = () =>
mockStore({
currentSummitState: { currentSummit: { id: 1 } },
currentSponsorState: { entity: { id: 123 } }
});

it("fetches the order for the explicit sponsorId, generates the PDF with the raw order and currentSummit, and never touches the shared order-detail state", async () => {
const fetchedOrder = { id: 7, forms: [] };
getRequest.mockImplementation((reqAC, recAC, url) => {
capturedUrl = url;
return () => () => Promise.resolve({ response: fetchedOrder });
});

const store = buildStore();
await store.dispatch(downloadSponsorInvoice(7, 456));
await flushPromises();

expect(capturedUrl).toBe(
`${window.PURCHASES_API_URL}/api/v2/summits/1/sponsors/456/purchases/7`
);
expect(generateInvoicePDF).toHaveBeenCalledWith(
fetchedOrder,
{ id: 1 },
expect.objectContaining({ logoSrc: expect.anything() })
);
expect(snackbarErrorMsg).not.toHaveBeenCalled();
});

it("swallows the order-fetch rejection silently since authErrorHandler already surfaced it", async () => {
getRequest.mockImplementation(
() => () => () => Promise.reject(new Error("Network error"))
);

const store = buildStore();
await store.dispatch(downloadSponsorInvoice(7, 456));
await flushPromises();

expect(generateInvoicePDF).not.toHaveBeenCalled();
// No second, stacked error UI on top of authErrorHandler's own message.
expect(snackbarErrorMsg).not.toHaveBeenCalled();
});

it("shows an error message when PDF generation rejects", async () => {
getRequest.mockImplementation(
() => () => () => Promise.resolve({ response: { id: 7, forms: [] } })
);
generateInvoicePDF.mockRejectedValueOnce(new Error("PDF error"));

const store = buildStore();
await store.dispatch(downloadSponsorInvoice(7, 456));
await flushPromises();

expect(snackbarErrorMsg).toHaveBeenCalledWith(
expect.objectContaining({ html: "errors.invoice_generation" })
);
});
});
50 changes: 48 additions & 2 deletions src/actions/sponsor-purchases-actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,10 @@ import {
stopLoading,
getCSV,
snackbarErrorHandler,
snackbarErrorMsg,
snackbarSuccessHandler
} from "openstack-uicore-foundation/lib/utils/actions";
import { generateInvoicePDF } from "openstack-uicore-foundation/lib/components/order-invoice-pdf";
import T from "i18n-react/dist/i18n-react";
import { escapeFilterValue, getAccessTokenSafely } from "../utils/methods";
import {
Expand All @@ -32,6 +34,7 @@ import {
DUMMY_ACTION,
PURCHASE_STATUS
} from "../utils/constants";
import logoInvoice from "../assets/fn-invoice-header.png";

export const REQUEST_ALL_SPONSOR_PURCHASES = "REQUEST_ALL_SPONSOR_PURCHASES";
export const RECEIVE_ALL_SPONSOR_PURCHASES = "RECEIVE_ALL_SPONSOR_PURCHASES";
Expand All @@ -44,6 +47,9 @@ export const CLEAR_SPONSOR_ORDER = "CLEAR_SPONSOR_ORDER";
export const SPONSOR_CLIENT_ADDRESS_UPDATED = "SPONSOR_CLIENT_ADDRESS_UPDATED";
export const SPONSOR_CLIENT_UPDATED = "SPONSOR_CLIENT_UPDATED";

const ORDER_DETAIL_EXPAND =
"forms,forms.items,forms.items.meta_fields,forms.items.type,refunds,payments,notes,fees";

export const getAllSponsorPurchases =
(
term = "",
Expand Down Expand Up @@ -307,8 +313,7 @@ export const getSponsorOrder = (orderId) => async (dispatch, getState) => {

const params = {
access_token: accessToken,
expand:
"forms,forms.items,forms.items.meta_fields,forms.items.type,refunds,payments,notes,fees"
expand: ORDER_DETAIL_EXPAND
};

return getRequest(
Expand All @@ -325,6 +330,47 @@ export const clearSponsorOrder = () => async (dispatch) => {
dispatch(createAction(CLEAR_SPONSOR_ORDER)({}));
};

export const downloadSponsorInvoice =
(orderId, sponsorId) => async (dispatch, getState) => {
const { currentSummitState } = getState();
const { currentSummit } = currentSummitState;
const accessToken = await getAccessTokenSafely();

dispatch(startLoading());

const params = {
access_token: accessToken,
expand: ORDER_DETAIL_EXPAND
};

// Uses a DUMMY_ACTION (not RECEIVE_SPONSOR_ORDER) on purpose: this fetch
// is only ever used to build a PDF and must never write into
// sponsorPagePurchaseListState.currentOrder, which SponsorOrderDetails
// owns and mutates by order id.
return getRequest(
null,
createAction(DUMMY_ACTION),
`${window.PURCHASES_API_URL}/api/v2/summits/${currentSummit.id}/sponsors/${sponsorId}/purchases/${orderId}`,
authErrorHandler
)(params)(dispatch)
.then(({ response: fetchedOrder }) =>
generateInvoicePDF(fetchedOrder, currentSummit, {
logoSrc: logoInvoice
}).catch(() =>
dispatch(
snackbarErrorMsg({
title: T.translate("general.error"),
html: T.translate("errors.invoice_generation")
})
)
)
)
.catch(() => {}) // authErrorHandler already surfaced the fetch failure
.finally(() => {
dispatch(stopLoading());
});
};

export const updateClientAddress =
(orderId, address) => async (dispatch, getState) => {
const { currentSummitState, currentSponsorState } = getState();
Expand Down
Binary file added src/assets/fn-invoice-header.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 3 additions & 1 deletion src/i18n/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@
"entity_not_found": "The entity you are looking for was not found.",
"maximum_files": "Maximum number of files has been reached",
"payment_profile_not_found_title": "Payment Profile not found",
"payment_profile_not_found": "Missing payment profile for summit {{summitName}}. Please contact support."
"payment_profile_not_found": "Missing payment profile for summit {{summitName}}. Please contact support.",
"invoice_generation": "Invoice could not be generated. Please contact support."
},
"general": {
"summit": "Event",
Expand Down Expand Up @@ -61,6 +62,7 @@
"save_and_publish": "Save & Publish",
"save_and_add_next": "Save & Add Next",
"export": "Export",
"download_invoice": "Download Invoice",
"are_you_sure": "Are you sure?",
"yes_delete": "Yes, delete.",
"yes_remove": "Yes, remove.",
Expand Down
Loading
Loading