diff options
Diffstat (limited to 'packages/merchant-backoffice-ui/src/paths/instance')
102 files changed, 8435 insertions, 3507 deletions
diff --git a/packages/merchant-backoffice-ui/src/paths/instance/reserves/create/Create.stories.tsx b/packages/merchant-backoffice-ui/src/paths/instance/accounts/create/Create.stories.tsx index 586881318..50cd801d8 100644 --- a/packages/merchant-backoffice-ui/src/paths/instance/reserves/create/Create.stories.tsx +++ b/packages/merchant-backoffice-ui/src/paths/instance/accounts/create/Create.stories.tsx @@ -1,6 +1,6 @@ /* This file is part of GNU Taler - (C) 2021 Taler Systems S.A. + (C) 2021-2024 Taler Systems S.A. GNU Taler is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -15,28 +15,14 @@ */ /** -* -* @author Sebastian Javier Marchano (sebasjm) -*/ + * + * @author Sebastian Javier Marchano (sebasjm) + */ -import { h, VNode, FunctionalComponent } from 'preact'; +import { h, VNode, FunctionalComponent } from "preact"; import { CreatePage as TestedComponent } from "./CreatePage.js"; - export default { - title: 'Pages/Reserve/Create', + title: "Pages/Accounts/Create", component: TestedComponent, - argTypes: { - onCreate: { action: 'onCreate' }, - onBack: { action: 'onBack' }, - }, }; - -function createExample<Props>(Component: FunctionalComponent<Props>, props: Partial<Props>) { - const r = (args: any) => <Component {...args} /> - r.args = props - return r -} - -export const Example = createExample(TestedComponent, { -}); diff --git a/packages/merchant-backoffice-ui/src/paths/instance/accounts/create/CreatePage.tsx b/packages/merchant-backoffice-ui/src/paths/instance/accounts/create/CreatePage.tsx new file mode 100644 index 000000000..d05375b6c --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/accounts/create/CreatePage.tsx @@ -0,0 +1,197 @@ +/* + This file is part of GNU Taler + (C) 2021-2024 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +/** + * + * @author Sebastian Javier Marchano (sebasjm) + */ + +import { TalerMerchantApi } from "@gnu-taler/taler-util"; +import { useTranslationContext } from "@gnu-taler/web-util/browser"; +import { Fragment, h, VNode } from "preact"; +import { useState } from "preact/hooks"; +import { AsyncButton } from "../../../../components/exception/AsyncButton.js"; +import { + FormErrors, + FormProvider, +} from "../../../../components/form/FormProvider.js"; +import { Input } from "../../../../components/form/Input.js"; +import { InputPaytoForm } from "../../../../components/form/InputPaytoForm.js"; +import { InputSelector } from "../../../../components/form/InputSelector.js"; +import { undefinedIfEmpty } from "../../../../utils/table.js"; +import { safeConvertURL } from "../update/UpdatePage.js"; + +type Entity = TalerMerchantApi.AccountAddDetails & { repeatPassword: string }; + +interface Props { + onCreate: (d: TalerMerchantApi.AccountAddDetails) => Promise<void>; + onBack?: () => void; +} + +const accountAuthType = ["none", "basic"]; + +export function CreatePage({ onCreate, onBack }: Props): VNode { + const { i18n } = useTranslationContext(); + + const [state, setState] = useState<Partial<Entity>>({}); + const facadeURL = safeConvertURL(state.credit_facade_url); + const errors: FormErrors<Entity> = { + payto_uri: !state.payto_uri ? i18n.str`required` : undefined, + + credit_facade_credentials: !state.credit_facade_credentials + ? undefined + : undefinedIfEmpty({ + username: + state.credit_facade_credentials.type === "basic" && + !state.credit_facade_credentials.username + ? i18n.str`required` + : undefined, + password: + state.credit_facade_credentials.type === "basic" && + !state.credit_facade_credentials.password + ? i18n.str`required` + : undefined, + }), + credit_facade_url: !state.credit_facade_url + ? undefined + : !facadeURL + ? i18n.str`Invalid url` + : !facadeURL.href.endsWith("/") + ? i18n.str`URL should end with a '/'` + : facadeURL.searchParams.size > 0 + ? i18n.str`URL should not contain params` + : facadeURL.hash + ? i18n.str`URL should not hash param` + : undefined, + repeatPassword: !state.credit_facade_credentials + ? undefined + : state.credit_facade_credentials.type === "basic" && + (!state.credit_facade_credentials.password || + state.credit_facade_credentials.password !== state.repeatPassword) + ? i18n.str`is not the same` + : undefined, + }; + + const hasErrors = Object.keys(errors).some( + (k) => (errors as Record<string, unknown>)[k] !== undefined, + ); + + const submitForm = () => { + if (hasErrors) return Promise.reject(); + const credit_facade_url = !state.credit_facade_url + ? undefined + : facadeURL?.href; + const credit_facade_credentials: + | TalerMerchantApi.FacadeCredentials + | undefined = + credit_facade_url == undefined + ? undefined + : state.credit_facade_credentials?.type === "basic" + ? { + type: "basic", + password: state.credit_facade_credentials.password, + username: state.credit_facade_credentials.username, + } + : { + type: "none", + }; + + return onCreate({ + payto_uri: state.payto_uri!, + credit_facade_credentials, + credit_facade_url, + }); + }; + + return ( + <div> + <section class="section is-main-section"> + <div class="columns"> + <div class="column" /> + <div class="column is-four-fifths"> + <FormProvider + object={state} + valueHandler={setState} + errors={errors} + > + <InputPaytoForm<Entity> + name="payto_uri" + label={i18n.str`Account`} + /> + <Input<Entity> + name="credit_facade_url" + label={i18n.str`Account info URL`} + help="https://bank.com" + expand + tooltip={i18n.str`From where the merchant can download information about incoming wire transfers to this account`} + /> + <InputSelector + name="credit_facade_credentials.type" + label={i18n.str`Auth type`} + tooltip={i18n.str`Choose the authentication type for the account info URL`} + values={accountAuthType} + toStr={(str) => { + if (str === "none") return "Without authentication"; + return "Username and password"; + }} + /> + {state.credit_facade_credentials?.type === "basic" ? ( + <Fragment> + <Input + name="credit_facade_credentials.username" + label={i18n.str`Username`} + tooltip={i18n.str`Username to access the account information.`} + /> + <Input + name="credit_facade_credentials.password" + inputType="password" + label={i18n.str`Password`} + tooltip={i18n.str`Password to access the account information.`} + /> + <Input + name="repeatPassword" + inputType="password" + label={i18n.str`Repeat password`} + /> + </Fragment> + ) : undefined} + </FormProvider> + + <div class="buttons is-right mt-5"> + {onBack && ( + <button class="button" onClick={onBack}> + <i18n.Translate>Cancel</i18n.Translate> + </button> + )} + <AsyncButton + disabled={hasErrors} + data-tooltip={ + hasErrors + ? i18n.str`Need to complete marked fields` + : "confirm operation" + } + onClick={submitForm} + > + <i18n.Translate>Confirm</i18n.Translate> + </AsyncButton> + </div> + </div> + <div class="column" /> + </div> + </section> + </div> + ); +} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/accounts/create/index.tsx b/packages/merchant-backoffice-ui/src/paths/instance/accounts/create/index.tsx new file mode 100644 index 000000000..9bab33f6f --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/accounts/create/index.tsx @@ -0,0 +1,236 @@ +/* + This file is part of GNU Taler + (C) 2021-2024 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +/** + * + * @author Sebastian Javier Marchano (sebasjm) + */ + +import { + FacadeCredentials, + HttpStatusCode, + OperationFail, + OperationOk, + TalerError, + TalerMerchantApi, + TalerRevenueHttpClient, + assertUnreachable, + opFixedSuccess, +} from "@gnu-taler/taler-util"; +import { + BrowserFetchHttpLib, + useTranslationContext +} from "@gnu-taler/web-util/browser"; +import { Fragment, VNode, h } from "preact"; +import { useState } from "preact/hooks"; +import { NotificationCard } from "../../../../components/menu/index.js"; +import { useSessionContext } from "../../../../context/session.js"; +import { Notification } from "../../../../utils/types.js"; +import { CreatePage } from "./CreatePage.js"; + +export type Entity = TalerMerchantApi.AccountAddDetails; +interface Props { + onBack?: () => void; + onConfirm: () => void; +} + +export default function CreateValidator({ onConfirm, onBack }: Props): VNode { + const { lib: api } = useSessionContext(); + const { state } = useSessionContext(); + const [notif, setNotif] = useState<Notification | undefined>(undefined); + const { i18n } = useTranslationContext(); + + return ( + <> + <NotificationCard notification={notif} /> + <CreatePage + onBack={onBack} + onCreate={async (request: Entity) => { + const revenueAPI = !request.credit_facade_url + ? undefined + : new URL("./", request.credit_facade_url); + + if (revenueAPI) { + const resp = await testRevenueAPI( + revenueAPI, + request.credit_facade_credentials, + ); + if (resp.type === "fail") { + switch (resp.case) { + case TestRevenueErrorType.NO_CONFIG: { + setNotif({ + message: i18n.str`Could not create account`, + type: "ERROR", + description: i18n.str`The endpoint doesn't seems to be a Taler Revenue API`, + }); + return; + } + case TestRevenueErrorType.CLIENT_BAD_REQUEST: { + setNotif({ + message: i18n.str`Could not create account`, + type: "ERROR", + description: i18n.str`Server replied with "bad request".`, + }); + return; + } + case TestRevenueErrorType.UNAUTHORIZED: { + setNotif({ + message: i18n.str`Could not create account`, + type: "ERROR", + description: i18n.str`Unauthorized, try with another credentials.`, + }); + return; + } + case TestRevenueErrorType.NOT_FOUND: { + setNotif({ + message: i18n.str`Could not create account`, + type: "ERROR", + description: i18n.str`Check facade URL, server replied with "not found".`, + }); + return; + } + case TestRevenueErrorType.GENERIC_ERROR: { + setNotif({ + message: i18n.str`Could not create account`, + type: "ERROR", + description: resp.detail.hint, + }); + return; + } + default: { + assertUnreachable(resp.case); + } + } + } + } + + return api.instance + .addBankAccount(state.token, request) + .then(() => { + onConfirm(); + }) + .catch((error) => { + setNotif({ + message: i18n.str`could not create account`, + type: "ERROR", + description: error.message, + }); + }); + }} + /> + </> + ); +} + +export enum TestRevenueErrorType { + NO_CONFIG, + CLIENT_BAD_REQUEST, + UNAUTHORIZED, + NOT_FOUND, + GENERIC_ERROR, +} + +export async function testRevenueAPI( + revenueAPI: URL, + creds: FacadeCredentials | undefined, +): Promise<OperationOk<void> | OperationFail<TestRevenueErrorType>> { + const api = new TalerRevenueHttpClient( + revenueAPI.href, + new BrowserFetchHttpLib(), + ); + const auth = + creds === undefined + ? undefined + : creds.type === "none" + ? undefined + : creds.type === "basic" + ? { + username: creds.username, + password: creds.password, + } + : undefined; + + try { + const config = await api.getConfig(auth); + + if (config.type === "fail") { + switch (config.case) { + case HttpStatusCode.Unauthorized: { + return { + type: "fail", + case: TestRevenueErrorType.UNAUTHORIZED, + detail: { + code: 1, + }, + }; + } + case HttpStatusCode.NotFound: { + return { + type: "fail", + case: TestRevenueErrorType.NO_CONFIG, + detail: { + code: 1, + }, + }; + } + } + } + + const history = await api.getHistory(auth); + + if (history.type === "fail") { + switch (history.case) { + case HttpStatusCode.BadRequest: { + return { + type: "fail", + case: TestRevenueErrorType.CLIENT_BAD_REQUEST, + detail: { + code: 1, + }, + }; + } + case HttpStatusCode.Unauthorized: { + return { + type: "fail", + case: TestRevenueErrorType.UNAUTHORIZED, + detail: { + code: 1, + }, + }; + } + case HttpStatusCode.NotFound: { + return { + type: "fail", + case: TestRevenueErrorType.NOT_FOUND, + detail: { + code: 1, + }, + }; + } + } + } + } catch (err) { + if (err instanceof TalerError) { + return { + type: "fail", + case: TestRevenueErrorType.GENERIC_ERROR, + detail: err.errorDetail, + }; + } + } + + return opFixedSuccess(undefined); +} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/accounts/list/List.stories.tsx b/packages/merchant-backoffice-ui/src/paths/instance/accounts/list/List.stories.tsx new file mode 100644 index 000000000..18e762642 --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/accounts/list/List.stories.tsx @@ -0,0 +1,28 @@ +/* + This file is part of GNU Taler + (C) 2021-2024 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +/** + * + * @author Sebastian Javier Marchano (sebasjm) + */ + +import { FunctionalComponent, h } from "preact"; +import { ListPage as TestedComponent } from "./ListPage.js"; + +export default { + title: "Pages/Accounts/List", + component: TestedComponent, +}; diff --git a/packages/merchant-backoffice-ui/src/paths/instance/accounts/list/ListPage.tsx b/packages/merchant-backoffice-ui/src/paths/instance/accounts/list/ListPage.tsx new file mode 100644 index 000000000..4ee68cd80 --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/accounts/list/ListPage.tsx @@ -0,0 +1,61 @@ +/* + This file is part of GNU Taler + (C) 2021-2024 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +/** + * + * @author Sebastian Javier Marchano (sebasjm) + */ + +import { TalerMerchantApi } from "@gnu-taler/taler-util"; +import { h, VNode } from "preact"; +import { CardTable } from "./Table.js"; + +export interface Props { + devices: TalerMerchantApi.BankAccountSummaryEntry[]; + // onLoadMoreBefore?: () => void; + // onLoadMoreAfter?: () => void; + onCreate: () => void; + onDelete: (e: TalerMerchantApi.BankAccountSummaryEntry) => void; + onSelect: (e: TalerMerchantApi.BankAccountSummaryEntry) => void; +} + +export function ListPage({ + devices, + onCreate, + onDelete, + onSelect, + // onLoadMoreBefore, + // onLoadMoreAfter, +}: Props): VNode { + + return ( + <section class="section is-main-section"> + <CardTable + accounts={devices.map((o) => ({ + ...o, + id: String(o.h_wire), + }))} + onCreate={onCreate} + onDelete={onDelete} + onSelect={onSelect} + // onLoadMoreBefore={onLoadMoreBefore} + // hasMoreBefore={!onLoadMoreBefore} + // onLoadMoreAfter={onLoadMoreAfter} + // hasMoreAfter={!onLoadMoreAfter} + /> + </section> + ); +} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/accounts/list/Table.tsx b/packages/merchant-backoffice-ui/src/paths/instance/accounts/list/Table.tsx new file mode 100644 index 000000000..efe484402 --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/accounts/list/Table.tsx @@ -0,0 +1,359 @@ +/* + This file is part of GNU Taler + (C) 2021-2024 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +/** + * + * @author Sebastian Javier Marchano (sebasjm) + */ + +import { parsePaytoUri, PaytoType, PaytoUri, PaytoUriBitcoin, PaytoUriIBAN, PaytoUriTalerBank, PaytoUriUnknown, TalerMerchantApi } from "@gnu-taler/taler-util"; +import { useTranslationContext } from "@gnu-taler/web-util/browser"; +import { Fragment, h, VNode } from "preact"; +import { StateUpdater, useState } from "preact/hooks"; + +type Entity = TalerMerchantApi.BankAccountSummaryEntry; + +interface Props { + accounts: Entity[]; + onDelete: (e: Entity) => void; + onSelect: (e: Entity) => void; + onCreate: () => void; +} + +export function CardTable({ + accounts, + onCreate, + onDelete, + onSelect, +}: Props): VNode { + const [rowSelection, rowSelectionHandler] = useState<string[]>([]); + + const { i18n } = useTranslationContext(); + + return ( + <div class="card has-table"> + <header class="card-header"> + <p class="card-header-title"> + <span class="icon"> + <i class="mdi mdi-newspaper" /> + </span> + <i18n.Translate>Bank accounts</i18n.Translate> + </p> + <div class="card-header-icon" aria-label="more options"> + <span + class="has-tooltip-left" + data-tooltip={i18n.str`add new accounts`} + > + <button class="button is-info" type="button" onClick={onCreate}> + <span class="icon is-small"> + <i class="mdi mdi-plus mdi-36px" /> + </span> + </button> + </span> + </div> + </header> + <div class="card-content"> + <div class="b-table has-pagination"> + <div class="table-wrapper has-mobile-cards"> + {accounts.length > 0 ? ( + <Table + accounts={accounts} + onDelete={onDelete} + onSelect={onSelect} + rowSelection={rowSelection} + rowSelectionHandler={rowSelectionHandler} + /> + ) : ( + <EmptyTable /> + )} + </div> + </div> + </div> + </div> + ); +} +interface TableProps { + rowSelection: string[]; + accounts: Entity[]; + onDelete: (e: Entity) => void; + onSelect: (e: Entity) => void; + rowSelectionHandler: StateUpdater<string[]>; +} + +function Table({ + accounts, + onDelete, + onSelect, +}: TableProps): VNode { + const { i18n } = useTranslationContext(); + const emptyList: Record<PaytoType | "unknown", { parsed: PaytoUri, acc: Entity }[]> = { "bitcoin": [], "x-taler-bank": [], "iban": [], "unknown": [], } + const accountsByType = accounts.reduce((prev, acc) => { + const parsed = parsePaytoUri(acc.payto_uri) + if (!parsed) return prev //skip + if (parsed.targetType !== "bitcoin" && parsed.targetType !== "x-taler-bank" && parsed.targetType !== "iban") { + prev["unknown"].push({ parsed, acc }) + } else { + prev[parsed.targetType].push({ parsed, acc }) + } + return prev + }, emptyList) + + const bitcoinAccounts = accountsByType["bitcoin"] + const talerbankAccounts = accountsByType["x-taler-bank"] + const ibanAccounts = accountsByType["iban"] + const unkownAccounts = accountsByType["unknown"] + + + return ( + <Fragment> + + {bitcoinAccounts.length > 0 && <div class="table-container"> + <p class="card-header-title"><i18n.Translate>Bitcoin type accounts</i18n.Translate></p> + <table class="table is-fullwidth is-striped is-hoverable is-fullwidth"> + <thead> + <tr> + <th> + <i18n.Translate>Address</i18n.Translate> + </th> + <th> + <i18n.Translate>Sewgit 1</i18n.Translate> + </th> + <th> + <i18n.Translate>Sewgit 2</i18n.Translate> + </th> + <th /> + </tr> + </thead> + <tbody> + {bitcoinAccounts.map(({ parsed, acc }, idx) => { + const ac = parsed as PaytoUriBitcoin + return ( + <tr key={idx}> + <td + onClick={(): void => onSelect(acc)} + style={{ cursor: "pointer" }} + > + {ac.targetPath} + </td> + <td + onClick={(): void => onSelect(acc)} + style={{ cursor: "pointer" }} + > + {ac.segwitAddrs[0]} + </td> + <td + onClick={(): void => onSelect(acc)} + style={{ cursor: "pointer" }} + > + {ac.segwitAddrs[1]} + </td> + <td class="is-actions-cell right-sticky"> + <div class="buttons is-right"> + <button + class="button is-danger is-small has-tooltip-left" + data-tooltip={i18n.str`delete selected accounts from the database`} + onClick={() => onDelete(acc)} + > + Delete + </button> + </div> + </td> + </tr> + ); + })} + </tbody> + </table> + </div>} + + + + {talerbankAccounts.length > 0 && <div class="table-container"> + <p class="card-header-title"><i18n.Translate>Taler type accounts</i18n.Translate></p> + <table class="table is-fullwidth is-striped is-hoverable is-fullwidth"> + <thead> + <tr> + <th> + <i18n.Translate>Host</i18n.Translate> + </th> + <th> + <i18n.Translate>Account name</i18n.Translate> + </th> + <th /> + </tr> + </thead> + <tbody> + {talerbankAccounts.map(({ parsed, acc }, idx) => { + const ac = parsed as PaytoUriTalerBank + return ( + <tr key={idx}> + <td + onClick={(): void => onSelect(acc)} + style={{ cursor: "pointer" }} + > + {ac.host} + </td> + <td + onClick={(): void => onSelect(acc)} + style={{ cursor: "pointer" }} + > + {ac.account} + </td> + <td class="is-actions-cell right-sticky"> + <div class="buttons is-right"> + <button + class="button is-danger is-small has-tooltip-left" + data-tooltip={i18n.str`delete selected accounts from the database`} + onClick={() => onDelete(acc)} + > + Delete + </button> + </div> + </td> + </tr> + ); + })} + </tbody> + </table> + </div>} + + {ibanAccounts.length > 0 && <div class="table-container"> + <p class="card-header-title"><i18n.Translate>IBAN type accounts</i18n.Translate></p> + <table class="table is-fullwidth is-striped is-hoverable is-fullwidth"> + <thead> + <tr> + <th> + <i18n.Translate>Account name</i18n.Translate> + </th> + <th> + <i18n.Translate>IBAN</i18n.Translate> + </th> + <th> + <i18n.Translate>BIC</i18n.Translate> + </th> + <th /> + </tr> + </thead> + <tbody> + {ibanAccounts.map(({ parsed, acc }, idx) => { + const ac = parsed as PaytoUriIBAN + return ( + <tr key={idx}> + <td + onClick={(): void => onSelect(acc)} + style={{ cursor: "pointer" }} + > + {ac.params["receiver-name"]} + </td> + <td + onClick={(): void => onSelect(acc)} + style={{ cursor: "pointer" }} + > + {ac.iban} + </td> + <td + onClick={(): void => onSelect(acc)} + style={{ cursor: "pointer" }} + > + {ac.bic ?? ""} + </td> + <td class="is-actions-cell right-sticky"> + <div class="buttons is-right"> + <button + class="button is-danger is-small has-tooltip-left" + data-tooltip={i18n.str`delete selected accounts from the database`} + onClick={() => onDelete(acc)} + > + Delete + </button> + </div> + </td> + </tr> + ); + })} + </tbody> + </table> + </div>} + + {unkownAccounts.length > 0 && <div class="table-container"> + <p class="card-header-title"><i18n.Translate>Other type accounts</i18n.Translate></p> + <table class="table is-fullwidth is-striped is-hoverable is-fullwidth"> + <thead> + <tr> + <th> + <i18n.Translate>Type</i18n.Translate> + </th> + <th> + <i18n.Translate>Path</i18n.Translate> + </th> + <th /> + </tr> + </thead> + <tbody> + {unkownAccounts.map(({ parsed, acc }, idx) => { + const ac = parsed as PaytoUriUnknown + return ( + <tr key={idx}> + <td + onClick={(): void => onSelect(acc)} + style={{ cursor: "pointer" }} + > + {ac.targetType} + </td> + <td + onClick={(): void => onSelect(acc)} + style={{ cursor: "pointer" }} + > + {ac.targetPath} + </td> + <td class="is-actions-cell right-sticky"> + <div class="buttons is-right"> + <button + class="button is-danger is-small has-tooltip-left" + data-tooltip={i18n.str`delete selected accounts from the database`} + onClick={() => onDelete(acc)} + > + Delete + </button> + </div> + </td> + </tr> + ); + })} + </tbody> + </table> + </div>} + </Fragment> + + ); +} + +function EmptyTable(): VNode { + const { i18n } = useTranslationContext(); + return ( + <div class="content has-text-grey has-text-centered"> + <p> + <span class="icon is-large"> + <i class="mdi mdi-magnify mdi-48px" /> + </span> + </p> + <p> + <i18n.Translate> + There is no accounts yet, add more pressing the + sign + </i18n.Translate> + </p> + </div> + ); +} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/accounts/list/index.tsx b/packages/merchant-backoffice-ui/src/paths/instance/accounts/list/index.tsx new file mode 100644 index 000000000..1eda7382d --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/accounts/list/index.tsx @@ -0,0 +1,111 @@ +/* + This file is part of GNU Taler + (C) 2021-2024 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +/** + * + * @author Sebastian Javier Marchano (sebasjm) + */ + +import { HttpStatusCode, TalerError, TalerMerchantApi, assertUnreachable } from "@gnu-taler/taler-util"; +import { + useTranslationContext +} from "@gnu-taler/web-util/browser"; +import { Fragment, VNode, h } from "preact"; +import { useState } from "preact/hooks"; +import { ErrorLoadingMerchant } from "../../../../components/ErrorLoadingMerchant.js"; +import { Loading } from "../../../../components/exception/loading.js"; +import { NotificationCard } from "../../../../components/menu/index.js"; +import { useSessionContext } from "../../../../context/session.js"; +import { useInstanceBankAccounts } from "../../../../hooks/bank.js"; +import { Notification } from "../../../../utils/types.js"; +import { LoginPage } from "../../../login/index.js"; +import { NotFoundPageOrAdminCreate } from "../../../notfound/index.js"; +import { ListPage } from "./ListPage.js"; + +interface Props { + onCreate: () => void; + onSelect: (id: string) => void; +} + +export default function ListOtpDevices({ + onCreate, + onSelect, +}: Props): VNode { + const { i18n } = useTranslationContext(); + const [notif, setNotif] = useState<Notification | undefined>(undefined); + const { lib: api } = useSessionContext(); + const { state } = useSessionContext(); + const result = useInstanceBankAccounts(); + + if (!result) return <Loading /> + if (result instanceof TalerError) { + return <ErrorLoadingMerchant error={result} /> + } + if (result.type === "fail") { + switch(result.case) { + case HttpStatusCode.NotFound: { + return <NotFoundPageOrAdminCreate /> + } + case HttpStatusCode.Unauthorized: { + return <LoginPage /> + } + default: { + assertUnreachable(result) + } + } + } + + return ( + <Fragment> + <NotificationCard notification={notif} /> + {result.body.accounts.length < 1 && + <NotificationCard notification={{ + type: "WARN", + message: i18n.str`You need to associate a bank account to receive revenue.`, + description: i18n.str`Without this the merchant backend will refuse to create new orders.` + }} /> + } + <ListPage + devices={result.body.accounts} + // onLoadMoreBefore={ + // result.isFirstPage ? undefined: result.loadFirst + // } + // onLoadMoreAfter={result.isLastPage ? undefined : result.loadNext} + onCreate={onCreate} + onSelect={(e) => { + onSelect(e.h_wire); + }} + onDelete={(e: TalerMerchantApi.BankAccountSummaryEntry) => { + return api.instance.deleteBankAccount(state.token, e.h_wire) + .then(() => + setNotif({ + message: i18n.str`bank account delete successfully`, + type: "SUCCESS", + }), + ) + .catch((error) => + setNotif({ + message: i18n.str`could not delete the bank account`, + type: "ERROR", + description: error.message, + }), + ) + } + } + /> + </Fragment> + ); +} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/details/Details.stories.tsx b/packages/merchant-backoffice-ui/src/paths/instance/accounts/update/Update.stories.tsx index 068dd55c0..06ea9d07a 100644 --- a/packages/merchant-backoffice-ui/src/paths/instance/details/Details.stories.tsx +++ b/packages/merchant-backoffice-ui/src/paths/instance/accounts/update/Update.stories.tsx @@ -1,6 +1,6 @@ /* This file is part of GNU Taler - (C) 2021 Taler Systems S.A. + (C) 2021-2024 Taler Systems S.A. GNU Taler is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -20,42 +20,13 @@ */ import { h, VNode, FunctionalComponent } from "preact"; -import { DetailPage as TestedComponent } from "./DetailPage.js"; +import { UpdatePage as TestedComponent } from "./UpdatePage.js"; export default { - title: "Pages/Instance/Detail", + title: "Pages/OtpDevices/Update", component: TestedComponent, argTypes: { onUpdate: { action: "onUpdate" }, onBack: { action: "onBack" }, }, }; - -function createExample<Props>( - Component: FunctionalComponent<Props>, - props: Partial<Props> -) { - const r = (args: any) => <Component {...args} />; - r.args = props; - return r; -} - -export const Example = createExample(TestedComponent, { - selected: { - accounts: [], - name: "name", - auth: { method: "external" }, - address: {}, - jurisdiction: {}, - default_max_deposit_fee: "TESTKUDOS:2", - default_max_wire_fee: "TESTKUDOS:1", - default_pay_delay: { - d_us: 1000000, - }, - default_wire_fee_amortization: 1, - default_wire_transfer_delay: { - d_us: 100000, - }, - merchant_pub: "ASDWQEKASJDKSADJ", - }, -}); diff --git a/packages/merchant-backoffice-ui/src/paths/instance/accounts/update/UpdatePage.tsx b/packages/merchant-backoffice-ui/src/paths/instance/accounts/update/UpdatePage.tsx new file mode 100644 index 000000000..1a8e9bdc1 --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/accounts/update/UpdatePage.tsx @@ -0,0 +1,232 @@ +/* + This file is part of GNU Taler + (C) 2021-2024 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +/** + * + * @author Sebastian Javier Marchano (sebasjm) + */ + +import { TalerMerchantApi } from "@gnu-taler/taler-util"; +import { useTranslationContext } from "@gnu-taler/web-util/browser"; +import { Fragment, h, VNode } from "preact"; +import { useState } from "preact/hooks"; +import { AsyncButton } from "../../../../components/exception/AsyncButton.js"; +import { + FormErrors, + FormProvider, +} from "../../../../components/form/FormProvider.js"; +import { Input } from "../../../../components/form/Input.js"; +import { InputPaytoForm } from "../../../../components/form/InputPaytoForm.js"; +import { InputSelector } from "../../../../components/form/InputSelector.js"; +import { undefinedIfEmpty } from "../../../../utils/table.js"; + +type Entity = TalerMerchantApi.BankAccountEntry & WithId; + +const accountAuthType = ["unedit", "none", "basic"]; +interface Props { + onUpdate: (d: TalerMerchantApi.AccountPatchDetails) => Promise<void>; + onBack?: () => void; + account: Entity; +} + +export function UpdatePage({ account, onUpdate, onBack }: Props): VNode { + const { i18n } = useTranslationContext(); + + const [state, setState] = + useState<Partial<TalerMerchantApi.AccountPatchDetails>>(account); + + // @ts-expect-error "unedit" is fine since is part of the accountAuthType values + if (state.credit_facade_credentials?.type === "unedit") { + // we use this to set creds to undefined but server don't get this type + state.credit_facade_credentials = undefined; + } + + const facadeURL = safeConvertURL(state.credit_facade_url); + + const errors: FormErrors<TalerMerchantApi.AccountPatchDetails> = { + credit_facade_url: !state.credit_facade_url + ? undefined + : !facadeURL + ? i18n.str`Invalid url` + : !facadeURL.href.endsWith("/") + ? i18n.str`URL should end with a '/'` + : facadeURL.searchParams.size > 0 + ? i18n.str`URL should not contain params` + : facadeURL.hash + ? i18n.str`URL should not hash param` + : undefined, + credit_facade_credentials: undefinedIfEmpty({ + username: + state.credit_facade_credentials?.type !== "basic" + ? undefined + : !state.credit_facade_credentials.username + ? i18n.str`required` + : undefined, + + password: + state.credit_facade_credentials?.type !== "basic" + ? undefined + : !state.credit_facade_credentials.password + ? i18n.str`required` + : undefined, + + repeatPassword: + state.credit_facade_credentials?.type !== "basic" + ? undefined + : !(state.credit_facade_credentials as any).repeatPassword + ? i18n.str`required` + : (state.credit_facade_credentials as any).repeatPassword !== + state.credit_facade_credentials.password + ? i18n.str`doesn't match` + : undefined, + }), + }; + + const hasErrors = Object.keys(errors).some( + (k) => (errors as any)[k] !== undefined, + ); + + const submitForm = () => { + if (hasErrors) return Promise.reject(); + const credit_facade_url = !state.credit_facade_url + ? undefined + : facadeURL?.href; + + const credit_facade_credentials: + | TalerMerchantApi.FacadeCredentials + | undefined = + credit_facade_url == undefined || + state.credit_facade_credentials === undefined + ? undefined + : state.credit_facade_credentials.type === "basic" + ? { + type: "basic", + password: state.credit_facade_credentials.password, + username: state.credit_facade_credentials.username, + } + : { + type: "none", + }; + + return onUpdate({ credit_facade_credentials, credit_facade_url }); + }; + + return ( + <div> + <section class="section"> + <section class="hero is-hero-bar"> + <div class="hero-body"> + <div class="level"> + <div class="level-left"> + <div class="level-item"> + <span class="is-size-4"> + Account: <b>{account.id.substring(0, 8)}...</b> + </span> + </div> + </div> + </div> + </div> + </section> + <hr /> + + <section class="section is-main-section"> + <div class="columns"> + <div class="column is-four-fifths"> + <FormProvider + object={state} + valueHandler={setState} + errors={errors} + > + <InputPaytoForm<Entity> + name="payto_uri" + label={i18n.str`Account`} + readonly + /> + <Input<Entity> + name="credit_facade_url" + label={i18n.str`Account info URL`} + help="https://bank.com" + expand + tooltip={i18n.str`From where the merchant can download information about incoming wire transfers to this account`} + /> + <InputSelector + name="credit_facade_credentials.type" + label={i18n.str`Auth type`} + tooltip={i18n.str`Choose the authentication type for the account info URL`} + values={accountAuthType} + toStr={(str) => { + if (str === "none") return "Without authentication"; + if (str === "basic") return "With authentication"; + return "Do not change"; + }} + /> + {state.credit_facade_credentials?.type === "basic" ? ( + <Fragment> + <Input + name="credit_facade_credentials.username" + label={i18n.str`Username`} + tooltip={i18n.str`Username to access the account information.`} + /> + <Input + name="credit_facade_credentials.password" + inputType="password" + label={i18n.str`Password`} + tooltip={i18n.str`Password to access the account information.`} + /> + <Input + name="credit_facade_credentials.repeatPassword" + inputType="password" + label={i18n.str`Repeat password`} + /> + </Fragment> + ) : undefined} + </FormProvider> + + <div class="buttons is-right mt-5"> + {onBack && ( + <button class="button" onClick={onBack}> + <i18n.Translate>Cancel</i18n.Translate> + </button> + )} + <AsyncButton + disabled={hasErrors} + data-tooltip={ + hasErrors + ? i18n.str`Need to complete marked fields` + : "confirm operation" + } + onClick={submitForm} + > + <i18n.Translate>Confirm</i18n.Translate> + </AsyncButton> + </div> + </div> + </div> + </section> + </section> + </div> + ); +} + +//TODO: move to utils +export function safeConvertURL(s?: string): URL | undefined { + if (!s) return undefined; + try { + return new URL(s); + } catch (e) { + return undefined; + } +} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/accounts/update/index.tsx b/packages/merchant-backoffice-ui/src/paths/instance/accounts/update/index.tsx new file mode 100644 index 000000000..70942fd55 --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/accounts/update/index.tsx @@ -0,0 +1,153 @@ +/* + This file is part of GNU Taler + (C) 2021-2024 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +/** + * + * @author Sebastian Javier Marchano (sebasjm) + */ + +import { HttpStatusCode, TalerError, TalerMerchantApi, assertUnreachable } from "@gnu-taler/taler-util"; +import { + useTranslationContext +} from "@gnu-taler/web-util/browser"; +import { Fragment, VNode, h } from "preact"; +import { useState } from "preact/hooks"; +import { ErrorLoadingMerchant } from "../../../../components/ErrorLoadingMerchant.js"; +import { Loading } from "../../../../components/exception/loading.js"; +import { NotificationCard } from "../../../../components/menu/index.js"; +import { useSessionContext } from "../../../../context/session.js"; +import { useBankAccountDetails } from "../../../../hooks/bank.js"; +import { Notification } from "../../../../utils/types.js"; +import { LoginPage } from "../../../login/index.js"; +import { NotFoundPageOrAdminCreate } from "../../../notfound/index.js"; +import { TestRevenueErrorType, testRevenueAPI } from "../create/index.js"; +import { UpdatePage } from "./UpdatePage.js"; + +export type Entity = TalerMerchantApi.AccountPatchDetails & WithId; + +interface Props { + onBack?: () => void; + onConfirm: () => void; + bid: string; +} +export default function UpdateValidator({ + bid, + onConfirm, + onBack, +}: Props): VNode { + const { lib: api } = useSessionContext(); + const { state } = useSessionContext(); + const result = useBankAccountDetails(bid); + const [notif, setNotif] = useState<Notification | undefined>(undefined); + + const { i18n } = useTranslationContext(); + + if (!result) return <Loading />; + if (result instanceof TalerError) { + return <ErrorLoadingMerchant error={result} />; + } + if (result.type === "fail") { + switch (result.case) { + case HttpStatusCode.NotFound: { + return <NotFoundPageOrAdminCreate />; + } + case HttpStatusCode.Unauthorized: { + return <LoginPage /> + } + default: { + assertUnreachable(result); + } + } + } + + return ( + <Fragment> + <NotificationCard notification={notif} /> + <UpdatePage + account={{ ...result.body, id: bid }} + onBack={onBack} + onUpdate={async (request) => { + const revenueAPI = !request.credit_facade_url + ? undefined + : new URL("./", request.credit_facade_url); + + if (revenueAPI) { + const resp = await testRevenueAPI( + revenueAPI, + request.credit_facade_credentials, + ); + if (resp.type === "fail") { + switch (resp.case) { + case TestRevenueErrorType.NO_CONFIG: { + setNotif({ + message: i18n.str`Could not create account`, + type: "ERROR", + description: i18n.str`The endpoint doesn't seems to be a Taler Revenue API`, + }); + return; + } + case TestRevenueErrorType.CLIENT_BAD_REQUEST: { + setNotif({ + message: i18n.str`Could not create account`, + type: "ERROR", + description: i18n.str`Server replied with "bad request".`, + }); + return; + } + case TestRevenueErrorType.UNAUTHORIZED: { + setNotif({ + message: i18n.str`Could not create account`, + type: "ERROR", + description: i18n.str`Unauthorized, try with another credentials.`, + }); + return; + } + case TestRevenueErrorType.NOT_FOUND: { + setNotif({ + message: i18n.str`Could not create account`, + type: "ERROR", + description: i18n.str`Check facade URL, server replied with "not found".`, + }); + return; + } + case TestRevenueErrorType.GENERIC_ERROR: { + setNotif({ + message: i18n.str`Could not create account`, + type: "ERROR", + description: resp.detail.hint, + }); + return; + } + default: { + assertUnreachable(resp.case) + } + } + } + } + return api.instance.updateBankAccount(state.token, bid, request) + .then(onConfirm) + .catch((error) => { + setNotif({ + message: i18n.str`could not update account`, + type: "ERROR", + description: error.message, + }); + }); + }} + /> + </Fragment> + ); +} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/details/DetailPage.tsx b/packages/merchant-backoffice-ui/src/paths/instance/details/DetailPage.tsx index d4717f251..3168c7cc4 100644 --- a/packages/merchant-backoffice-ui/src/paths/instance/details/DetailPage.tsx +++ b/packages/merchant-backoffice-ui/src/paths/instance/details/DetailPage.tsx @@ -1,6 +1,6 @@ /* This file is part of GNU Taler - (C) 2021 Taler Systems S.A. + (C) 2021-2024 Taler Systems S.A. GNU Taler is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -15,73 +15,69 @@ */ /** -* -* @author Sebastian Javier Marchano (sebasjm) -*/ + * + * @author Sebastian Javier Marchano (sebasjm) + */ +import { useTranslationContext } from "@gnu-taler/web-util/browser"; import { h, VNode } from "preact"; import { useState } from "preact/hooks"; import { FormProvider } from "../../../components/form/FormProvider.js"; import { Input } from "../../../components/form/Input.js"; -import { MerchantBackend } from "../../../declaration.js"; -import { useTranslator } from "../../../i18n/index.js"; +import { TalerMerchantApi } from "@gnu-taler/taler-util"; -type Entity = MerchantBackend.Instances.InstanceReconfigurationMessage; +type Entity = TalerMerchantApi.InstanceReconfigurationMessage; interface Props { onUpdate: () => void; onDelete: () => void; - selected: MerchantBackend.Instances.QueryInstancesResponse; + selected: TalerMerchantApi.QueryInstancesResponse; } -function convert(from: MerchantBackend.Instances.QueryInstancesResponse): Entity { - const { accounts, ...rest } = from - const payto_uris = accounts.filter(a => a.active).map(a => a.payto_uri) +function convert( + from: TalerMerchantApi.QueryInstancesResponse, +): Entity { const defaults = { default_wire_fee_amortization: 1, - default_pay_delay: { d_us: 1000 * 60 * 60 }, //one hour - default_wire_transfer_delay: { d_us: 1000 * 60 * 60 * 2 }, //two hours - } - return { ...defaults, ...rest, payto_uris }; + use_stefan: true, + default_pay_delay: { d_us: 1000 * 60 * 60 * 1000 }, //one hour + default_wire_transfer_delay: { d_us: 1000 * 60 * 60 * 2 * 1000 }, //two hours + }; + return { ...defaults, ...from }; } export function DetailPage({ selected }: Props): VNode { - const [value, valueHandler] = useState<Partial<Entity>>(convert(selected)) + const [value, valueHandler] = useState<Partial<Entity>>(convert(selected)); + + const { i18n } = useTranslationContext(); - const i18n = useTranslator() - - return <div> - <section class="hero is-hero-bar"> - <div class="hero-body"> - <div class="level"> - <div class="level-left"> - <div class="level-item"> - <h1 class="title"> - Here goes the instance description - </h1> + return ( + <div> + <section class="hero is-hero-bar"> + <div class="hero-body"> + <div class="level"> + <div class="level-left"> + <div class="level-item"> + <h1 class="title">Here goes the instance description</h1> + </div> + </div> + <div class="level-right" style="display: none;"> + <div class="level-item" /> </div> - </div> - <div class="level-right" style="display: none;"> - <div class="level-item" /> </div> </div> - </div> - </section> - - <section class="section is-main-section"> - <div class="columns"> - <div class="column" /> - <div class="column is-6"> - <FormProvider<Entity> object={value} valueHandler={valueHandler} > + </section> - <Input<Entity> name="name" readonly label={i18n`Name`} /> - <Input<Entity> name="payto_uris" readonly label={i18n`Account address`} /> - - </FormProvider> + <section class="section is-main-section"> + <div class="columns"> + <div class="column" /> + <div class="column is-6"> + <FormProvider<Entity> object={value} valueHandler={valueHandler}> + <Input<Entity> name="name" readonly label={i18n.str`Name`} /> + </FormProvider> + </div> + <div class="column" /> </div> - <div class="column" /> - </div> - </section> - - </div> - -}
\ No newline at end of file + </section> + </div> + ); +} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/details/index.tsx b/packages/merchant-backoffice-ui/src/paths/instance/details/index.tsx index 2ef0f6d1d..e1a7f87f0 100644 --- a/packages/merchant-backoffice-ui/src/paths/instance/details/index.tsx +++ b/packages/merchant-backoffice-ui/src/paths/instance/details/index.tsx @@ -1,6 +1,6 @@ /* This file is part of GNU Taler - (C) 2021 Taler Systems S.A. + (C) 2021-2024 Taler Systems S.A. GNU Taler is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -13,53 +13,78 @@ You should have received a copy of the GNU General Public License along with GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> */ -import { Fragment, h, VNode } from "preact"; +import { HttpStatusCode, TalerError, assertUnreachable } from "@gnu-taler/taler-util"; +import { Fragment, VNode, h } from "preact"; import { useState } from "preact/hooks"; +import { ErrorLoadingMerchant } from "../../../components/ErrorLoadingMerchant.js"; import { Loading } from "../../../components/exception/loading.js"; import { DeleteModal } from "../../../components/modal/index.js"; -import { useInstanceContext } from "../../../context/instance.js"; -import { HttpError } from "../../../hooks/backend.js"; -import { useInstanceAPI, useInstanceDetails } from "../../../hooks/instance.js"; +import { useSessionContext } from "../../../context/session.js"; +import { useInstanceDetails } from "../../../hooks/instance.js"; +import { LoginPage } from "../../login/index.js"; +import { NotFoundPageOrAdminCreate } from "../../notfound/index.js"; import { DetailPage } from "./DetailPage.js"; interface Props { - onUnauthorized: () => VNode; - onLoadError: (error: HttpError) => VNode; onUpdate: () => void; - onNotFound: () => VNode; onDelete: () => void; } -export default function Detail({ onUpdate, onLoadError, onUnauthorized, onDelete, onNotFound }: Props): VNode { - const { id } = useInstanceContext() - const result = useInstanceDetails() - const [deleting, setDeleting] = useState<boolean>(false) +export default function Detail({ + onUpdate, + onDelete, +}: Props): VNode { + const { state } = useSessionContext(); + const result = useInstanceDetails(); + const [deleting, setDeleting] = useState<boolean>(false); - const { deleteInstance } = useInstanceAPI() + // const { deleteInstance } = useInstanceAPI(); + const { lib } = useSessionContext(); - if (result.clientError && result.isUnauthorized) return onUnauthorized() - if (result.clientError && result.isNotfound) return onNotFound() - if (result.loading) return <Loading /> - if (!result.ok) return onLoadError(result) + if (!result) return <Loading /> + if (result instanceof TalerError) { + return <ErrorLoadingMerchant error={result} /> + } + if (result.type === "fail") { + switch(result.case) { + case HttpStatusCode.Unauthorized: { + return <LoginPage /> + } + case HttpStatusCode.NotFound: { + return <NotFoundPageOrAdminCreate />; + } + default: { + assertUnreachable(result) + } + } + } - return <Fragment> - <DetailPage - selected={result.data} - onUpdate={onUpdate} - onDelete={() => setDeleting(true)} - /> - {deleting && <DeleteModal - element={{ name: result.data.name, id }} - onCancel={() => setDeleting(false)} - onConfirm={async (): Promise<void> => { - try { - await deleteInstance() - onDelete() - } catch (error) { - } - setDeleting(false) - }} - />} - </Fragment> -}
\ No newline at end of file + return ( + <Fragment> + <DetailPage + selected={result.body} + onUpdate={onUpdate} + onDelete={() => setDeleting(true)} + /> + {deleting && ( + <DeleteModal + element={{ name: result.body.name, id: state.instance }} + onCancel={() => setDeleting(false)} + onConfirm={async (): Promise<void> => { + if (state.status !== "loggedIn") { + return + } + try { + await lib.instance.deleteCurrentInstance(state.token); + onDelete(); + } catch (error) { + //FIXME: show message error + } + setDeleting(false); + }} + /> + )} + </Fragment> + ); +} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/details/stories.tsx b/packages/merchant-backoffice-ui/src/paths/instance/details/stories.tsx new file mode 100644 index 000000000..42cb1cb02 --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/details/stories.tsx @@ -0,0 +1,87 @@ +/* + This file is part of GNU Taler + (C) 2021-2024 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +/** + * + * @author Sebastian Javier Marchano (sebasjm) + */ + +import { MerchantApiProviderTesting } from "@gnu-taler/web-util/browser"; +import { FunctionalComponent, h } from "preact"; +import { DetailPage as TestedComponent } from "./DetailPage.js"; + +export default { + title: "Pages/Instance/Detail", + component: TestedComponent, + argTypes: { + onUpdate: { action: "onUpdate" }, + onBack: { action: "onBack" }, + }, +}; + +function createExample<Props>( + Internal: FunctionalComponent<Props>, + props: Partial<Props>, +) { + const component = (args: any) => ( + <MerchantApiProviderTesting + value={{ + cancelRequest: () => { }, + changeBackend: () => { }, + config: { + currency: "ARS", + version: "1", + currencies: { + "ASD": { + name: "testkudos", + alt_unit_names: {}, + num_fractional_input_digits: 1, + num_fractional_normal_digits: 1, + num_fractional_trailing_zero_digits: 1, + } + }, + exchanges: [], + name: "taler-merchant" + }, + hints: [], + lib: {} as any, + onActivity: (() => { }) as any, + url: new URL("asdasd"), + }} + > + <Internal {...(props as any)} /> + </MerchantApiProviderTesting> + ); + return { component, props }; +} + +export const Example = createExample(TestedComponent, { + selected: { + name: "name", + auth: { method: "external" }, + address: {}, + user_type: "business", + jurisdiction: {}, + use_stefan: true, + default_pay_delay: { + d_us: 1000 * 1000, //one second + }, + default_wire_transfer_delay: { + d_us: 1000 * 1000, //one second + }, + merchant_pub: "ASDWQEKASJDKSADJ", + }, +}); diff --git a/packages/merchant-backoffice-ui/src/paths/instance/index.stories.ts b/packages/merchant-backoffice-ui/src/paths/instance/index.stories.ts new file mode 100644 index 000000000..8f06937df --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/index.stories.ts @@ -0,0 +1,18 @@ +/* + This file is part of GNU Taler + (C) 2021-2024 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +export * as details from "./details/stories.js"; +export * as kycList from "./kyc/list/ListPage.stories.js"; diff --git a/packages/merchant-backoffice-ui/src/paths/instance/kyc/list/ListPage.stories.tsx b/packages/merchant-backoffice-ui/src/paths/instance/kyc/list/ListPage.stories.tsx new file mode 100644 index 000000000..046636b4b --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/kyc/list/ListPage.stories.tsx @@ -0,0 +1,57 @@ +/* + This file is part of GNU Taler + (C) 2021-2024 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +/** + * + * @author Sebastian Javier Marchano (sebasjm) + */ + +import { PaytoString } from "@gnu-taler/taler-util"; +import * as tests from "@gnu-taler/web-util/testing"; +import { ListPage as TestedComponent } from "./ListPage.js"; + +export default { + title: "Pages/KYC/List", + component: TestedComponent, + argTypes: { + onUpdate: { action: "onUpdate" }, + onBack: { action: "onBack" }, + }, +}; + +export const Example = tests.createExample(TestedComponent, { + status: { + timeout_kycs: [], + pending_kycs: [ + { + aml_status: 0, + exchange_url: "http://exchange.taler", + payto_uri: "payto://iban/de123123123" as PaytoString, + kyc_url: "http://exchange.taler/kyc", + }, + { + aml_status: 1, + exchange_url: "http://exchange.taler", + payto_uri: "payto://iban/de123123123" as PaytoString, + }, + { + aml_status: 2, + exchange_url: "http://exchange.taler", + payto_uri: "payto://iban/de123123123" as PaytoString, + }, + ], + }, +}); diff --git a/packages/merchant-backoffice-ui/src/paths/instance/kyc/list/ListPage.tsx b/packages/merchant-backoffice-ui/src/paths/instance/kyc/list/ListPage.tsx index 6b9a50660..3eeed1d7b 100644 --- a/packages/merchant-backoffice-ui/src/paths/instance/kyc/list/ListPage.tsx +++ b/packages/merchant-backoffice-ui/src/paths/instance/kyc/list/ListPage.tsx @@ -1,6 +1,6 @@ /* This file is part of GNU Taler - (C) 2021 Taler Systems S.A. + (C) 2021-2024 Taler Systems S.A. GNU Taler is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -19,16 +19,16 @@ * @author Sebastian Javier Marchano (sebasjm) */ +import { TalerMerchantApi } from "@gnu-taler/taler-util"; +import { useTranslationContext } from "@gnu-taler/web-util/browser"; import { h, VNode } from "preact"; -import { MerchantBackend } from "../../../../declaration.js"; -import { Translate, useTranslator } from "../../../../i18n/index.js"; export interface Props { - status: MerchantBackend.Instances.AccountKycRedirects; + status: TalerMerchantApi.AccountKycRedirects; } export function ListPage({ status }: Props): VNode { - const i18n = useTranslator(); + const { i18n } = useTranslationContext(); return ( <section class="section is-main-section"> @@ -38,7 +38,7 @@ export function ListPage({ status }: Props): VNode { <span class="icon"> <i class="mdi mdi-clock" /> </span> - <Translate>Pending KYC verification</Translate> + <i18n.Translate>Pending KYC verification</i18n.Translate> </p> <div class="card-header-icon" aria-label="more options" /> @@ -63,7 +63,7 @@ export function ListPage({ status }: Props): VNode { <span class="icon"> <i class="mdi mdi-clock" /> </span> - <Translate>Timed out</Translate> + <i18n.Translate>Timed out</i18n.Translate> </p> <div class="card-header-icon" aria-label="more options" /> @@ -85,43 +85,71 @@ export function ListPage({ status }: Props): VNode { ); } interface PendingTableProps { - entries: MerchantBackend.Instances.MerchantAccountKycRedirect[]; + entries: TalerMerchantApi.MerchantAccountKycRedirect[]; } interface TimedOutTableProps { - entries: MerchantBackend.Instances.ExchangeKycTimeout[]; + entries: TalerMerchantApi.ExchangeKycTimeout[]; } function PendingTable({ entries }: PendingTableProps): VNode { + const { i18n } = useTranslationContext(); return ( <div class="table-container"> <table class="table is-striped is-hoverable is-fullwidth"> <thead> <tr> <th> - <Translate>Exchange</Translate> + <i18n.Translate>Exchange</i18n.Translate> </th> <th> - <Translate>Target account</Translate> + <i18n.Translate>Target account</i18n.Translate> </th> <th> - <Translate>KYC URL</Translate> + <i18n.Translate>Reason</i18n.Translate> </th> </tr> </thead> <tbody> {entries.map((e, i) => { - return ( - <tr key={i}> - <td>{e.exchange_url}</td> - <td>{e.payto_uri}</td> - <td> - <a href={e.kyc_url} target="_black" rel="noreferrer"> - {e.kyc_url} - </a> - </td> - </tr> - ); + if (e.kyc_url === undefined) { + // blocked by AML + return ( + <tr key={i}> + <td>{e.exchange_url}</td> + <td>{e.payto_uri}</td> + <td> + {e.aml_status === 1 ? ( + <i18n.Translate> + There is an anti-money laundering process pending to + complete. + </i18n.Translate> + ) : ( + <i18n.Translate> + The account is frozen due to the anti-money laundering + rules. Contact the exchange service provider for further + instructions. + </i18n.Translate> + )} + </td> + </tr> + ); + } else { + // blocked by KYC + return ( + <tr key={i}> + <td>{e.exchange_url}</td> + <td>{e.payto_uri}</td> + <td> + <a href={e.kyc_url} target="_black" rel="noreferrer"> + <i18n.Translate> + Pending KYC process, click here to complete + </i18n.Translate> + </a> + </td> + </tr> + ); + } })} </tbody> </table> @@ -130,19 +158,20 @@ function PendingTable({ entries }: PendingTableProps): VNode { } function TimedOutTable({ entries }: TimedOutTableProps): VNode { + const { i18n } = useTranslationContext(); return ( <div class="table-container"> <table class="table is-striped is-hoverable is-fullwidth"> <thead> <tr> <th> - <Translate>Exchange</Translate> + <i18n.Translate>Exchange</i18n.Translate> </th> <th> - <Translate>Code</Translate> + <i18n.Translate>Code</i18n.Translate> </th> <th> - <Translate>Http Status</Translate> + <i18n.Translate>Http Status</i18n.Translate> </th> </tr> </thead> @@ -163,6 +192,7 @@ function TimedOutTable({ entries }: TimedOutTableProps): VNode { } function EmptyTable(): VNode { + const { i18n } = useTranslationContext(); return ( <div class="content has-text-grey has-text-centered"> <p> @@ -171,7 +201,7 @@ function EmptyTable(): VNode { </span> </p> <p> - <Translate>No pending kyc verification!</Translate> + <i18n.Translate>No pending kyc verification!</i18n.Translate> </p> </div> ); diff --git a/packages/merchant-backoffice-ui/src/paths/instance/kyc/list/index.tsx b/packages/merchant-backoffice-ui/src/paths/instance/kyc/list/index.tsx index 3ef95cb34..ed0e1220f 100644 --- a/packages/merchant-backoffice-ui/src/paths/instance/kyc/list/index.tsx +++ b/packages/merchant-backoffice-ui/src/paths/instance/kyc/list/index.tsx @@ -1,6 +1,6 @@ /* This file is part of GNU Taler - (C) 2021 Taler Systems S.A. + (C) 2021-2024 Taler Systems S.A. GNU Taler is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -19,30 +19,55 @@ * @author Sebastian Javier Marchano (sebasjm) */ -import { h, VNode } from "preact"; +import { HttpStatusCode, TalerError, assertUnreachable } from "@gnu-taler/taler-util"; +import { VNode, h } from "preact"; +import { ErrorLoadingMerchant } from "../../../../components/ErrorLoadingMerchant.js"; import { Loading } from "../../../../components/exception/loading.js"; -import { HttpError } from "../../../../hooks/backend.js"; import { useInstanceKYCDetails } from "../../../../hooks/instance.js"; import { ListPage } from "./ListPage.js"; interface Props { - onUnauthorized: () => VNode; - onLoadError: (error: HttpError) => VNode; - onNotFound: () => VNode; } -export default function ListKYC({ - onUnauthorized, - onLoadError, - onNotFound, -}: Props): VNode { +export default function ListKYC(_p: Props): VNode { const result = useInstanceKYCDetails(); - if (result.clientError && result.isUnauthorized) return onUnauthorized(); - if (result.clientError && result.isNotfound) return onNotFound(); - if (result.loading) return <Loading />; - if (!result.ok) return onLoadError(result); + if (!result) return <Loading /> + if (result instanceof TalerError) { + return <ErrorLoadingMerchant error={result} /> + } + /** + * This component just render known kyc requirements. + * If query fail then is safe to hide errors. + */ + if (result.type === "fail") { + switch (result.case) { + case HttpStatusCode.GatewayTimeout: { + return <div /> + } + case HttpStatusCode.BadGateway: { + const status = result.body; + + if (!status) { + return <div>no kyc required</div>; + } + return <ListPage status={status} />; - const status = result.data.type === "ok" ? undefined : result.data.status; + } + case HttpStatusCode.ServiceUnavailable: { + return <div /> + } + case HttpStatusCode.Unauthorized: { + return <div /> + } + case HttpStatusCode.NotFound: { + return <div />; + } + default: { + assertUnreachable(result) + } + } + } + const status = result.body; if (!status) { return <div>no kyc required</div>; diff --git a/packages/merchant-backoffice-ui/src/paths/instance/orders/create/Create.stories.tsx b/packages/merchant-backoffice-ui/src/paths/instance/orders/create/Create.stories.tsx index e658dff8f..fc814b68f 100644 --- a/packages/merchant-backoffice-ui/src/paths/instance/orders/create/Create.stories.tsx +++ b/packages/merchant-backoffice-ui/src/paths/instance/orders/create/Create.stories.tsx @@ -1,6 +1,6 @@ /* This file is part of GNU Taler - (C) 2021 Taler Systems S.A. + (C) 2021-2024 Taler Systems S.A. GNU Taler is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -33,7 +33,7 @@ export default { function createExample<Props>( Component: FunctionalComponent<Props>, - props: Partial<Props> + props: Partial<Props>, ) { const r = (args: any) => <Component {...args} />; r.args = props; @@ -42,12 +42,13 @@ function createExample<Props>( export const Example = createExample(TestedComponent, { instanceConfig: { - default_max_deposit_fee: "", - default_max_wire_fee: "", default_pay_delay: { - d_us: 1000 * 60 * 60, + d_us: 1000 * 1000 * 60 * 60, //one hour }, - default_wire_fee_amortization: 1, + default_wire_transfer_delay: { + d_us: 1000 * 1000 * 60 * 60, //one hour + }, + use_stefan: true, }, instanceInventory: [ { diff --git a/packages/merchant-backoffice-ui/src/paths/instance/orders/create/CreatePage.tsx b/packages/merchant-backoffice-ui/src/paths/instance/orders/create/CreatePage.tsx index 56bb65b90..7be3d23f6 100644 --- a/packages/merchant-backoffice-ui/src/paths/instance/orders/create/CreatePage.tsx +++ b/packages/merchant-backoffice-ui/src/paths/instance/orders/create/CreatePage.tsx @@ -1,6 +1,6 @@ /* This file is part of GNU Taler - (C) 2021 Taler Systems S.A. + (C) 2021-2024 Taler Systems S.A. GNU Taler is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -19,69 +19,81 @@ * @author Sebastian Javier Marchano (sebasjm) */ -import { add, isAfter, isBefore, isFuture } from "date-fns"; -import { Amounts } from "@gnu-taler/taler-util"; -import { Fragment, h, VNode } from "preact"; +import { + AbsoluteTime, + AmountString, + Amounts, + Duration, + TalerMerchantApi, + TalerProtocolDuration, +} from "@gnu-taler/taler-util"; +import { + useTranslationContext +} from "@gnu-taler/web-util/browser"; +import { format, isFuture } from "date-fns"; +import { Fragment, VNode, h } from "preact"; import { useEffect, useState } from "preact/hooks"; import { - FormProvider, FormErrors, + FormProvider, } from "../../../../components/form/FormProvider.js"; import { Input } from "../../../../components/form/Input.js"; import { InputCurrency } from "../../../../components/form/InputCurrency.js"; import { InputDate } from "../../../../components/form/InputDate.js"; +import { InputDuration } from "../../../../components/form/InputDuration.js"; import { InputGroup } from "../../../../components/form/InputGroup.js"; import { InputLocation } from "../../../../components/form/InputLocation.js"; -import { ProductList } from "../../../../components/product/ProductList.js"; -import { useConfigContext } from "../../../../context/config.js"; -import { Duration, MerchantBackend, WithId } from "../../../../declaration.js"; -import { Translate, useTranslator } from "../../../../i18n/index.js"; -import { OrderCreateSchema as schema } from "../../../../schemas/index.js"; -import { rate } from "../../../../utils/amount.js"; +import { InputNumber } from "../../../../components/form/InputNumber.js"; +import { InputToggle } from "../../../../components/form/InputToggle.js"; import { InventoryProductForm } from "../../../../components/product/InventoryProductForm.js"; import { NonInventoryProductFrom } from "../../../../components/product/NonInventoryProductForm.js"; -import { InputNumber } from "../../../../components/form/InputNumber.js"; -import { InputBoolean } from "../../../../components/form/InputBoolean.js"; +import { ProductList } from "../../../../components/product/ProductList.js"; +import { useSessionContext } from "../../../../context/session.js"; +import { usePreference } from "../../../../hooks/preference.js"; +import { rate } from "../../../../utils/amount.js"; import { undefinedIfEmpty } from "../../../../utils/table.js"; interface Props { - onCreate: (d: MerchantBackend.Orders.PostOrderRequest) => void; + onCreate: (d: TalerMerchantApi.PostOrderRequest) => void; onBack?: () => void; instanceConfig: InstanceConfig; - instanceInventory: (MerchantBackend.Products.ProductDetail & WithId)[]; + instanceInventory: (TalerMerchantApi.ProductDetail & WithId)[]; } interface InstanceConfig { - default_max_wire_fee: string; - default_max_deposit_fee: string; - default_wire_fee_amortization: number; - default_pay_delay: Duration; + use_stefan: boolean; + default_pay_delay: TalerProtocolDuration; + default_wire_transfer_delay: TalerProtocolDuration; } -function with_defaults(config: InstanceConfig): Partial<Entity> { - const defaultPayDeadline = - !config.default_pay_delay || config.default_pay_delay.d_us === "forever" - ? undefined - : add(new Date(), { seconds: config.default_pay_delay.d_us / 1000 }); +function with_defaults( + config: InstanceConfig, + _currency: string, +): Partial<Entity> { + const defaultPayDeadline = Duration.fromTalerProtocolDuration( + config.default_pay_delay, + ); + const defaultWireDeadline = Duration.fromTalerProtocolDuration( + config.default_wire_transfer_delay, + ); return { inventoryProducts: {}, products: [], pricing: {}, payments: { - max_wire_fee: config.default_max_wire_fee, - max_fee: config.default_max_deposit_fee, - wire_fee_amortization: config.default_wire_fee_amortization, + max_fee: undefined, + createToken: true, pay_deadline: defaultPayDeadline, refund_deadline: defaultPayDeadline, - createToken: true, + wire_transfer_deadline: defaultWireDeadline, }, shipping: {}, - extra: "", + extra: {}, }; } interface ProductAndQuantity { - product: MerchantBackend.Products.ProductDetail & WithId; + product: TalerMerchantApi.ProductDetail & WithId; quantity: number; } export interface ProductMap { @@ -95,156 +107,144 @@ interface Pricing { } interface Shipping { delivery_date?: Date; - delivery_location?: MerchantBackend.Location; + delivery_location?: TalerMerchantApi.Location; fullfilment_url?: string; } interface Payments { - refund_deadline?: Date; - pay_deadline?: Date; - wire_transfer_deadline?: Date; - auto_refund_deadline?: Date; + refund_deadline: Duration; + pay_deadline: Duration; + wire_transfer_deadline: Duration; + auto_refund_deadline: Duration; max_fee?: string; - max_wire_fee?: string; - wire_fee_amortization?: number; createToken: boolean; minimum_age?: number; } interface Entity { inventoryProducts: ProductMap; - products: MerchantBackend.Product[]; + products: TalerMerchantApi.Product[]; pricing: Partial<Pricing>; payments: Partial<Payments>; shipping: Partial<Shipping>; - extra: string; + extra: Record<string, string>; } -const stringIsValidJSON = (value: string) => { - try { - JSON.parse(value.trim()); - return true; - } catch { - return false; - } -}; - export function CreatePage({ onCreate, onBack, instanceConfig, instanceInventory, }: Props): VNode { - const [value, valueHandler] = useState(with_defaults(instanceConfig)); - const config = useConfigContext(); + const { config } = useSessionContext(); + const instance_default = with_defaults(instanceConfig, config.currency); + const [value, valueHandler] = useState(instance_default); const zero = Amounts.zeroOfCurrency(config.currency); - + const [settings, updateSettings] = usePreference(); const inventoryList = Object.values(value.inventoryProducts || {}); const productList = Object.values(value.products || {}); - const i18n = useTranslator(); + const { i18n } = useTranslationContext(); + + const parsedPrice = !value.pricing?.order_price + ? undefined + : Amounts.parse(value.pricing.order_price); const errors: FormErrors<Entity> = { pricing: undefinedIfEmpty({ - summary: !value.pricing?.summary ? i18n`required` : undefined, + summary: !value.pricing?.summary ? i18n.str`required` : undefined, order_price: !value.pricing?.order_price - ? i18n`required` - : Amounts.isZero(value.pricing.order_price) - ? i18n`must be greater than 0` - : undefined, + ? i18n.str`required` + : !parsedPrice + ? i18n.str`not valid` + : Amounts.isZero(parsedPrice) + ? i18n.str`must be greater than 0` + : undefined, }), - extra: - value.extra && !stringIsValidJSON(value.extra) - ? i18n`not a valid json` - : undefined, payments: undefinedIfEmpty({ refund_deadline: !value.payments?.refund_deadline ? undefined - : !isFuture(value.payments.refund_deadline) - ? i18n`should be in the future` : value.payments.pay_deadline && - isBefore(value.payments.refund_deadline, value.payments.pay_deadline) - ? i18n`refund deadline cannot be before pay deadline` - : value.payments.wire_transfer_deadline && - isBefore( - value.payments.wire_transfer_deadline, - value.payments.refund_deadline - ) - ? i18n`wire transfer deadline cannot be before refund deadline` - : undefined, + Duration.cmp( + value.payments.refund_deadline, + value.payments.pay_deadline, + ) === -1 + ? i18n.str`refund deadline cannot be before pay deadline` + : value.payments.wire_transfer_deadline && + Duration.cmp( + value.payments.wire_transfer_deadline, + value.payments.refund_deadline, + ) === -1 + ? i18n.str`wire transfer deadline cannot be before refund deadline` + : undefined, pay_deadline: !value.payments?.pay_deadline - ? undefined - : !isFuture(value.payments.pay_deadline) - ? i18n`should be in the future` + ? i18n.str`required` : value.payments.wire_transfer_deadline && - isBefore( - value.payments.wire_transfer_deadline, - value.payments.pay_deadline - ) - ? i18n`wire transfer deadline cannot be before pay deadline` + Duration.cmp( + value.payments.wire_transfer_deadline, + value.payments.pay_deadline, + ) === -1 + ? i18n.str`wire transfer deadline cannot be before pay deadline` + : undefined, + wire_transfer_deadline: !value.payments?.wire_transfer_deadline + ? i18n.str`required` : undefined, auto_refund_deadline: !value.payments?.auto_refund_deadline ? undefined - : !isFuture(value.payments.auto_refund_deadline) - ? i18n`should be in the future` : !value.payments?.refund_deadline - ? i18n`should have a refund deadline` - : !isAfter( - value.payments.refund_deadline, - value.payments.auto_refund_deadline - ) - ? i18n`auto refund cannot be after refund deadline` - : undefined, + ? i18n.str`should have a refund deadline` + : Duration.cmp( + value.payments.refund_deadline, + value.payments.auto_refund_deadline, + ) == -1 + ? i18n.str`auto refund cannot be after refund deadline` + : undefined, }), shipping: undefinedIfEmpty({ delivery_date: !value.shipping?.delivery_date ? undefined : !isFuture(value.shipping.delivery_date) - ? i18n`should be in the future` - : undefined, + ? i18n.str`should be in the future` + : undefined, }), }; const hasErrors = Object.keys(errors).some( - (k) => (errors as any)[k] !== undefined + (k) => (errors as any)[k] !== undefined, ); const submit = (): void => { - const order = schema.cast(value); + const order = value as any; //schema.cast(value); if (!value.payments) return; if (!value.shipping) return; - const request: MerchantBackend.Orders.PostOrderRequest = { + const request: TalerMerchantApi.PostOrderRequest = { order: { amount: order.pricing.order_price, summary: order.pricing.summary, products: productList, - extra: value.extra, - pay_deadline: value.payments.pay_deadline - ? { - t_s: Math.floor(value.payments.pay_deadline.getTime() / 1000), - } - : undefined, - wire_transfer_deadline: value.payments.wire_transfer_deadline - ? { - t_s: Math.floor( - value.payments.wire_transfer_deadline.getTime() / 1000 - ), - } - : undefined, - refund_deadline: value.payments.refund_deadline - ? { - t_s: Math.floor(value.payments.refund_deadline.getTime() / 1000), - } - : undefined, + extra: undefinedIfEmpty(value.extra), + pay_deadline: AbsoluteTime.toProtocolTimestamp( + AbsoluteTime.addDuration( + AbsoluteTime.now(), + value.payments.pay_deadline!, + ), + ), + wire_transfer_deadline: AbsoluteTime.toProtocolTimestamp( + AbsoluteTime.addDuration( + AbsoluteTime.now(), + value.payments.wire_transfer_deadline!, + ), + ), + refund_deadline: AbsoluteTime.toProtocolTimestamp( + AbsoluteTime.addDuration( + AbsoluteTime.now(), + value.payments.refund_deadline!, + ), + ), auto_refund: value.payments.auto_refund_deadline - ? { - d_us: Math.floor( - value.payments.auto_refund_deadline.getTime() * 1000 - ), - } + ? Duration.toTalerProtocolDuration( + value.payments.auto_refund_deadline, + ) : undefined, - wire_fee_amortization: value.payments.wire_fee_amortization as number, - max_fee: value.payments.max_fee as string, - max_wire_fee: value.payments.max_wire_fee as string, - + max_fee: value.payments.max_fee as AmountString, delivery_date: value.shipping.delivery_date ? { t_s: value.shipping.delivery_date.getTime() / 1000 } : undefined, @@ -263,8 +263,8 @@ export function CreatePage({ }; const addProductToTheInventoryList = ( - product: MerchantBackend.Products.ProductDetail & WithId, - quantity: number + product: TalerMerchantApi.ProductDetail & WithId, + quantity: number, ) => { valueHandler((v) => { const inventoryProducts = { ...v.inventoryProducts }; @@ -281,7 +281,7 @@ export function CreatePage({ }); }; - const addNewProduct = async (product: MerchantBackend.Product) => { + const addNewProduct = async (product: TalerMerchantApi.Product) => { return valueHandler((v) => { const products = v.products ? [...v.products, product] : []; return { ...v, products }; @@ -297,7 +297,7 @@ export function CreatePage({ }; const [editingProduct, setEditingProduct] = useState< - MerchantBackend.Product | undefined + TalerMerchantApi.Product | undefined >(undefined); const totalPriceInventory = inventoryList.reduce((prev, cur) => { @@ -308,7 +308,7 @@ export function CreatePage({ const totalPriceProducts = productList.reduce((prev, cur) => { if (!cur.price) return zero; const p = Amounts.parseOrThrow(cur.price); - return Amounts.add(prev, Amounts.mult(p, cur.quantity).amount).amount; + return Amounts.add(prev, Amounts.mult(p, cur.quantity ?? 0).amount).amount; }, zero); const hasProducts = inventoryList.length > 0 || productList.length > 0; @@ -317,6 +317,8 @@ export function CreatePage({ const totalAsString = Amounts.stringify(totalPrice.amount); const allProducts = productList.concat(inventoryList.map(asProduct)); + const [newField, setNewField] = useState(""); + useEffect(() => { valueHandler((v) => { return { @@ -331,25 +333,65 @@ export function CreatePage({ }, [hasProducts, totalAsString]); const discountOrRise = rate( - value.pricing?.order_price || `${config.currency}:0`, - totalAsString + parsedPrice ?? Amounts.zeroOfCurrency(config.currency), + totalPrice.amount, ); - const minAgeByProducts = allProducts.reduce( + const minAgeByProducts = inventoryList.reduce( (cur, prev) => - !prev.minimum_age || cur > prev.minimum_age ? cur : prev.minimum_age, - 0 + !prev.product.minimum_age || cur > prev.product.minimum_age ? cur : prev.product.minimum_age, + 0, ); + + // if there is no default pay deadline + const noDefault_payDeadline = + !instance_default.payments || !instance_default.payments.pay_deadline; + // and there is no default wire deadline + const noDefault_wireDeadline = + !instance_default.payments || + !instance_default.payments.wire_transfer_deadline; + // user required to set the taler options + const requiresSomeTalerOptions = + noDefault_payDeadline || noDefault_wireDeadline; + return ( <div> <section class="section is-main-section"> + <div class="tabs is-toggle is-fullwidth is-small"> + <ul> + <li + class={!settings.advanceOrderMode ? "is-active" : ""} + onClick={() => { + updateSettings("advanceOrderMode", false); + }} + > + <a> + <span> + <i18n.Translate>Simple</i18n.Translate> + </span> + </a> + </li> + <li + class={settings.advanceOrderMode ? "is-active" : ""} + onClick={() => { + updateSettings("advanceOrderMode", true); + }} + > + <a> + <span> + <i18n.Translate>Advanced</i18n.Translate> + </span> + </a> + </li> + </ul> + </div> <div class="columns"> <div class="column" /> <div class="column is-four-fifths"> {/* // FIXME: translating plural singular */} <InputGroup name="inventory_products" - label={i18n`Manage products in order`} + label={i18n.str`Manage products in order`} alternative={ allProducts.length > 0 && ( <p> @@ -358,7 +400,7 @@ export function CreatePage({ </p> ) } - tooltip={i18n`Manage list of products in the order.`} + tooltip={i18n.str`Manage list of products in the order.`} > <InventoryProductForm currentProducts={value.inventoryProducts || {}} @@ -366,21 +408,23 @@ export function CreatePage({ inventory={instanceInventory} /> - <NonInventoryProductFrom - productToEdit={editingProduct} - onAddProduct={(p) => { - setEditingProduct(undefined); - return addNewProduct(p); - }} - /> + {settings.advanceOrderMode && ( + <NonInventoryProductFrom + productToEdit={editingProduct} + onAddProduct={(p) => { + setEditingProduct(undefined); + return addNewProduct(p); + }} + /> + )} {allProducts.length > 0 && ( <ProductList list={allProducts} actions={[ { - name: i18n`Remove`, - tooltip: i18n`Remove this product from the order.`, + name: i18n.str`Remove`, + tooltip: i18n.str`Remove this product from the order.`, handler: (e, index) => { if (e.product_id) { removeProductFromTheInventoryList(e.product_id); @@ -404,141 +448,299 @@ export function CreatePage({ <Fragment> <InputCurrency name="pricing.products_price" - label={i18n`Total price`} + label={i18n.str`Total price`} readonly - tooltip={i18n`total product price added up`} + tooltip={i18n.str`total product price added up`} /> <InputCurrency name="pricing.order_price" - label={i18n`Total price`} + label={i18n.str`Total price`} addonAfter={ discountOrRise > 0 && (discountOrRise < 1 ? `discount of %${Math.round( - (1 - discountOrRise) * 100 + (1 - discountOrRise) * 100, )}` : `rise of %${Math.round((discountOrRise - 1) * 100)}`) } - tooltip={i18n`Amount to be paid by the customer`} + tooltip={i18n.str`Amount to be paid by the customer`} /> </Fragment> ) : ( <InputCurrency name="pricing.order_price" - label={i18n`Order price`} - tooltip={i18n`final order price`} + label={i18n.str`Order price`} + tooltip={i18n.str`final order price`} /> )} <Input name="pricing.summary" inputType="multiline" - label={i18n`Summary`} - tooltip={i18n`Title of the order to be shown to the customer`} + label={i18n.str`Summary`} + tooltip={i18n.str`Title of the order to be shown to the customer`} /> - <InputGroup - name="shipping" - label={i18n`Shipping and Fulfillment`} - initialActive - > - <InputDate - name="shipping.delivery_date" - label={i18n`Delivery date`} - tooltip={i18n`Deadline for physical delivery assured by the merchant.`} - /> - {value.shipping?.delivery_date && ( - <InputGroup - name="shipping.delivery_location" - label={i18n`Location`} - tooltip={i18n`address where the products will be delivered`} - > - <InputLocation name="shipping.delivery_location" /> - </InputGroup> - )} - <Input - name="shipping.fullfilment_url" - label={i18n`Fulfillment URL`} - tooltip={i18n`URL to which the user will be redirected after successful payment.`} - /> - </InputGroup> - - <InputGroup - name="payments" - label={i18n`Taler payment options`} - tooltip={i18n`Override default Taler payment settings for this order`} - > - <InputDate - name="payments.pay_deadline" - label={i18n`Payment deadline`} - tooltip={i18n`Deadline for the customer to pay for the offer before it expires. Inventory products will be reserved until this deadline.`} - /> - <InputDate - name="payments.refund_deadline" - label={i18n`Refund deadline`} - tooltip={i18n`Time until which the order can be refunded by the merchant.`} - /> - <InputDate - name="payments.wire_transfer_deadline" - label={i18n`Wire transfer deadline`} - tooltip={i18n`Deadline for the exchange to make the wire transfer.`} - /> - <InputDate - name="payments.auto_refund_deadline" - label={i18n`Auto-refund deadline`} - tooltip={i18n`Time until which the wallet will automatically check for refunds without user interaction.`} - /> + {settings.advanceOrderMode && ( + <InputGroup + name="shipping" + label={i18n.str`Shipping and Fulfillment`} + initialActive + > + <InputDate + name="shipping.delivery_date" + label={i18n.str`Delivery date`} + tooltip={i18n.str`Deadline for physical delivery assured by the merchant.`} + /> + {value.shipping?.delivery_date && ( + <InputGroup + name="shipping.delivery_location" + label={i18n.str`Location`} + tooltip={i18n.str`address where the products will be delivered`} + > + <InputLocation name="shipping.delivery_location" /> + </InputGroup> + )} + <Input + name="shipping.fullfilment_url" + label={i18n.str`Fulfillment URL`} + tooltip={i18n.str`URL to which the user will be redirected after successful payment.`} + /> + </InputGroup> + )} - <InputCurrency - name="payments.max_fee" - label={i18n`Maximum deposit fee`} - tooltip={i18n`Maximum deposit fees the merchant is willing to cover for this order. Higher deposit fees must be covered in full by the consumer.`} - /> - <InputCurrency - name="payments.max_wire_fee" - label={i18n`Maximum wire fee`} - tooltip={i18n`Maximum aggregate wire fees the merchant is willing to cover for this order. Wire fees exceeding this amount are to be covered by the customers.`} - /> - <InputNumber - name="payments.wire_fee_amortization" - label={i18n`Wire fee amortization`} - tooltip={i18n`Factor by which wire fees exceeding the above threshold are divided to determine the share of excess wire fees to be paid explicitly by the consumer.`} - /> - <InputBoolean - name="payments.createToken" - label={i18n`Create token`} - tooltip={i18n`Uncheck this option if the merchant backend generated an order ID with enough entropy to prevent adversarial claims.`} - /> - <InputNumber - name="payments.minimum_age" - label={i18n`Minimum age required`} - tooltip={i18n`Any value greater than 0 will limit the coins able be used to pay this contract. If empty the age restriction will be defined by the products`} - help={ - minAgeByProducts > 0 - ? i18n`Min age defined by the producs is ${minAgeByProducts}` - : undefined - } - /> - </InputGroup> + {(settings.advanceOrderMode || requiresSomeTalerOptions) && ( + <InputGroup + name="payments" + label={i18n.str`Taler payment options`} + tooltip={i18n.str`Override default Taler payment settings for this order`} + > + {(settings.advanceOrderMode || noDefault_payDeadline) && ( + <InputDuration + name="payments.pay_deadline" + label={i18n.str`Payment time`} + help={ + <DeadlineHelp duration={value.payments?.pay_deadline} /> + } + withForever + withoutClear + tooltip={i18n.str`Time for the customer to pay for the offer before it expires. Inventory products will be reserved until this deadline. Time start to run after the order is created.`} + side={ + <span> + <button + class="button" + onClick={() => { + const c = { + ...value, + payments: { + ...(value.payments ?? {}), + pay_deadline: + instance_default.payments?.pay_deadline, + }, + }; + valueHandler(c); + }} + > + <i18n.Translate>default</i18n.Translate> + </button> + </span> + } + /> + )} + {settings.advanceOrderMode && ( + <InputDuration + name="payments.refund_deadline" + label={i18n.str`Refund time`} + help={ + <DeadlineHelp + duration={value.payments?.refund_deadline} + /> + } + withForever + withoutClear + tooltip={i18n.str`Time while the order can be refunded by the merchant. Time starts after the order is created.`} + side={ + <span> + <button + class="button" + onClick={() => { + valueHandler({ + ...value, + payments: { + ...(value.payments ?? {}), + refund_deadline: + instance_default.payments?.refund_deadline, + }, + }); + }} + > + <i18n.Translate>default</i18n.Translate> + </button> + </span> + } + /> + )} + {(settings.advanceOrderMode || noDefault_wireDeadline) && ( + <InputDuration + name="payments.wire_transfer_deadline" + label={i18n.str`Wire transfer time`} + help={ + <DeadlineHelp + duration={value.payments?.wire_transfer_deadline} + /> + } + withoutClear + withForever + tooltip={i18n.str`Time for the exchange to make the wire transfer. Time starts after the order is created.`} + side={ + <span> + <button + class="button" + onClick={() => { + valueHandler({ + ...value, + payments: { + ...(value.payments ?? {}), + wire_transfer_deadline: + instance_default.payments + ?.wire_transfer_deadline, + }, + }); + }} + > + <i18n.Translate>default</i18n.Translate> + </button> + </span> + } + /> + )} + {settings.advanceOrderMode && ( + <InputDuration + name="payments.auto_refund_deadline" + label={i18n.str`Auto-refund time`} + help={ + <DeadlineHelp + duration={value.payments?.auto_refund_deadline} + /> + } + tooltip={i18n.str`Time until which the wallet will automatically check for refunds without user interaction.`} + withForever + /> + )} + + {settings.advanceOrderMode && ( + <InputCurrency + name="payments.max_fee" + label={i18n.str`Maximum fee`} + tooltip={i18n.str`Maximum fees the merchant is willing to cover for this order. Higher deposit fees must be covered in full by the consumer.`} + /> + )} + {settings.advanceOrderMode && ( + <InputToggle + name="payments.createToken" + label={i18n.str`Create token`} + tooltip={i18n.str`If the order ID is easy to guess the token will prevent user to steal orders from others.`} + /> + )} + {settings.advanceOrderMode && ( + <InputNumber + name="payments.minimum_age" + label={i18n.str`Minimum age required`} + tooltip={i18n.str`Any value greater than 0 will limit the coins able be used to pay this contract. If empty the age restriction will be defined by the products`} + help={ + minAgeByProducts > 0 + ? i18n.str`Min age defined by the producs is ${minAgeByProducts}` + : i18n.str`No product with age restriction in this order` + } + /> + )} + </InputGroup> + )} - <InputGroup - name="extra" - label={i18n`Additional information`} - tooltip={i18n`Custom information to be included in the contract for this order.`} - > - <Input + {settings.advanceOrderMode && ( + <InputGroup name="extra" - inputType="multiline" - label={`Value`} - tooltip={i18n`You must enter a value in JavaScript Object Notation (JSON).`} - /> - </InputGroup> + label={i18n.str`Additional information`} + tooltip={i18n.str`Custom information to be included in the contract for this order.`} + > + {Object.keys(value.extra ?? {}).map((key, idx) => { + return ( + <Input + name={`extra.${key}`} + key={String(idx)} + inputType="multiline" + label={key} + tooltip={i18n.str`You must enter a value in JavaScript Object Notation (JSON).`} + side={ + <button + class="button" + onClick={(e) => { + if ( + value.extra && + value.extra[key] !== undefined + ) { + delete value.extra[key]; + } + valueHandler({ + ...value, + }); + e.preventDefault(); + }} + > + remove + </button> + } + /> + ); + })} + <div class="field is-horizontal"> + <div class="field-label is-normal"> + <label class="label"> + <i18n.Translate>Custom field name</i18n.Translate> + <span + class="icon has-tooltip-right" + data-tooltip={"new extra field"} + > + <i class="mdi mdi-information" /> + </span> + </label> + </div> + <div class="field-body is-flex-grow-3"> + <div class="field"> + <p class="control"> + <input + class="input " + value={newField} + onChange={(e) => setNewField(e.currentTarget.value)} + /> + </p> + </div> + </div> + <button + class="button" + onClick={(e) => { + setNewField(""); + valueHandler({ + ...value, + extra: { + ...(value.extra ?? {}), + [newField]: "", + }, + }); + e.preventDefault(); + }} + > + add + </button> + </div> + </InputGroup> + )} </FormProvider> <div class="buttons is-right mt-5"> {onBack && ( <button class="button" onClick={onBack}> - <Translate>Cancel</Translate> + <i18n.Translate>Cancel</i18n.Translate> </button> )} <button @@ -546,7 +748,7 @@ export function CreatePage({ onClick={submit} disabled={hasErrors} > - <Translate>Confirm</Translate> + <i18n.Translate>Confirm</i18n.Translate> </button> </div> </div> @@ -557,7 +759,7 @@ export function CreatePage({ ); } -function asProduct(p: ProductAndQuantity): MerchantBackend.Product { +function asProduct(p: ProductAndQuantity): TalerMerchantApi.Product { return { product_id: p.product.id, image: p.product.image, @@ -566,6 +768,27 @@ function asProduct(p: ProductAndQuantity): MerchantBackend.Product { quantity: p.quantity, description: p.product.description, taxes: p.product.taxes, - minimum_age: p.product.minimum_age, }; } + +function DeadlineHelp({ duration }: { duration?: Duration }): VNode { + const { i18n } = useTranslationContext(); + const [now, setNow] = useState(AbsoluteTime.now()); + useEffect(() => { + const iid = setInterval(() => { + setNow(AbsoluteTime.now()); + }, 60 * 1000); + return () => { + clearInterval(iid); + }; + }); + if (!duration) return <i18n.Translate>Disabled</i18n.Translate>; + const when = AbsoluteTime.addDuration(now, duration); + if (when.t_ms === "never") + return <i18n.Translate>No deadline</i18n.Translate>; + return ( + <i18n.Translate> + Deadline at {format(when.t_ms, "dd/MM/yy HH:mm")} + </i18n.Translate> + ); +} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/orders/create/OrderCreatedSuccessfully.tsx b/packages/merchant-backoffice-ui/src/paths/instance/orders/create/OrderCreatedSuccessfully.tsx index d94013da3..32f3f05c7 100644 --- a/packages/merchant-backoffice-ui/src/paths/instance/orders/create/OrderCreatedSuccessfully.tsx +++ b/packages/merchant-backoffice-ui/src/paths/instance/orders/create/OrderCreatedSuccessfully.tsx @@ -1,6 +1,6 @@ /* This file is part of GNU Taler - (C) 2021 Taler Systems S.A. + (C) 2021-2024 Taler Systems S.A. GNU Taler is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -13,12 +13,15 @@ You should have received a copy of the GNU General Public License along with GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> */ -import { h, VNode } from "preact"; -import { useEffect, useState } from "preact/hooks"; +import { HttpStatusCode, TalerError, assertUnreachable } from "@gnu-taler/taler-util"; +import { Loading, useTranslationContext } from "@gnu-taler/web-util/browser"; +import { VNode, h } from "preact"; +import { ErrorLoadingMerchant } from "../../../../components/ErrorLoadingMerchant.js"; import { CreatedSuccessfully } from "../../../../components/notifications/CreatedSuccessfully.js"; -import { useOrderAPI } from "../../../../hooks/order.js"; -import { Translate } from "../../../../i18n/index.js"; +import { useOrderDetails } from "../../../../hooks/order.js"; +import { NotFoundPageOrAdminCreate } from "../../../notfound/index.js"; import { Entity } from "./index.js"; +import { LoginPage } from "../../../login/index.js"; interface Props { entity: Entity; @@ -26,64 +29,113 @@ interface Props { onCreateAnother?: () => void; } -export function OrderCreatedSuccessfully({ entity, onConfirm, onCreateAnother }: Props): VNode { - const { getPaymentURL } = useOrderAPI() - const [url, setURL] = useState<string | undefined>(undefined) +export function OrderCreatedSuccessfully({ + entity, + onConfirm, + onCreateAnother, +}: Props): VNode { + const result = useOrderDetails(entity.response.order_id) + const { i18n } = useTranslationContext(); - useEffect(() => { - getPaymentURL(entity.response.order_id).then(response => { - setURL(response.data) - }) - }, [getPaymentURL, entity.response.order_id]) + if (!result) return <Loading /> + if (result instanceof TalerError) { + return <ErrorLoadingMerchant error={result} /> + } + if (result.type === "fail") { + switch(result.case) { + case HttpStatusCode.NotFound: { + return <NotFoundPageOrAdminCreate /> + } + case HttpStatusCode.BadGateway: { + return <div>Failed to obtain a response from the exchange</div>; + } + case HttpStatusCode.GatewayTimeout: { + return ( + <div>The merchant's interaction with the exchange took too long</div> + ); + } + case HttpStatusCode.Unauthorized: { + return <LoginPage /> + } + default: { + assertUnreachable(result) + } + } + } - return <CreatedSuccessfully onConfirm={onConfirm} onCreateAnother={onCreateAnother}> - <div class="field is-horizontal"> - <div class="field-label is-normal"> - <label class="label"><Translate>Amount</Translate></label> - </div> - <div class="field-body is-flex-grow-3"> - <div class="field"> - <p class="control"> - <input class="input" readonly value={entity.request.order.amount} /> - </p> + const url = result.body.order_status === "unpaid" ? + result.body.taler_pay_uri : + result.body.contract_terms.fulfillment_url + + return ( + <CreatedSuccessfully + onConfirm={onConfirm} + onCreateAnother={onCreateAnother} + > + <div class="field is-horizontal"> + <div class="field-label is-normal"> + <label class="label"> + <i18n.Translate>Amount</i18n.Translate> + </label> </div> - </div> - </div> - <div class="field is-horizontal"> - <div class="field-label is-normal"> - <label class="label"><Translate>Summary</Translate></label> - </div> - <div class="field-body is-flex-grow-3"> - <div class="field"> - <p class="control"> - <input class="input" readonly value={entity.request.order.summary} /> - </p> + <div class="field-body is-flex-grow-3"> + <div class="field"> + <p class="control"> + <input + class="input" + readonly + value={entity.request.order.amount} + /> + </p> + </div> </div> </div> - </div> - <div class="field is-horizontal"> - <div class="field-label is-normal"> - <label class="label"><Translate>Order ID</Translate></label> - </div> - <div class="field-body is-flex-grow-3"> - <div class="field"> - <p class="control"> - <input class="input" readonly value={entity.response.order_id} /> - </p> + <div class="field is-horizontal"> + <div class="field-label is-normal"> + <label class="label"> + <i18n.Translate>Summary</i18n.Translate> + </label> + </div> + <div class="field-body is-flex-grow-3"> + <div class="field"> + <p class="control"> + <input + class="input" + readonly + value={entity.request.order.summary} + /> + </p> + </div> </div> </div> - </div> - <div class="field is-horizontal"> - <div class="field-label is-normal"> - <label class="label"><Translate>Payment URL</Translate></label> + <div class="field is-horizontal"> + <div class="field-label is-normal"> + <label class="label"> + <i18n.Translate>Order ID</i18n.Translate> + </label> + </div> + <div class="field-body is-flex-grow-3"> + <div class="field"> + <p class="control"> + <input class="input" readonly value={entity.response.order_id} /> + </p> + </div> + </div> </div> - <div class="field-body is-flex-grow-3"> - <div class="field"> - <p class="control"> - <input class="input" readonly value={url} /> - </p> + <div class="field is-horizontal"> + <div class="field-label is-normal"> + <label class="label"> + <i18n.Translate>Payment URL</i18n.Translate> + </label> + </div> + <div class="field-body is-flex-grow-3"> + <div class="field"> + <p class="control"> + <input class="input" readonly value={url} /> + </p> + </div> </div> </div> - </div> - </CreatedSuccessfully>; + </CreatedSuccessfully> + ); } diff --git a/packages/merchant-backoffice-ui/src/paths/instance/orders/create/index.tsx b/packages/merchant-backoffice-ui/src/paths/instance/orders/create/index.tsx index b58a6507e..861114014 100644 --- a/packages/merchant-backoffice-ui/src/paths/instance/orders/create/index.tsx +++ b/packages/merchant-backoffice-ui/src/paths/instance/orders/create/index.tsx @@ -1,6 +1,6 @@ /* This file is part of GNU Taler - (C) 2021 Taler Systems S.A. + (C) 2021-2024 Taler Systems S.A. GNU Taler is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -15,68 +15,106 @@ */ /** -* -* @author Sebastian Javier Marchano (sebasjm) -*/ + * + * @author Sebastian Javier Marchano (sebasjm) + */ -import { Fragment, h, VNode } from 'preact'; -import { useState } from 'preact/hooks'; +import { HttpStatusCode, TalerError, TalerMerchantApi, assertUnreachable } from "@gnu-taler/taler-util"; +import { Fragment, VNode, h } from "preact"; +import { useState } from "preact/hooks"; +import { ErrorLoadingMerchant } from "../../../../components/ErrorLoadingMerchant.js"; import { Loading } from "../../../../components/exception/loading.js"; import { NotificationCard } from "../../../../components/menu/index.js"; -import { MerchantBackend } from "../../../../declaration.js"; -import { HttpError } from "../../../../hooks/backend.js"; +import { useSessionContext } from "../../../../context/session.js"; import { useInstanceDetails } from "../../../../hooks/instance.js"; -import { useOrderAPI } from "../../../../hooks/order.js"; import { useInstanceProducts } from "../../../../hooks/product.js"; import { Notification } from "../../../../utils/types.js"; +import { LoginPage } from "../../../login/index.js"; +import { NotFoundPageOrAdminCreate } from "../../../notfound/index.js"; import { CreatePage } from "./CreatePage.js"; -import { OrderCreatedSuccessfully } from "./OrderCreatedSuccessfully.js"; export type Entity = { - request: MerchantBackend.Orders.PostOrderRequest, - response: MerchantBackend.Orders.PostOrderResponse -} + request: TalerMerchantApi.PostOrderRequest; + response: TalerMerchantApi.PostOrderResponse; +}; interface Props { onBack?: () => void; - onConfirm: () => void; - onUnauthorized: () => VNode; - onNotFound: () => VNode; - onLoadError: (error: HttpError) => VNode; + onConfirm: (id: string) => void; } -export default function OrderCreate({ onConfirm, onBack, onLoadError, onNotFound, onUnauthorized }: Props): VNode { - const { createOrder } = useOrderAPI() - const [notif, setNotif] = useState<Notification | undefined>(undefined) - - const detailsResult = useInstanceDetails() - const inventoryResult = useInstanceProducts() - - if (detailsResult.clientError && detailsResult.isUnauthorized) return onUnauthorized() - if (detailsResult.clientError && detailsResult.isNotfound) return onNotFound() - if (detailsResult.loading) return <Loading /> - if (!detailsResult.ok) return onLoadError(detailsResult) +export default function OrderCreate({ + onConfirm, + onBack, +}: Props): VNode { + const { lib } = useSessionContext(); + const [notif, setNotif] = useState<Notification | undefined>(undefined); + const { state } = useSessionContext(); + const detailsResult = useInstanceDetails(); + const inventoryResult = useInstanceProducts(); - if (inventoryResult.clientError && inventoryResult.isUnauthorized) return onUnauthorized() - if (inventoryResult.clientError && inventoryResult.isNotfound) return onNotFound() - if (inventoryResult.loading) return <Loading /> - if (!inventoryResult.ok) return onLoadError(inventoryResult) + if (!detailsResult) return <Loading /> + if (detailsResult instanceof TalerError) { + return <ErrorLoadingMerchant error={detailsResult} /> + } + if (detailsResult.type === "fail") { + switch (detailsResult.case) { + case HttpStatusCode.Unauthorized: { + return <LoginPage /> + } + case HttpStatusCode.NotFound: { + return <NotFoundPageOrAdminCreate />; + } + default: { + assertUnreachable(detailsResult); + } + } + } + if (!inventoryResult) return <Loading /> + if (inventoryResult instanceof TalerError) { + return <ErrorLoadingMerchant error={inventoryResult} /> + } + if (inventoryResult.type === "fail") { + switch (inventoryResult.case) { + case HttpStatusCode.NotFound: { + return <NotFoundPageOrAdminCreate />; + } + case HttpStatusCode.Unauthorized: { + return <LoginPage /> + } + default: { + assertUnreachable(inventoryResult); + } + } + } - return <Fragment> - - <NotificationCard notification={notif} /> + return ( + <Fragment> + <NotificationCard notification={notif} /> - <CreatePage - onBack={onBack} - onCreate={(request: MerchantBackend.Orders.PostOrderRequest) => { - createOrder(request).then(onConfirm).catch((error) => { - setNotif({ - message: 'could not create order', - type: "ERROR", - description: error.message - }) - }) - }} - instanceConfig={detailsResult.data} - instanceInventory={inventoryResult.data} + <CreatePage + onBack={onBack} + onCreate={(request: TalerMerchantApi.PostOrderRequest) => { + lib.instance.createOrder(state.token, request) + .then((r) => { + if (r.type === "ok") { + return onConfirm(r.body.order_id) + } else { + setNotif({ + message: "could not create order", + type: "ERROR", + }); + } + }) + .catch((error) => { + setNotif({ + message: "could not create order", + type: "ERROR", + description: error.message, + }); + }); + }} + instanceConfig={detailsResult.body} + instanceInventory={inventoryResult.body} /> - </Fragment> + </Fragment> + ); } diff --git a/packages/merchant-backoffice-ui/src/paths/instance/orders/details/Detail.stories.tsx b/packages/merchant-backoffice-ui/src/paths/instance/orders/details/Detail.stories.tsx index 8c21665e6..7d4877db9 100644 --- a/packages/merchant-backoffice-ui/src/paths/instance/orders/details/Detail.stories.tsx +++ b/packages/merchant-backoffice-ui/src/paths/instance/orders/details/Detail.stories.tsx @@ -1,6 +1,6 @@ /* This file is part of GNU Taler - (C) 2021 Taler Systems S.A. + (C) 2021-2024 Taler Systems S.A. GNU Taler is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -19,9 +19,9 @@ * @author Sebastian Javier Marchano (sebasjm) */ +import { AmountString, TalerMerchantApi } from "@gnu-taler/taler-util"; import { addDays } from "date-fns"; -import { h, VNode, FunctionalComponent } from "preact"; -import { MerchantBackend } from "../../../../declaration.js"; +import { FunctionalComponent, h } from "preact"; import { DetailPage as TestedComponent } from "./DetailPage.js"; export default { @@ -35,28 +35,25 @@ export default { function createExample<Props>( Component: FunctionalComponent<Props>, - props: Partial<Props> + props: Partial<Props>, ) { const r = (args: any) => <Component {...args} />; r.args = props; return r; } -const defaultContractTerm = { - amount: "TESTKUDOS:10", +const defaultContractTerm: TalerMerchantApi.ContractTerms = { + amount: "TESTKUDOS:10" as AmountString, timestamp: { t_s: new Date().getTime() / 1000, }, - auditors: [], exchanges: [], - max_fee: "TESTKUDOS:1", - max_wire_fee: "TESTKUDOS:1", + max_fee: "TESTKUDOS:1" as AmountString, merchant: {} as any, merchant_base_url: "http://merchant.url/", order_id: "2021.165-03GDFC26Y1NNG", products: [], summary: "text summary", - wire_fee_amortization: 1, wire_transfer_deadline: { t_s: "never", }, @@ -68,7 +65,7 @@ const defaultContractTerm = { }, wire_method: "x-taler-bank", h_wire: "asd", -} as MerchantBackend.ContractTerms; +}; // contract_terms: defaultContracTerm, export const Claimed = createExample(TestedComponent, { @@ -85,16 +82,16 @@ export const PaidNotRefundable = createExample(TestedComponent, { order_status: "paid", contract_terms: defaultContractTerm, refunded: false, - deposit_total: "TESTKUDOS:10", - exchange_ec: 0, + deposit_total: "TESTKUDOS:10" as AmountString, + exchange_code: 0, order_status_url: "http://merchant.backend/status", - exchange_hc: 0, - refund_amount: "TESTKUDOS:0", + exchange_http_status: 0, + refund_amount: "TESTKUDOS:0" as AmountString, refund_details: [], refund_pending: false, wire_details: [], - wire_reports: [], wired: false, + wire_reports: [], }, }); @@ -109,15 +106,15 @@ export const PaidRefundable = createExample(TestedComponent, { }, }, refunded: false, - deposit_total: "TESTKUDOS:10", - exchange_ec: 0, + deposit_total: "TESTKUDOS:10" as AmountString, + exchange_code: 0, order_status_url: "http://merchant.backend/status", - exchange_hc: 0, - refund_amount: "TESTKUDOS:0", + exchange_http_status: 0, + refund_amount: "TESTKUDOS:0" as AmountString, refund_details: [], + wire_reports: [], refund_pending: false, wire_details: [], - wire_reports: [], wired: false, }, }); @@ -132,6 +129,6 @@ export const Unpaid = createExample(TestedComponent, { }, summary: "text summary", taler_pay_uri: "pay uri", - total_amount: "TESTKUDOS:10", + total_amount: "TESTKUDOS:10" as AmountString, }, }); diff --git a/packages/merchant-backoffice-ui/src/paths/instance/orders/details/DetailPage.tsx b/packages/merchant-backoffice-ui/src/paths/instance/orders/details/DetailPage.tsx index 3445a86df..498ea83e3 100644 --- a/packages/merchant-backoffice-ui/src/paths/instance/orders/details/DetailPage.tsx +++ b/packages/merchant-backoffice-ui/src/paths/instance/orders/details/DetailPage.tsx @@ -1,6 +1,6 @@ /* This file is part of GNU Taler - (C) 2021 Taler Systems S.A. + (C) 2021-2024 Taler Systems S.A. GNU Taler is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -19,9 +19,17 @@ * @author Sebastian Javier Marchano (sebasjm) */ -import { AmountJson, Amounts } from "@gnu-taler/taler-util"; -import { format } from "date-fns"; -import { Fragment, h, VNode } from "preact"; +import { + AmountJson, + Amounts, + TalerMerchantApi, + stringifyRefundUri, +} from "@gnu-taler/taler-util"; +import { + useTranslationContext +} from "@gnu-taler/web-util/browser"; +import { format, formatDistance } from "date-fns"; +import { Fragment, VNode, h } from "preact"; import { useState } from "preact/hooks"; import { FormProvider } from "../../../../components/form/FormProvider.js"; import { Input } from "../../../../components/form/Input.js"; @@ -32,108 +40,98 @@ import { InputGroup } from "../../../../components/form/InputGroup.js"; import { InputLocation } from "../../../../components/form/InputLocation.js"; import { TextField } from "../../../../components/form/TextField.js"; import { ProductList } from "../../../../components/product/ProductList.js"; -import { useBackendContext } from "../../../../context/backend.js"; -import { MerchantBackend } from "../../../../declaration.js"; -import { Translate, useTranslator } from "../../../../i18n/index.js"; +import { useSessionContext } from "../../../../context/session.js"; +import { + datetimeFormatForSettings, + usePreference, +} from "../../../../hooks/preference.js"; import { mergeRefunds } from "../../../../utils/amount.js"; import { RefundModal } from "../list/Table.js"; import { Event, Timeline } from "./Timeline.js"; -type Entity = MerchantBackend.Orders.MerchantOrderStatusResponse; -type CT = MerchantBackend.ContractTerms; +type Entity = TalerMerchantApi.MerchantOrderStatusResponse; +type CT = TalerMerchantApi.ContractTerms; interface Props { onBack: () => void; selected: Entity; id: string; - onRefund: (id: string, value: MerchantBackend.Orders.RefundRequest) => void; + onRefund: (id: string, value: TalerMerchantApi.RefundRequest) => void; } -type Paid = MerchantBackend.Orders.CheckPaymentPaidResponse & { +type Paid = TalerMerchantApi.CheckPaymentPaidResponse & { refund_taken: string; }; -type Unpaid = MerchantBackend.Orders.CheckPaymentUnpaidResponse; -type Claimed = MerchantBackend.Orders.CheckPaymentClaimedResponse; +type Unpaid = TalerMerchantApi.CheckPaymentUnpaidResponse; +type Claimed = TalerMerchantApi.CheckPaymentClaimedResponse; function ContractTerms({ value }: { value: CT }) { - const i18n = useTranslator(); + const { i18n } = useTranslationContext(); return ( - <InputGroup name="contract_terms" label={i18n`Contract Terms`}> + <InputGroup name="contract_terms" label={i18n.str`Contract Terms`}> <FormProvider<CT> object={value} valueHandler={null}> <Input<CT> readonly name="summary" - label={i18n`Summary`} - tooltip={i18n`human-readable description of the whole purchase`} + label={i18n.str`Summary`} + tooltip={i18n.str`human-readable description of the whole purchase`} /> <InputCurrency<CT> readonly name="amount" - label={i18n`Amount`} - tooltip={i18n`total price for the transaction`} + label={i18n.str`Amount`} + tooltip={i18n.str`total price for the transaction`} /> {value.fulfillment_url && ( <Input<CT> readonly name="fulfillment_url" - label={i18n`Fulfillment URL`} - tooltip={i18n`URL for this purchase`} + label={i18n.str`Fulfillment URL`} + tooltip={i18n.str`URL for this purchase`} /> )} <Input<CT> readonly name="max_fee" - label={i18n`Max fee`} - tooltip={i18n`maximum total deposit fee accepted by the merchant for this contract`} - /> - <Input<CT> - readonly - name="max_wire_fee" - label={i18n`Max wire fee`} - tooltip={i18n`maximum wire fee accepted by the merchant`} - /> - <Input<CT> - readonly - name="wire_fee_amortization" - label={i18n`Wire fee amortization`} - tooltip={i18n`over how many customer transactions does the merchant expect to amortize wire fees on average`} + label={i18n.str`Max fee`} + tooltip={i18n.str`maximum total deposit fee accepted by the merchant for this contract`} /> <InputDate<CT> readonly name="timestamp" - label={i18n`Created at`} - tooltip={i18n`time when this contract was generated`} + label={i18n.str`Created at`} + tooltip={i18n.str`time when this contract was generated`} /> <InputDate<CT> readonly name="refund_deadline" - label={i18n`Refund deadline`} - tooltip={i18n`after this deadline has passed no refunds will be accepted`} + label={i18n.str`Refund deadline`} + tooltip={i18n.str`after this deadline has passed no refunds will be accepted`} /> <InputDate<CT> readonly name="pay_deadline" - label={i18n`Payment deadline`} - tooltip={i18n`after this deadline, the merchant won't accept payments for the contract`} + label={i18n.str`Payment deadline`} + tooltip={i18n.str`after this deadline, the merchant won't accept payments for the contract`} /> <InputDate<CT> readonly name="wire_transfer_deadline" - label={i18n`Wire transfer deadline`} - tooltip={i18n`transfer deadline for the exchange`} + label={i18n.str`Wire transfer deadline`} + tooltip={i18n.str`transfer deadline for the exchange`} /> <InputDate<CT> readonly name="delivery_date" - label={i18n`Delivery date`} - tooltip={i18n`time indicating when the order should be delivered`} + label={i18n.str`Delivery date`} + tooltip={i18n.str`time indicating when the order should be delivered`} /> {value.delivery_date && ( <InputGroup name="delivery_location" - label={i18n`Location`} - tooltip={i18n`where the order will be delivered`} + label={i18n.str`Location`} + tooltip={i18n.str`where the order will be delivered`} > <InputLocation name="payments.delivery_location" /> </InputGroup> @@ -141,14 +139,14 @@ function ContractTerms({ value }: { value: CT }) { <InputDuration<CT> readonly name="auto_refund" - label={i18n`Auto-refund delay`} - tooltip={i18n`how long the wallet should try to get an automatic refund for the purchase`} + label={i18n.str`Auto-refund delay`} + tooltip={i18n.str`how long the wallet should try to get an automatic refund for the purchase`} /> <Input<CT> readonly name="extra" - label={i18n`Extra info`} - tooltip={i18n`extra data that is only interpreted by the merchant frontend`} + label={i18n.str`Extra info`} + tooltip={i18n.str`extra data that is only interpreted by the merchant frontend`} /> </FormProvider> </InputGroup> @@ -160,8 +158,12 @@ function ClaimedPage({ order, }: { id: string; - order: MerchantBackend.Orders.CheckPaymentClaimedResponse; + order: TalerMerchantApi.CheckPaymentClaimedResponse; }) { + const now = new Date(); + const refundable = + order.contract_terms.refund_deadline.t_s !== "never" && + now.getTime() < order.contract_terms.refund_deadline.t_s * 1000; const events: Event[] = []; if (order.contract_terms.timestamp.t_s !== "never") { events.push({ @@ -177,20 +179,20 @@ function ClaimedPage({ type: "deadline", }); } - if (order.contract_terms.refund_deadline.t_s !== "never") { + if (order.contract_terms.refund_deadline.t_s !== "never" && refundable) { events.push({ when: new Date(order.contract_terms.refund_deadline.t_s * 1000), description: "refund deadline", type: "deadline", }); } - if (order.contract_terms.wire_transfer_deadline.t_s !== "never") { - events.push({ - when: new Date(order.contract_terms.wire_transfer_deadline.t_s * 1000), - description: "wire deadline", - type: "deadline", - }); - } + // if (order.contract_terms.wire_transfer_deadline.t_s !== "never") { + // events.push({ + // when: new Date(order.contract_terms.wire_transfer_deadline.t_s * 1000), + // description: "wire deadline", + // type: "deadline", + // }); + // } if ( order.contract_terms.delivery_date && order.contract_terms.delivery_date.t_s !== "never" @@ -203,7 +205,8 @@ function ClaimedPage({ } const [value, valueHandler] = useState<Partial<Claimed>>(order); - const i18n = useTranslator(); + const { i18n } = useTranslationContext(); + const [settings] = usePreference(); return ( <div> @@ -216,13 +219,14 @@ function ClaimedPage({ <div class="level"> <div class="level-left"> <div class="level-item"> - <Translate>Order</Translate> #{id} + <i18n.Translate>Order</i18n.Translate> #{id} <div class="tag is-info ml-4"> - <Translate>claimed</Translate> + <i18n.Translate>claimed</i18n.Translate> </div> </div> </div> </div> + <div class="level"> <div class="level-left"> <div class="level-item"> @@ -244,12 +248,16 @@ function ClaimedPage({ > <p> <b> - <Translate>claimed at</Translate>: + <i18n.Translate>claimed at</i18n.Translate>: </b>{" "} - {format( - new Date(order.contract_terms.timestamp.t_s * 1000), - "yyyy-MM-dd HH:mm:ss" - )} + {order.contract_terms.timestamp.t_s === "never" + ? "never" + : format( + new Date( + order.contract_terms.timestamp.t_s * 1000, + ), + datetimeFormatForSettings(settings), + )} </p> </div> </div> @@ -262,13 +270,13 @@ function ClaimedPage({ <div class="columns"> <div class="column is-4"> <div class="title"> - <Translate>Timeline</Translate> + <i18n.Translate>Timeline</i18n.Translate> </div> <Timeline events={events} /> </div> <div class="column is-8"> <div class="title"> - <Translate>Payment details</Translate> + <i18n.Translate>Payment details</i18n.Translate> </div> <FormProvider<Claimed> object={value} @@ -278,17 +286,17 @@ function ClaimedPage({ name="contract_terms.summary" readonly inputType="multiline" - label={i18n`Summary`} + label={i18n.str`Summary`} /> <InputCurrency name="contract_terms.amount" readonly - label={i18n`Amount`} + label={i18n.str`Amount`} /> <Input<Claimed> name="order_status" readonly - label={i18n`Order status`} + label={i18n.str`Order status`} /> </FormProvider> </div> @@ -298,7 +306,7 @@ function ClaimedPage({ {order.contract_terms.products.length ? ( <Fragment> <div class="title"> - <Translate>Product list</Translate> + <i18n.Translate>Product list</i18n.Translate> </div> <ProductList list={order.contract_terms.products} /> </Fragment> @@ -320,25 +328,16 @@ function PaidPage({ onRefund, }: { id: string; - order: MerchantBackend.Orders.CheckPaymentPaidResponse; + order: TalerMerchantApi.CheckPaymentPaidResponse; onRefund: (id: string) => void; }) { + const now = new Date(); + const refundable = + order.contract_terms.refund_deadline.t_s !== "never" && + now.getTime() < order.contract_terms.refund_deadline.t_s * 1000; + const events: Event[] = []; - if (order.contract_terms.timestamp.t_s !== "never") { - events.push({ - when: new Date(order.contract_terms.timestamp.t_s * 1000), - description: "order created", - type: "start", - }); - } - if (order.contract_terms.pay_deadline.t_s !== "never") { - events.push({ - when: new Date(order.contract_terms.pay_deadline.t_s * 1000), - description: "pay deadline", - type: "deadline", - }); - } - if (order.contract_terms.refund_deadline.t_s !== "never") { + if (order.contract_terms.refund_deadline.t_s !== "never" && refundable) { events.push({ when: new Date(order.contract_terms.refund_deadline.t_s * 1000), description: "refund deadline", @@ -372,61 +371,72 @@ function PaidPage({ }); } }); - if (order.wire_details && order.wire_details.length) { - if (order.wire_details.length > 1) { - let last: MerchantBackend.Orders.TransactionWireTransfer | null = null; - let first: MerchantBackend.Orders.TransactionWireTransfer | null = null; - let total: AmountJson | null = null; - - order.wire_details.forEach((w) => { - if (last === null || last.execution_time.t_s < w.execution_time.t_s) { - last = w; - } - if (first === null || first.execution_time.t_s > w.execution_time.t_s) { - first = w; - } - total = - total === null - ? Amounts.parseOrThrow(w.amount) - : Amounts.add(total, Amounts.parseOrThrow(w.amount)).amount; - }); - const last_time = last!.execution_time.t_s; - if (last_time !== "never") { - events.push({ - when: new Date(last_time * 1000), - description: `wired ${Amounts.stringify(total!)}`, - type: "wired-range", - }); - } - const first_time = first!.execution_time.t_s; - if (first_time !== "never") { - events.push({ - when: new Date(first_time * 1000), - description: `wire transfer started...`, - type: "wired-range", + const ra = !order.refunded ? undefined : Amounts.parse(order.refund_amount); + const am = Amounts.parseOrThrow(order.contract_terms.amount); + if (ra && Amounts.cmp(ra, am) === 1) { + if (order.wire_details && order.wire_details.length) { + if (order.wire_details.length > 1) { + let last: TalerMerchantApi.TransactionWireTransfer | null = null; + let first: TalerMerchantApi.TransactionWireTransfer | null = null; + let total: AmountJson | null = null; + + order.wire_details.forEach((w) => { + if (last === null || last.execution_time.t_s < w.execution_time.t_s) { + last = w; + } + if ( + first === null || + first.execution_time.t_s > w.execution_time.t_s + ) { + first = w; + } + total = + total === null + ? Amounts.parseOrThrow(w.amount) + : Amounts.add(total, Amounts.parseOrThrow(w.amount)).amount; }); - } - } else { - order.wire_details.forEach((e) => { - if (e.execution_time.t_s !== "never") { + const last_time = last!.execution_time.t_s; + if (last_time !== "never") { events.push({ - when: new Date(e.execution_time.t_s * 1000), - description: `wired ${e.amount}`, - type: "wired", + when: new Date(last_time * 1000), + description: `wired ${Amounts.stringify(total!)}`, + type: "wired-range", }); } - }); + const first_time = first!.execution_time.t_s; + if (first_time !== "never") { + events.push({ + when: new Date(first_time * 1000), + description: `wire transfer started...`, + type: "wired-range", + }); + } + } else { + order.wire_details.forEach((e) => { + if (e.execution_time.t_s !== "never") { + events.push({ + when: new Date(e.execution_time.t_s * 1000), + description: `wired ${e.amount}`, + type: "wired", + }); + } + }); + } } } + const nextEvent = events.find((e) => { + return e.when.getTime() > now.getTime(); + }); + const [value, valueHandler] = useState<Partial<Paid>>(order); - const { url } = useBackendContext(); - const refundHost = url.replace(/.*:\/\//, ""); // remove protocol part - const proto = url.startsWith("http://") ? "taler+http" : "taler"; - const refundurl = `${proto}://refund/${refundHost}/${order.contract_terms.order_id}/`; - const refundable = - new Date().getTime() < order.contract_terms.refund_deadline.t_s * 1000; - const i18n = useTranslator(); + const { state } = useSessionContext(); + + const refundurl = stringifyRefundUri({ + merchantBaseUrl: state.backendUrl.href, + orderId: order.contract_terms.order_id, + }); + const { i18n } = useTranslationContext(); const amount = Amounts.parseOrThrow(order.contract_terms.amount); const refund_taken = order.refund_details.reduce((prev, cur) => { @@ -446,18 +456,18 @@ function PaidPage({ <div class="level"> <div class="level-left"> <div class="level-item"> - <Translate>Order</Translate> #{id} + <i18n.Translate>Order</i18n.Translate> #{id} <div class="tag is-success ml-4"> - <Translate>paid</Translate> + <i18n.Translate>paid</i18n.Translate> </div> {order.wired ? ( <div class="tag is-success ml-4"> - <Translate>wired</Translate> + <i18n.Translate>wired</i18n.Translate> </div> ) : null} {order.refunded ? ( <div class="tag is-danger ml-4"> - <Translate>refunded</Translate> + <i18n.Translate>refunded</i18n.Translate> </div> ) : null} </div> @@ -477,8 +487,8 @@ function PaidPage({ class="has-tooltip-left" data-tooltip={ refundable - ? i18n`refund order` - : i18n`not refundable` + ? i18n.str`refund order` + : i18n.str`not refundable` } > <button @@ -486,7 +496,7 @@ function PaidPage({ disabled={!refundable} onClick={() => onRefund(id)} > - <Translate>refund</Translate> + <i18n.Translate>refund</i18n.Translate> </button> </span> </div> @@ -504,24 +514,18 @@ function PaidPage({ whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis", - // maxWidth: '100%', }} > - <p> - <a - href={order.contract_terms.fulfillment_url} - rel="nofollow" - target="new" - > - {order.contract_terms.fulfillment_url} - </a> - </p> - <p> - {format( - new Date(order.contract_terms.timestamp.t_s * 1000), - "yyyy/MM/dd HH:mm:ss" - )} - </p> + {nextEvent && ( + <p> + <i18n.Translate>Next event in </i18n.Translate>{" "} + {formatDistance( + nextEvent.when, + new Date(), + // "yyyy/MM/dd HH:mm:ss", + )} + </p> + )} </div> </div> </div> @@ -533,41 +537,41 @@ function PaidPage({ <div class="columns"> <div class="column is-4"> <div class="title"> - <Translate>Timeline</Translate> + <i18n.Translate>Timeline</i18n.Translate> </div> <Timeline events={events} /> </div> <div class="column is-8"> <div class="title"> - <Translate>Payment details</Translate> + <i18n.Translate>Payment details</i18n.Translate> </div> <FormProvider<Paid> object={value} valueHandler={valueHandler} > - {/* <InputCurrency<Paid> name="deposit_total" readonly label={i18n`Deposit total`} /> */} + {/* <InputCurrency<Paid> name="deposit_total" readonly label={i18n.str`Deposit total`} /> */} {order.refunded && ( <InputCurrency<Paid> name="refund_amount" readonly - label={i18n`Refunded amount`} + label={i18n.str`Refunded amount`} /> )} {order.refunded && ( <InputCurrency<Paid> name="refund_taken" readonly - label={i18n`Refund taken`} + label={i18n.str`Refund taken`} /> )} <Input<Paid> name="order_status" readonly - label={i18n`Order status`} + label={i18n.str`Order status`} /> <TextField<Paid> name="order_status_url" - label={i18n`Status URL`} + label={i18n.str`Status URL`} > <a target="_blank" @@ -580,7 +584,7 @@ function PaidPage({ {order.refunded && ( <TextField<Paid> name="order_status_url" - label={i18n`Refund URI`} + label={i18n.str`Refund URI`} > <a target="_blank" rel="noreferrer" href={refundurl}> {refundurl} @@ -595,7 +599,7 @@ function PaidPage({ {order.contract_terms.products.length ? ( <Fragment> <div class="title"> - <Translate>Product list</Translate> + <i18n.Translate>Product list</i18n.Translate> </div> <ProductList list={order.contract_terms.products} /> </Fragment> @@ -617,10 +621,11 @@ function UnpaidPage({ order, }: { id: string; - order: MerchantBackend.Orders.CheckPaymentUnpaidResponse; + order: TalerMerchantApi.CheckPaymentUnpaidResponse; }) { const [value, valueHandler] = useState<Partial<Unpaid>>(order); - const i18n = useTranslator(); + const { i18n } = useTranslationContext(); + const [settings] = usePreference(); return ( <div> <section class="hero is-hero-bar"> @@ -629,11 +634,11 @@ function UnpaidPage({ <div class="level-left"> <div class="level-item"> <h1 class="title"> - <Translate>Order</Translate> #{id} + <i18n.Translate>Order</i18n.Translate> #{id} </h1> </div> <div class="tag is-dark"> - <Translate>unpaid</Translate> + <i18n.Translate>unpaid</i18n.Translate> </div> </div> </div> @@ -651,7 +656,7 @@ function UnpaidPage({ > <p> <b> - <Translate>pay at</Translate>: + <i18n.Translate>pay at</i18n.Translate>: </b>{" "} <a href={order.order_status_url} @@ -663,13 +668,13 @@ function UnpaidPage({ </p> <p> <b> - <Translate>created at</Translate>: + <i18n.Translate>created at</i18n.Translate>: </b>{" "} {order.creation_time.t_s === "never" ? "never" : format( new Date(order.creation_time.t_s * 1000), - "yyyy-MM-dd HH:mm:ss" + datetimeFormatForSettings(settings), )} </p> </div> @@ -687,26 +692,29 @@ function UnpaidPage({ <Input<Unpaid> readonly name="summary" - label={i18n`Summary`} - tooltip={i18n`human-readable description of the whole purchase`} + label={i18n.str`Summary`} + tooltip={i18n.str`human-readable description of the whole purchase`} /> <InputCurrency<Unpaid> readonly name="total_amount" - label={i18n`Amount`} - tooltip={i18n`total price for the transaction`} + label={i18n.str`Amount`} + tooltip={i18n.str`total price for the transaction`} /> <Input<Unpaid> name="order_status" readonly - label={i18n`Order status`} + label={i18n.str`Order status`} /> <Input<Unpaid> name="order_status_url" readonly - label={i18n`Order status URL`} + label={i18n.str`Order status URL`} /> - <TextField<Unpaid> name="taler_pay_uri" label={i18n`Payment URI`}> + <TextField<Unpaid> + name="taler_pay_uri" + label={i18n.str`Payment URI`} + > <a target="_blank" rel="noreferrer" href={value.taler_pay_uri}> {value.taler_pay_uri} </a> @@ -722,7 +730,7 @@ function UnpaidPage({ export function DetailPage({ id, selected, onRefund, onBack }: Props): VNode { const [showRefund, setShowRefund] = useState<string | undefined>(undefined); - + const { i18n } = useTranslationContext(); const DetailByStatus = function () { switch (selected.order_status) { case "claimed": @@ -734,10 +742,10 @@ export function DetailPage({ id, selected, onRefund, onBack }: Props): VNode { default: return ( <div> - <Translate> + <i18n.Translate> Unknown order status. This is an error, please contact the administrator. - </Translate> + </i18n.Translate> </div> ); } @@ -761,7 +769,7 @@ export function DetailPage({ id, selected, onRefund, onBack }: Props): VNode { <div class="column is-four-fifths"> <div class="buttons is-right mt-5"> <button class="button" onClick={onBack}> - <Translate>Back</Translate> + <i18n.Translate>Back</i18n.Translate> </button> </div> </div> @@ -770,7 +778,3 @@ export function DetailPage({ id, selected, onRefund, onBack }: Props): VNode { </Fragment> ); } - -async function copyToClipboard(text: string) { - return navigator.clipboard.writeText(text); -} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/orders/details/Timeline.tsx b/packages/merchant-backoffice-ui/src/paths/instance/orders/details/Timeline.tsx index bea65607a..2d62e2252 100644 --- a/packages/merchant-backoffice-ui/src/paths/instance/orders/details/Timeline.tsx +++ b/packages/merchant-backoffice-ui/src/paths/instance/orders/details/Timeline.tsx @@ -1,6 +1,6 @@ /* This file is part of GNU Taler - (C) 2021 Taler Systems S.A. + (C) 2021-2024 Taler Systems S.A. GNU Taler is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -16,6 +16,7 @@ import { format } from "date-fns"; import { h } from "preact"; import { useEffect, useState } from "preact/hooks"; +import { datetimeFormatForSettings, usePreference } from "../../../../hooks/preference.js"; interface Props { events: Event[]; @@ -30,7 +31,7 @@ export function Timeline({ events: e }: Props) { }); events.sort((a, b) => a.when.getTime() - b.when.getTime()); - + const [settings] = usePreference(); const [state, setState] = useState(events); useEffect(() => { const handle = setTimeout(() => { @@ -67,7 +68,7 @@ export function Timeline({ events: e }: Props) { ); case "start": return ( - <div class="timeline-marker is-icon is-success"> + <div class="timeline-marker is-icon"> <i class="mdi mdi-flag " /> </div> ); @@ -104,7 +105,7 @@ export function Timeline({ events: e }: Props) { } })()} <div class="timeline-content"> - <p class="heading">{format(e.when, "yyyy/MM/dd HH:mm:ss")}</p> + {e.description !== "now" && <p class="heading">{format(e.when, datetimeFormatForSettings(settings))}</p>} <p>{e.description}</p> </div> </div> @@ -117,12 +118,12 @@ export interface Event { when: Date; description: string; type: - | "start" - | "refund" - | "refund-taken" - | "wired" - | "wired-range" - | "deadline" - | "delivery" - | "now"; + | "start" + | "refund" + | "refund-taken" + | "wired" + | "wired-range" + | "deadline" + | "delivery" + | "now"; } diff --git a/packages/merchant-backoffice-ui/src/paths/instance/orders/details/index.tsx b/packages/merchant-backoffice-ui/src/paths/instance/orders/details/index.tsx index 0549ab8ed..b28e59b29 100644 --- a/packages/merchant-backoffice-ui/src/paths/instance/orders/details/index.tsx +++ b/packages/merchant-backoffice-ui/src/paths/instance/orders/details/index.tsx @@ -1,6 +1,6 @@ /* This file is part of GNU Taler - (C) 2021 Taler Systems S.A. + (C) 2021-2024 Taler Systems S.A. GNU Taler is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -13,55 +13,94 @@ You should have received a copy of the GNU General Public License along with GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> */ -import { Fragment, h, VNode } from "preact"; +import { + HttpStatusCode, + TalerError, + assertUnreachable, +} from "@gnu-taler/taler-util"; +import { + useTranslationContext +} from "@gnu-taler/web-util/browser"; +import { Fragment, VNode, h } from "preact"; import { useState } from "preact/hooks"; +import { ErrorLoadingMerchant } from "../../../../components/ErrorLoadingMerchant.js"; import { Loading } from "../../../../components/exception/loading.js"; import { NotificationCard } from "../../../../components/menu/index.js"; -import { HttpError } from "../../../../hooks/backend.js"; -import { useOrderDetails, useOrderAPI } from "../../../../hooks/order.js"; -import { useTranslator } from "../../../../i18n/index.js"; +import { useSessionContext } from "../../../../context/session.js"; +import { useOrderDetails } from "../../../../hooks/order.js"; import { Notification } from "../../../../utils/types.js"; +import { LoginPage } from "../../../login/index.js"; +import { NotFoundPageOrAdminCreate } from "../../../notfound/index.js"; import { DetailPage } from "./DetailPage.js"; export interface Props { oid: string; - onBack: () => void; - onUnauthorized: () => VNode; - onNotFound: () => VNode; - onLoadError: (error: HttpError) => VNode; } -export default function Update({ oid, onBack, onLoadError, onNotFound, onUnauthorized }: Props): VNode { - const { refundOrder } = useOrderAPI(); - const result = useOrderDetails(oid) - const [notif, setNotif] = useState<Notification | undefined>(undefined) - - const i18n = useTranslator() +export default function Update({ oid, onBack }: Props): VNode { + const result = useOrderDetails(oid); + const [notif, setNotif] = useState<Notification | undefined>(undefined); + const { lib: api } = useSessionContext(); + const { state } = useSessionContext(); - if (result.clientError && result.isUnauthorized) return onUnauthorized() - if (result.clientError && result.isNotfound) return onNotFound() - if (result.loading) return <Loading /> - if (!result.ok) return onLoadError(result) + const { i18n } = useTranslationContext(); - return <Fragment> + if (!result) return <Loading />; + if (result instanceof TalerError) { + return <ErrorLoadingMerchant error={result} />; + } + if (result.type === "fail") { + switch (result.case) { + case HttpStatusCode.NotFound: { + return <NotFoundPageOrAdminCreate />; + } + case HttpStatusCode.BadGateway: { + return <div>Failed to obtain a response from the exchange</div>; + } + case HttpStatusCode.GatewayTimeout: { + return ( + <div>The merchant's interaction with the exchange took too long</div> + ); + } + case HttpStatusCode.Unauthorized: { + return <LoginPage /> + } + default: { + assertUnreachable(result); + } + } + } - <NotificationCard notification={notif} /> + return ( + <Fragment> + <NotificationCard notification={notif} /> - <DetailPage - onBack={onBack} - id={oid} - onRefund={(id, value) => refundOrder(id, value) - .then(() => setNotif({ - message: i18n`refund created successfully`, - type: "SUCCESS" - })).catch((error) => setNotif({ - message: i18n`could not create the refund`, - type: "ERROR", - description: error.message - })) - } - selected={result.data} - /> - </Fragment> -}
\ No newline at end of file + <DetailPage + onBack={onBack} + id={oid} + onRefund={(id, value) => { + if (state.status !== "loggedIn") { + return; + } + api.instance + .addRefund(state.token, id, value) + .then(() => + setNotif({ + message: i18n.str`refund created successfully`, + type: "SUCCESS", + }), + ) + .catch((error) => + setNotif({ + message: i18n.str`could not create the refund`, + type: "ERROR", + description: error.message, + }), + ); + }} + selected={result.body} + /> + </Fragment> + ); +} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/orders/list/List.stories.tsx b/packages/merchant-backoffice-ui/src/paths/instance/orders/list/List.stories.tsx index f68c3fd2e..5c9969689 100644 --- a/packages/merchant-backoffice-ui/src/paths/instance/orders/list/List.stories.tsx +++ b/packages/merchant-backoffice-ui/src/paths/instance/orders/list/List.stories.tsx @@ -1,6 +1,6 @@ /* This file is part of GNU Taler - (C) 2021 Taler Systems S.A. + (C) 2021-2024 Taler Systems S.A. GNU Taler is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -19,8 +19,9 @@ * @author Sebastian Javier Marchano (sebasjm) */ -import { h, VNode, FunctionalComponent } from "preact"; +import { FunctionalComponent, h } from "preact"; import { ListPage as TestedComponent } from "./ListPage.js"; +import { AmountString } from "@gnu-taler/taler-util"; export default { title: "Pages/Order/List", @@ -43,7 +44,7 @@ export default { function createExample<Props>( Component: FunctionalComponent<Props>, - props: Partial<Props> + props: Partial<Props>, ) { const r = (args: any) => <Component {...args} />; r.args = props; @@ -54,7 +55,7 @@ export const Example = createExample(TestedComponent, { orders: [ { id: "123", - amount: "TESTKUDOS:10", + amount: "TESTKUDOS:10" as AmountString, paid: false, refundable: true, row_id: 1, @@ -66,7 +67,7 @@ export const Example = createExample(TestedComponent, { }, { id: "234", - amount: "TESTKUDOS:12", + amount: "TESTKUDOS:12" as AmountString, paid: true, refundable: true, row_id: 2, @@ -79,7 +80,7 @@ export const Example = createExample(TestedComponent, { }, { id: "456", - amount: "TESTKUDOS:1", + amount: "TESTKUDOS:1" as AmountString, paid: false, refundable: false, row_id: 3, @@ -92,7 +93,7 @@ export const Example = createExample(TestedComponent, { }, { id: "234", - amount: "TESTKUDOS:12", + amount: "TESTKUDOS:12" as AmountString, paid: false, refundable: false, row_id: 4, diff --git a/packages/merchant-backoffice-ui/src/paths/instance/orders/list/ListPage.tsx b/packages/merchant-backoffice-ui/src/paths/instance/orders/list/ListPage.tsx index 69e60954f..408bc0c0a 100644 --- a/packages/merchant-backoffice-ui/src/paths/instance/orders/list/ListPage.tsx +++ b/packages/merchant-backoffice-ui/src/paths/instance/orders/list/ListPage.tsx @@ -1,6 +1,6 @@ /* This file is part of GNU Taler - (C) 2021 Taler Systems S.A. + (C) 2021-2024 Taler Systems S.A. GNU Taler is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -15,132 +15,208 @@ */ /** -* -* @author Sebastian Javier Marchano (sebasjm) -*/ + * + * @author Sebastian Javier Marchano (sebasjm) + */ -import { format } from 'date-fns'; -import { h, VNode } from 'preact'; -import { useState } from 'preact/hooks'; +import { AbsoluteTime, TalerMerchantApi } from "@gnu-taler/taler-util"; +import { useTranslationContext } from "@gnu-taler/web-util/browser"; +import { format } from "date-fns"; +import { Fragment, VNode, h } from "preact"; +import { useState } from "preact/hooks"; import { DatePicker } from "../../../../components/picker/DatePicker.js"; -import { MerchantBackend, WithId } from "../../../../declaration.js"; -import { Translate, useTranslator } from '../../../../i18n/index.js'; +import { dateFormatForSettings, usePreference } from "../../../../hooks/preference.js"; import { CardTable } from "./Table.js"; export interface ListPageProps { - errorOrderId: string | undefined, - - onShowAll: () => void, - onShowPaid: () => void, - onShowRefunded: () => void, - onShowNotWired: () => void, + onShowAll: () => void; + onShowNotPaid: () => void; + onShowPaid: () => void; + onShowRefunded: () => void; + onShowNotWired: () => void; + onShowWired: () => void; onCopyURL: (id: string) => void; - isAllActive: string, - isPaidActive: string, - isRefundedActive: string, - isNotWiredActive: string, + isAllActive: string; + isPaidActive: string; + isNotPaidActive: string; + isRefundedActive: string; + isNotWiredActive: string; + isWiredActive: string; - jumpToDate?: Date, - onSelectDate: (date?: Date) => void, + jumpToDate?: AbsoluteTime; + onSelectDate: (date?: AbsoluteTime) => void; - orders: (MerchantBackend.Orders.OrderHistoryEntry & WithId)[]; + orders: (TalerMerchantApi.OrderHistoryEntry & WithId)[]; onLoadMoreBefore?: () => void; - hasMoreBefore?: boolean; - hasMoreAfter?: boolean; onLoadMoreAfter?: () => void; - onSelectOrder: (o: MerchantBackend.Orders.OrderHistoryEntry & WithId) => void; - onRefundOrder: (o: MerchantBackend.Orders.OrderHistoryEntry & WithId) => void; - onSearchOrderById: (id: string) => void; + onSelectOrder: (o: TalerMerchantApi.OrderHistoryEntry & WithId) => void; + onRefundOrder: (o: TalerMerchantApi.OrderHistoryEntry & WithId) => void; onCreate: () => void; } -export function ListPage({ orders, errorOrderId, isAllActive, onSelectOrder, onRefundOrder, onSearchOrderById, jumpToDate, onCopyURL, onShowAll, onShowPaid, onShowRefunded, onShowNotWired, onSelectDate, isPaidActive, isRefundedActive, isNotWiredActive, onCreate }: ListPageProps): VNode { - const i18n = useTranslator(); - const dateTooltip = i18n`select date to show nearby orders`; +export function ListPage({ + onLoadMoreAfter, + onLoadMoreBefore, + orders, + isAllActive, + onSelectOrder, + onRefundOrder, + jumpToDate, + onCopyURL, + onShowAll, + onShowPaid, + onShowNotPaid, + onShowRefunded, + onShowNotWired, + onShowWired, + onSelectDate, + isPaidActive, + isRefundedActive, + isNotWiredActive, + onCreate, + isNotPaidActive, + isWiredActive, +}: ListPageProps): VNode { + const { i18n } = useTranslationContext(); + const dateTooltip = i18n.str`select date to show nearby orders`; const [pickDate, setPickDate] = useState(false); - const [orderId, setOrderId] = useState<string>(''); - - return <section class="section is-main-section"> + const [settings] = usePreference(); - <div class="level"> - <div class="level-left"> - <div class="level-item"> - <div class="field has-addons"> - <div class="control"> - <input class={errorOrderId ? "input is-danger" : "input"} type="text" value={orderId} onChange={e => setOrderId(e.currentTarget.value)} placeholder={i18n`order id`} /> - {errorOrderId && <p class="help is-danger">{errorOrderId}</p>} - </div> - <span class="has-tooltip-bottom" data-tooltip={i18n`jump to order with the given order ID`}> - <button class="button" onClick={(e) => onSearchOrderById(orderId)}> - <span class="icon"><i class="mdi mdi-arrow-right" /></span> - </button> - </span> + return ( + <Fragment> + <div class="columns"> + <div class="column is-two-thirds"> + <div class="tabs" style={{ overflow: "inherit" }}> + <ul> + <li class={isNotPaidActive}> + <div + class="has-tooltip-right" + data-tooltip={i18n.str`only show paid orders`} + > + <a onClick={onShowNotPaid}> + <i18n.Translate>New</i18n.Translate> + </a> + </div> + </li> + <li class={isPaidActive}> + <div + class="has-tooltip-right" + data-tooltip={i18n.str`only show paid orders`} + > + <a onClick={onShowPaid}> + <i18n.Translate>Paid</i18n.Translate> + </a> + </div> + </li> + <li class={isRefundedActive}> + <div + class="has-tooltip-right" + data-tooltip={i18n.str`only show orders with refunds`} + > + <a onClick={onShowRefunded}> + <i18n.Translate>Refunded</i18n.Translate> + </a> + </div> + </li> + <li class={isNotWiredActive}> + <div + class="has-tooltip-left" + data-tooltip={i18n.str`only show orders where customers paid, but wire payments from payment provider are still pending`} + > + <a onClick={onShowNotWired}> + <i18n.Translate>Not wired</i18n.Translate> + </a> + </div> + </li> + <li class={isWiredActive}> + <div + class="has-tooltip-left" + data-tooltip={i18n.str`only show orders where customers paid, but wire payments from payment provider are still pending`} + > + <a onClick={onShowWired}> + <i18n.Translate>Completed</i18n.Translate> + </a> + </div> + </li> + <li class={isAllActive}> + <div + class="has-tooltip-right" + data-tooltip={i18n.str`remove all filters`} + > + <a onClick={onShowAll}> + <i18n.Translate>All</i18n.Translate> + </a> + </div> + </li> + </ul> </div> </div> - </div> - </div> - <div class="columns"> - <div class="column is-two-thirds"> - <div class="tabs" style={{overflow:'inherit'}}> - <ul> - <li class={isAllActive}> - <div class="has-tooltip-right" data-tooltip={i18n`remove all filters`}> - <a onClick={onShowAll}><Translate>All</Translate></a> + <div class="column "> + <div class="buttons is-right"> + <div class="field has-addons"> + {jumpToDate && ( + <div class="control"> + <a class="button is-fullwidth" onClick={() => onSelectDate(undefined)}> + <span + class="icon" + data-tooltip={i18n.str`clear date filter`} + > + <i class="mdi mdi-close" /> + </span> + </a> + </div> + )} + <div class="control"> + <span class="has-tooltip-top" data-tooltip={dateTooltip}> + <input + class="input" + type="text" + readonly + value={!jumpToDate || jumpToDate.t_ms === "never" ? "" : format(jumpToDate.t_ms, dateFormatForSettings(settings))} + placeholder={i18n.str`date (${dateFormatForSettings(settings)})`} + onClick={() => { + setPickDate(true); + }} + /> + </span> </div> - </li> - <li class={isPaidActive}> - <div class="has-tooltip-right" data-tooltip={i18n`only show paid orders`}> - <a onClick={onShowPaid}><Translate>Paid</Translate></a> + <div class="control"> + <span class="has-tooltip-left" data-tooltip={dateTooltip}> + <a + class="button is-fullwidth" + onClick={() => { + setPickDate(true); + }} + > + <span class="icon"> + <i class="mdi mdi-calendar" /> + </span> + </a> + </span> </div> - </li> - <li class={isRefundedActive}> - <div class="has-tooltip-right" data-tooltip={i18n`only show orders with refunds`}> - <a onClick={onShowRefunded}><Translate>Refunded</Translate></a> - </div> - </li> - <li class={isNotWiredActive}> - <div class="has-tooltip-left" data-tooltip={i18n`only show orders where customers paid, but wire payments from payment provider are still pending`}> - <a onClick={onShowNotWired}><Translate>Not wired</Translate></a> - </div> - </li> - </ul> - </div> - </div> - <div class="column "> - <div class="buttons is-right"> - <div class="field has-addons"> - {jumpToDate && <div class="control"> - <a class="button" onClick={() => onSelectDate(undefined)}> - <span class="icon" data-tooltip={i18n`clear date filter`}><i class="mdi mdi-close" /></span> - </a> - </div>} - <div class="control"> - <span class="has-tooltip-top" data-tooltip={dateTooltip}> - <input class="input" type="text" readonly value={!jumpToDate ? '' : format(jumpToDate, 'yyyy/MM/dd')} placeholder={i18n`date (YYYY/MM/DD)`} onClick={() => { setPickDate(true); }} /> - </span> - </div> - <div class="control"> - <span class="has-tooltip-left" data-tooltip={dateTooltip}> - <a class="button" onClick={() => { setPickDate(true); }}> - <span class="icon"><i class="mdi mdi-calendar" /></span> - </a> - </span> </div> </div> </div> </div> - </div> - <DatePicker - opened={pickDate} - closeFunction={() => setPickDate(false)} - dateReceiver={onSelectDate} /> + <DatePicker + opened={pickDate} + closeFunction={() => setPickDate(false)} + dateReceiver={(d) => { + onSelectDate(AbsoluteTime.fromMilliseconds(d.getTime())) + }} + /> - <CardTable orders={orders} - onCreate={onCreate} - onCopyURL={onCopyURL} - onSelect={onSelectOrder} - onRefund={onRefundOrder} /> - </section>; + <CardTable + orders={orders} + onCreate={onCreate} + onCopyURL={onCopyURL} + onSelect={onSelectOrder} + onRefund={onRefundOrder} + onLoadMoreAfter={onLoadMoreAfter} + onLoadMoreBefore={onLoadMoreBefore} + /> + </Fragment> + ); } diff --git a/packages/merchant-backoffice-ui/src/paths/instance/orders/list/Table.tsx b/packages/merchant-backoffice-ui/src/paths/instance/orders/list/Table.tsx index 02d5b0bfc..5ece34409 100644 --- a/packages/merchant-backoffice-ui/src/paths/instance/orders/list/Table.tsx +++ b/packages/merchant-backoffice-ui/src/paths/instance/orders/list/Table.tsx @@ -1,6 +1,6 @@ /* This file is part of GNU Taler - (C) 2021 Taler Systems S.A. + (C) 2021-2024 Taler Systems S.A. GNU Taler is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -19,9 +19,12 @@ * @author Sebastian Javier Marchano (sebasjm) */ -import { Amounts } from "@gnu-taler/taler-util"; +import { Amounts, TalerMerchantApi } from "@gnu-taler/taler-util"; +import { + useTranslationContext +} from "@gnu-taler/web-util/browser"; import { format } from "date-fns"; -import { h, VNode } from "preact"; +import { VNode, h } from "preact"; import { StateUpdater, useState } from "preact/hooks"; import { FormErrors, @@ -32,12 +35,14 @@ import { InputCurrency } from "../../../../components/form/InputCurrency.js"; import { InputGroup } from "../../../../components/form/InputGroup.js"; import { InputSelector } from "../../../../components/form/InputSelector.js"; import { ConfirmModal } from "../../../../components/modal/index.js"; -import { useConfigContext } from "../../../../context/config.js"; -import { MerchantBackend, WithId } from "../../../../declaration.js"; -import { Translate, useTranslator } from "../../../../i18n/index.js"; +import { useSessionContext } from "../../../../context/session.js"; +import { + datetimeFormatForSettings, + usePreference, +} from "../../../../hooks/preference.js"; import { mergeRefunds } from "../../../../utils/amount.js"; -type Entity = MerchantBackend.Orders.OrderHistoryEntry & WithId; +type Entity = TalerMerchantApi.OrderHistoryEntry & WithId; interface Props { orders: Entity[]; onRefund: (value: Entity) => void; @@ -45,8 +50,6 @@ interface Props { onCreate: () => void; onSelect: (order: Entity) => void; onLoadMoreBefore?: () => void; - hasMoreBefore?: boolean; - hasMoreAfter?: boolean; onLoadMoreAfter?: () => void; } @@ -58,12 +61,10 @@ export function CardTable({ onSelect, onLoadMoreAfter, onLoadMoreBefore, - hasMoreAfter, - hasMoreBefore, }: Props): VNode { const [rowSelection, rowSelectionHandler] = useState<string[]>([]); - const i18n = useTranslator(); + const { i18n } = useTranslationContext(); return ( <div class="card has-table"> @@ -72,13 +73,13 @@ export function CardTable({ <span class="icon"> <i class="mdi mdi-cash-register" /> </span> - <Translate>Orders</Translate> + <i18n.Translate>Orders</i18n.Translate> </p> <div class="card-header-icon" aria-label="more options" /> <div class="card-header-icon" aria-label="more options"> - <span class="has-tooltip-left" data-tooltip={i18n`create order`}> + <span class="has-tooltip-left" data-tooltip={i18n.str`create order`}> <button class="button is-info" type="button" onClick={onCreate}> <span class="icon is-small"> <i class="mdi mdi-plus mdi-36px" /> @@ -100,8 +101,6 @@ export function CardTable({ rowSelectionHandler={rowSelectionHandler} onLoadMoreAfter={onLoadMoreAfter} onLoadMoreBefore={onLoadMoreBefore} - hasMoreAfter={hasMoreAfter} - hasMoreBefore={hasMoreBefore} /> ) : ( <EmptyTable /> @@ -120,8 +119,6 @@ interface TableProps { onSelect: (id: Entity) => void; rowSelectionHandler: StateUpdater<string[]>; onLoadMoreBefore?: () => void; - hasMoreBefore?: boolean; - hasMoreAfter?: boolean; onLoadMoreAfter?: () => void; } @@ -132,31 +129,27 @@ function Table({ onCopyURL, onLoadMoreAfter, onLoadMoreBefore, - hasMoreAfter, - hasMoreBefore, }: TableProps): VNode { + const { i18n } = useTranslationContext(); + const [settings] = usePreference(); return ( <div class="table-container"> {onLoadMoreBefore && ( - <button - class="button is-fullwidth" - disabled={!hasMoreBefore} - onClick={onLoadMoreBefore} - > - <Translate>load newer orders</Translate> + <button class="button is-fullwidth" onClick={onLoadMoreBefore}> + <i18n.Translate>load first page</i18n.Translate> </button> )} <table class="table is-striped is-hoverable is-fullwidth"> <thead> <tr> <th style={{ minWidth: 100 }}> - <Translate>Date</Translate> + <i18n.Translate>Date</i18n.Translate> </th> <th style={{ minWidth: 100 }}> - <Translate>Amount</Translate> + <i18n.Translate>Amount</i18n.Translate> </th> <th style={{ minWidth: 400 }}> - <Translate>Summary</Translate> + <i18n.Translate>Summary</i18n.Translate> </th> <th style={{ minWidth: 50 }} /> </tr> @@ -173,7 +166,7 @@ function Table({ ? "never" : format( new Date(i.timestamp.t_s * 1000), - "yyyy/MM/dd HH:mm:ss" + datetimeFormatForSettings(settings), )} </td> <td @@ -196,7 +189,7 @@ function Table({ type="button" onClick={(): void => onRefund(i)} > - <Translate>Refund</Translate> + <i18n.Translate>Refund</i18n.Translate> </button> )} {!i.paid && ( @@ -205,7 +198,7 @@ function Table({ type="button" onClick={(): void => onCopyURL(i)} > - <Translate>copy url</Translate> + <i18n.Translate>copy url</i18n.Translate> </button> )} </div> @@ -216,12 +209,10 @@ function Table({ </tbody> </table> {onLoadMoreAfter && ( - <button - class="button is-fullwidth" - disabled={!hasMoreAfter} - onClick={onLoadMoreAfter} - > - <Translate>load older orders</Translate> + <button class="button is-fullwidth" + data-tooltip={i18n.str`load more orders after the last one`} + onClick={onLoadMoreAfter}> + <i18n.Translate>load next page</i18n.Translate> </button> )} </div> @@ -229,15 +220,18 @@ function Table({ } function EmptyTable(): VNode { + const { i18n } = useTranslationContext(); return ( <div class="content has-text-grey has-text-centered"> <p> <span class="icon is-large"> - <i class="mdi mdi-emoticon-sad mdi-48px" /> + <i class="mdi mdi-magnify mdi-48px" /> </span> </p> <p> - <Translate>No orders have been found matching your query!</Translate> + <i18n.Translate> + No orders have been found matching your query! + </i18n.Translate> </p> </div> ); @@ -245,8 +239,8 @@ function EmptyTable(): VNode { interface RefundModalProps { onCancel: () => void; - onConfirm: (value: MerchantBackend.Orders.RefundRequest) => void; - order: MerchantBackend.Orders.MerchantOrderStatusResponse; + onConfirm: (value: TalerMerchantApi.RefundRequest) => void; + order: TalerMerchantApi.MerchantOrderStatusResponse; } export function RefundModal({ @@ -256,19 +250,20 @@ export function RefundModal({ }: RefundModalProps): VNode { type State = { mainReason?: string; description?: string; refund?: string }; const [form, setValue] = useState<State>({}); - const i18n = useTranslator(); + const [settings] = usePreference(); + const { i18n } = useTranslationContext(); // const [errors, setErrors] = useState<FormErrors<State>>({}); const refunds = ( order.order_status === "paid" ? order.refund_details : [] ).reduce(mergeRefunds, []); - const config = useConfigContext(); + const { config } = useSessionContext(); const totalRefunded = refunds .map((r) => r.amount) .reduce( (p, c) => Amounts.add(p, Amounts.parseOrThrow(c)).amount, - Amounts.zeroOfCurrency(config.currency) + Amounts.zeroOfCurrency(config.currency), ); const orderPrice = order.order_status === "paid" @@ -277,28 +272,28 @@ export function RefundModal({ const totalRefundable = !orderPrice ? Amounts.zeroOfCurrency(totalRefunded.currency) : refunds.length - ? Amounts.sub(orderPrice, totalRefunded).amount - : orderPrice; + ? Amounts.sub(orderPrice, totalRefunded).amount + : orderPrice; const isRefundable = Amounts.isNonZero(totalRefundable); - const duplicatedText = i18n`duplicated`; + const duplicatedText = i18n.str`duplicated`; const errors: FormErrors<State> = { - mainReason: !form.mainReason ? i18n`required` : undefined, + mainReason: !form.mainReason ? i18n.str`required` : undefined, description: !form.description && form.mainReason !== duplicatedText - ? i18n`required` + ? i18n.str`required` : undefined, refund: !form.refund - ? i18n`required` + ? i18n.str`required` : !Amounts.parse(form.refund) - ? i18n`invalid format` - : Amounts.cmp(totalRefundable, Amounts.parse(form.refund)!) === -1 - ? i18n`this value exceed the refundable amount` - : undefined, + ? i18n.str`invalid format` + : Amounts.cmp(totalRefundable, Amounts.parse(form.refund)!) === -1 + ? i18n.str`this value exceed the refundable amount` + : undefined, }; const hasErrors = Object.keys(errors).some( - (k) => (errors as any)[k] !== undefined + (k) => (errors as Record<string, unknown>)[k] !== undefined, ); const validateAndConfirm = () => { @@ -306,7 +301,7 @@ export function RefundModal({ if (!form.refund) return; onConfirm({ refund: Amounts.stringify( - Amounts.add(Amounts.parse(form.refund)!, totalRefunded).amount + Amounts.add(Amounts.parse(form.refund)!, totalRefunded).amount, ), reason: form.description === undefined @@ -339,13 +334,13 @@ export function RefundModal({ <thead> <tr> <th> - <Translate>date</Translate> + <i18n.Translate>date</i18n.Translate> </th> <th> - <Translate>amount</Translate> + <i18n.Translate>amount</i18n.Translate> </th> <th> - <Translate>reason</Translate> + <i18n.Translate>reason</i18n.Translate> </th> </tr> </thead> @@ -358,7 +353,7 @@ export function RefundModal({ ? "never" : format( new Date(r.timestamp.t_s * 1000), - "yyyy-MM-dd HH:mm:ss" + datetimeFormatForSettings(settings), )} </td> <td>{r.amount}</td> @@ -377,32 +372,32 @@ export function RefundModal({ <FormProvider<State> errors={errors} object={form} - valueHandler={(d) => setValue(d as any)} + valueHandler={(d) => setValue(d)} > <InputCurrency<State> name="refund" - label={i18n`Refund`} - tooltip={i18n`amount to be refunded`} + label={i18n.str`Refund`} + tooltip={i18n.str`amount to be refunded`} > - <Translate>Max refundable:</Translate>{" "} + <i18n.Translate>Max refundable:</i18n.Translate>{" "} {Amounts.stringify(totalRefundable)} </InputCurrency> <InputSelector name="mainReason" - label={i18n`Reason`} + label={i18n.str`Reason`} values={[ - i18n`Choose one...`, + i18n.str`Choose one...`, duplicatedText, - i18n`requested by the customer`, - i18n`other`, + i18n.str`requested by the customer`, + i18n.str`other`, ]} - tooltip={i18n`why this order is being refunded`} + tooltip={i18n.str`why this order is being refunded`} /> {form.mainReason && form.mainReason !== duplicatedText ? ( <Input<State> - label={i18n`Description`} + label={i18n.str`Description`} name="description" - tooltip={i18n`more information to give context`} + tooltip={i18n.str`more information to give context`} /> ) : undefined} </FormProvider> diff --git a/packages/merchant-backoffice-ui/src/paths/instance/orders/list/index.tsx b/packages/merchant-backoffice-ui/src/paths/instance/orders/list/index.tsx index 233afde04..8a1f85b1c 100644 --- a/packages/merchant-backoffice-ui/src/paths/instance/orders/list/index.tsx +++ b/packages/merchant-backoffice-ui/src/paths/instance/orders/list/index.tsx @@ -1,6 +1,6 @@ /* This file is part of GNU Taler - (C) 2021 Taler Systems S.A. + (C) 2021-2024 Taler Systems S.A. GNU Taler is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -15,157 +15,216 @@ */ /** -* -* @author Sebastian Javier Marchano (sebasjm) -*/ + * + * @author Sebastian Javier Marchano (sebasjm) + */ -import { h, VNode, Fragment } from 'preact'; -import { useState } from 'preact/hooks'; +import { + AbsoluteTime, + HttpStatusCode, + TalerError, + TalerMerchantApi, + assertUnreachable, +} from "@gnu-taler/taler-util"; +import { + useTranslationContext +} from "@gnu-taler/web-util/browser"; +import { VNode, h } from "preact"; +import { useState } from "preact/hooks"; +import { ErrorLoadingMerchant } from "../../../../components/ErrorLoadingMerchant.js"; import { Loading } from "../../../../components/exception/loading.js"; +import { JumpToElementById } from "../../../../components/form/JumpToElementById.js"; import { NotificationCard } from "../../../../components/menu/index.js"; -import { MerchantBackend, WithId } from "../../../../declaration.js"; -import { HttpError } from "../../../../hooks/backend.js"; -import { InstanceOrderFilter, useInstanceOrders, useOrderAPI, useOrderDetails } from "../../../../hooks/order.js"; -import { useTranslator } from '../../../../i18n/index.js'; +import { useSessionContext } from "../../../../context/session.js"; +import { + InstanceOrderFilter, + useInstanceOrders, + useOrderDetails, +} from "../../../../hooks/order.js"; import { Notification } from "../../../../utils/types.js"; -import { RefundModal } from "./Table.js"; +import { LoginPage } from "../../../login/index.js"; +import { NotFoundPageOrAdminCreate } from "../../../notfound/index.js"; import { ListPage } from "./ListPage.js"; +import { RefundModal } from "./Table.js"; interface Props { - onUnauthorized: () => VNode; - onLoadError: (error: HttpError) => VNode; - onNotFound: () => VNode; onSelect: (id: string) => void; onCreate: () => void; } -export default function ({ onUnauthorized, onLoadError, onCreate, onSelect, onNotFound }: Props): VNode { - const [filter, setFilter] = useState<InstanceOrderFilter>({}) - const [orderToBeRefunded, setOrderToBeRefunded] = useState<MerchantBackend.Orders.OrderHistoryEntry | undefined>(undefined) - - const setNewDate = (date?: Date) => setFilter(prev => ({ ...prev, date })) +export default function OrderList({ onCreate, onSelect }: Props): VNode { + const [filter, setFilter] = useState<InstanceOrderFilter>({ paid: false }); + const [orderToBeRefunded, setOrderToBeRefunded] = useState< + TalerMerchantApi.OrderHistoryEntry | undefined + >(undefined); - const result = useInstanceOrders(filter, setNewDate) - const { refundOrder, getPaymentURL } = useOrderAPI() + const setNewDate = (date?: AbsoluteTime): void => + setFilter((prev) => ({ ...prev, date })); - const [notif, setNotif] = useState<Notification | undefined>(undefined) + const result = useInstanceOrders(filter, (d) => + setFilter({ ...filter, position: d }), + ); + const { lib } = useSessionContext(); - if (result.clientError && result.isUnauthorized) return onUnauthorized() - if (result.clientError && result.isNotfound) return onNotFound() - if (result.loading) return <Loading /> - if (!result.ok) return onLoadError(result) + const [notif, setNotif] = useState<Notification | undefined>(undefined); - const isPaidActive = filter.paid === 'yes' ? "is-active" : '' - const isRefundedActive = filter.refunded === 'yes' ? "is-active" : '' - const isNotWiredActive = filter.wired === 'no' ? "is-active" : '' - const isAllActive = filter.paid === undefined && filter.refunded === undefined && filter.wired === undefined ? 'is-active' : '' + const { i18n } = useTranslationContext(); + const { state } = useSessionContext(); - const i18n = useTranslator() - const [errorOrderId, setErrorOrderId] = useState<string | undefined>(undefined) - - async function testIfOrderExistAndSelect(orderId: string) { - if (!orderId) { - setErrorOrderId(i18n`Enter an order id`) - return; - } - try { - await getPaymentURL(orderId) - onSelect(orderId) - setErrorOrderId(undefined) - } catch { - setErrorOrderId(i18n`order not found`) + if (!result) return <Loading />; + if (result instanceof TalerError) { + return <ErrorLoadingMerchant error={result} />; + } + if (result.type === "fail") { + switch(result.case) { + case HttpStatusCode.NotFound: { + return <NotFoundPageOrAdminCreate />; + } + case HttpStatusCode.Unauthorized: { + return <LoginPage /> + } + default: { + assertUnreachable(result) + } } } - return <Fragment> - <NotificationCard notification={notif} /> - - <ListPage - orders={result.data.orders.map(o => ({ ...o, id: o.order_id }))} - onLoadMoreBefore={result.loadMorePrev} hasMoreBefore={!result.isReachingStart} - onLoadMoreAfter={result.loadMore} hasMoreAfter={!result.isReachingEnd} - - onSelectOrder={(order) => onSelect(order.id)} - onRefundOrder={(value) => setOrderToBeRefunded(value)} - - errorOrderId={errorOrderId} - isAllActive={isAllActive} - isNotWiredActive={isNotWiredActive} - isPaidActive={isPaidActive} - isRefundedActive={isRefundedActive} - jumpToDate={filter.date} - onCopyURL={(id) => getPaymentURL(id).then((resp) => copyToClipboard(resp.data))} - - onCreate={onCreate} - onSearchOrderById={testIfOrderExistAndSelect} - onSelectDate={setNewDate} - onShowAll={() => setFilter({})} - onShowPaid={() => setFilter({ paid: 'yes' })} - onShowRefunded={() => setFilter({ refunded: 'yes' })} - onShowNotWired={() => setFilter({ wired: 'no' })} - - /> - - {orderToBeRefunded && <RefundModalForTable - id={orderToBeRefunded.order_id} - onCancel={() => setOrderToBeRefunded(undefined)} - onConfirm={(value) => refundOrder(orderToBeRefunded.order_id, value) - .then(() => setNotif({ - message: i18n`refund created successfully`, - type: "SUCCESS" - })) - .catch((error) => setNotif({ - message: i18n`could not create the refund`, - type: "ERROR", - description: error.message - })) - .then(() => setOrderToBeRefunded(undefined))} - onLoadError={(error) => { - setNotif({ - message: i18n`could not create the refund`, - type: "ERROR", - description: error.message - }); - setOrderToBeRefunded(undefined); - return <div />; - }} - onUnauthorized={onUnauthorized} - onNotFound={() => { - setNotif({ - message: i18n`could not get the order to refund`, - type: "ERROR", - // description: error.message - }); - setOrderToBeRefunded(undefined); - return <div />; - }} />} - </Fragment> + const isNotPaidActive = filter.paid === false ? "is-active" : ""; + const isPaidActive = + filter.paid === true && filter.wired === undefined ? "is-active" : ""; + const isRefundedActive = filter.refunded === true ? "is-active" : ""; + const isNotWiredActive = + filter.wired === false && filter.paid === true ? "is-active" : ""; + const isWiredActive = filter.wired === true ? "is-active" : ""; + const isAllActive = + filter.paid === undefined && + filter.refunded === undefined && + filter.wired === undefined + ? "is-active" + : ""; + + return ( + <section class="section is-main-section"> + <NotificationCard notification={notif} /> + + <JumpToElementById + testIfExist={async (order) => { + const resp = await lib.instance.getOrderDetails(state.token, order); + return resp.type === "ok"; + }} + onSelect={onSelect} + description={i18n.str`jump to order with the given product ID`} + placeholder={i18n.str`order id`} + /> + + <ListPage + orders={result.body.map((o) => ({ ...o, id: o.order_id }))} + onLoadMoreBefore={result.isFirstPage ? undefined : result.loadFirst} + onLoadMoreAfter={result.isLastPage ? undefined : result.loadNext} + onSelectOrder={(order) => onSelect(order.id)} + onRefundOrder={(value) => setOrderToBeRefunded(value)} + isAllActive={isAllActive} + isNotWiredActive={isNotWiredActive} + isWiredActive={isWiredActive} + isPaidActive={isPaidActive} + isNotPaidActive={isNotPaidActive} + isRefundedActive={isRefundedActive} + jumpToDate={filter.date} + onSelectDate={setNewDate} + onCopyURL={async (id) => { + const resp = await lib.instance.getOrderDetails(state.token, id); + if (resp.type === "ok") { + if (resp.body.order_status === "unpaid") { + copyToClipboard(resp.body.taler_pay_uri); + } else { + if (resp.body.contract_terms.fulfillment_url) { + copyToClipboard(resp.body.contract_terms.fulfillment_url); + } + } + copyToClipboard(resp.body.order_status); + } + }} + onCreate={onCreate} + onShowAll={() => setFilter({})} + onShowNotPaid={() => setFilter({ paid: false })} + onShowPaid={() => setFilter({ paid: true })} + onShowRefunded={() => setFilter({ refunded: true })} + onShowNotWired={() => setFilter({ wired: false, paid: true })} + onShowWired={() => setFilter({ wired: true })} + /> + + {orderToBeRefunded && ( + <RefundModalForTable + id={orderToBeRefunded.order_id} + onCancel={() => setOrderToBeRefunded(undefined)} + onConfirm={(value) => { + lib.instance + .addRefund(state.token, orderToBeRefunded.order_id, value) + .then(() => + setNotif({ + message: i18n.str`refund created successfully`, + type: "SUCCESS", + }), + ) + .catch((error) => + setNotif({ + message: i18n.str`could not create the refund`, + type: "ERROR", + description: error.message, + }), + ) + .then(() => setOrderToBeRefunded(undefined)); + }} + /> + )} + </section> + ); } interface RefundProps { id: string; - onUnauthorized: () => VNode; - onLoadError: (error: HttpError) => VNode; - onNotFound: () => VNode; onCancel: () => void; - onConfirm: (m: MerchantBackend.Orders.RefundRequest) => void; + onConfirm: (m: TalerMerchantApi.RefundRequest) => void; } -function RefundModalForTable({ id, onUnauthorized, onLoadError, onNotFound, onConfirm, onCancel }: RefundProps) { +function RefundModalForTable({ id, onConfirm, onCancel }: RefundProps): VNode { const result = useOrderDetails(id); - if (result.clientError && result.isUnauthorized) return onUnauthorized() - if (result.clientError && result.isNotfound) return onNotFound() - if (result.loading) return <Loading /> - if (!result.ok) return onLoadError(result) + if (!result) return <Loading />; + if (result instanceof TalerError) { + return <ErrorLoadingMerchant error={result} />; + } + if (result.type === "fail") { + switch (result.case) { + case HttpStatusCode.NotFound: { + return <NotFoundPageOrAdminCreate />; + } + case HttpStatusCode.BadGateway: { + return <div>Failed to obtain a response from the exchange</div>; + } + case HttpStatusCode.GatewayTimeout: { + return ( + <div>The merchant's interaction with the exchange took too long</div> + ); + } + case HttpStatusCode.Unauthorized: { + return <LoginPage /> + } + default: { + assertUnreachable(result); + } + } + } - return <RefundModal - order={result.data} - onCancel={onCancel} - onConfirm={onConfirm} - /> + return ( + <RefundModal + order={result.body} + onCancel={onCancel} + onConfirm={onConfirm} + /> + ); } -async function copyToClipboard(text: string) { - return navigator.clipboard.writeText(text) +async function copyToClipboard(text: string): Promise<void> { + return navigator.clipboard.writeText(text); } diff --git a/packages/merchant-backoffice-ui/src/paths/instance/otp_devices/create/Create.stories.tsx b/packages/merchant-backoffice-ui/src/paths/instance/otp_devices/create/Create.stories.tsx new file mode 100644 index 000000000..36b31ebe8 --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/otp_devices/create/Create.stories.tsx @@ -0,0 +1,28 @@ +/* + This file is part of GNU Taler + (C) 2021-2024 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +/** + * + * @author Sebastian Javier Marchano (sebasjm) + */ + +import { h, VNode, FunctionalComponent } from "preact"; +import { CreatePage as TestedComponent } from "./CreatePage.js"; + +export default { + title: "Pages/OtpDevices/Create", + component: TestedComponent, +}; diff --git a/packages/merchant-backoffice-ui/src/paths/instance/otp_devices/create/CreatePage.tsx b/packages/merchant-backoffice-ui/src/paths/instance/otp_devices/create/CreatePage.tsx new file mode 100644 index 000000000..d5522c2d4 --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/otp_devices/create/CreatePage.tsx @@ -0,0 +1,181 @@ +/* + This file is part of GNU Taler + (C) 2021-2024 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +/** + * + * @author Sebastian Javier Marchano (sebasjm) + */ + +import { + TalerMerchantApi, + isRfc3548Base32Charset, + randomRfc3548Base32Key, +} from "@gnu-taler/taler-util"; +import { useTranslationContext } from "@gnu-taler/web-util/browser"; +import { Fragment, VNode, h } from "preact"; +import { useState } from "preact/hooks"; +import { AsyncButton } from "../../../../components/exception/AsyncButton.js"; +import { + FormErrors, + FormProvider, +} from "../../../../components/form/FormProvider.js"; +import { Input } from "../../../../components/form/Input.js"; +import { InputSelector } from "../../../../components/form/InputSelector.js"; +import { InputWithAddon } from "../../../../components/form/InputWithAddon.js"; + +type Entity = TalerMerchantApi.OtpDeviceAddDetails; + +interface Props { + onCreate: (d: Entity) => Promise<void>; + onBack?: () => void; +} + +const algorithms = [0, 1, 2]; +const algorithmsNames = ["off", "30s 8d TOTP-SHA1", "30s 8d eTOTP-SHA1"]; + +export function CreatePage({ onCreate, onBack }: Props): VNode { + const { i18n } = useTranslationContext(); + + const [state, setState] = useState<Partial<Entity>>({}); + + const [showKey, setShowKey] = useState(false); + + const errors: FormErrors<Entity> = { + otp_device_id: !state.otp_device_id + ? i18n.str`required` + : !/[a-zA-Z0-9]*/.test(state.otp_device_id) + ? i18n.str`no valid. only characters and numbers` + : undefined, + otp_algorithm: !state.otp_algorithm ? i18n.str`required` : undefined, + otp_key: !state.otp_key + ? i18n.str`required` + : !isRfc3548Base32Charset(state.otp_key) + ? i18n.str`just letters and numbers from 2 to 7` + : state.otp_key.length !== 32 + ? i18n.str`size of the key should be 32` + : undefined, + otp_device_description: !state.otp_device_description + ? i18n.str`required` + : !/[a-zA-Z0-9]*/.test(state.otp_device_description) + ? i18n.str`no valid. only characters and numbers` + : undefined, + }; + + const hasErrors = Object.keys(errors).some( + (k) => (errors as any)[k] !== undefined, + ); + + const submitForm = () => { + if (hasErrors) return Promise.reject(); + return onCreate(state as any); + }; + + return ( + <div> + <section class="section is-main-section"> + <div class="columns"> + <div class="column" /> + <div class="column is-four-fifths"> + <FormProvider + object={state} + valueHandler={setState} + errors={errors} + > + <Input<Entity> + name="otp_device_id" + label={i18n.str`ID`} + tooltip={i18n.str`Internal id on the system`} + /> + <Input<Entity> + name="otp_device_description" + label={i18n.str`Descripiton`} + tooltip={i18n.str`Useful to identify the device physically`} + /> + <InputSelector<Entity> + name="otp_algorithm" + label={i18n.str`Verification algorithm`} + tooltip={i18n.str`Algorithm to use to verify transaction in offline mode`} + values={algorithms} + toStr={(v) => algorithmsNames[v]} + fromStr={(v) => Number(v)} + /> + {state.otp_algorithm ? ( + <Fragment> + <InputWithAddon<Entity> + expand + name="otp_key" + label={i18n.str`Device key`} + inputType={showKey ? "text" : "password"} + help="Be sure to be very hard to guess or use the random generator" + tooltip={i18n.str`Your device need to have exactly the same value`} + fromStr={(v) => v.toUpperCase()} + addonAfterAction={() => { + setShowKey(!showKey); + }} + addonAfter={ + <span class="icon"> + {showKey ? ( + <i class="mdi mdi-eye" /> + ) : ( + <i class="mdi mdi-eye-off" /> + )} + </span> + } + side={ + <button + data-tooltip={i18n.str`generate random secret key`} + class="button is-info mr-3" + onClick={(e) => { + setState((s) => ({ + ...s, + otp_key: randomRfc3548Base32Key(), + })); + e.preventDefault(); + }} + > + <i18n.Translate>random</i18n.Translate> + </button> + } + /> + </Fragment> + ) : undefined} + </FormProvider> + + <div class="buttons is-right mt-5"> + {onBack && ( + <button class="button" onClick={onBack}> + <i18n.Translate>Cancel</i18n.Translate> + </button> + )} + <AsyncButton + disabled={hasErrors} + data-tooltip={ + hasErrors + ? i18n.str`Need to complete marked fields` + : "confirm operation" + } + onClick={submitForm} + > + <i18n.Translate>Confirm</i18n.Translate> + </AsyncButton> + </div> + </div> + <div class="column" /> + </div> + </section> + </div> + ); +} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/otp_devices/create/CreatedSuccessfully.tsx b/packages/merchant-backoffice-ui/src/paths/instance/otp_devices/create/CreatedSuccessfully.tsx new file mode 100644 index 000000000..7723bec81 --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/otp_devices/create/CreatedSuccessfully.tsx @@ -0,0 +1,98 @@ +/* + This file is part of GNU Taler + (C) 2021-2024 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +import { TalerMerchantApi } from "@gnu-taler/taler-util"; +import { useTranslationContext } from "@gnu-taler/web-util/browser"; +import { VNode, h } from "preact"; +import { QR } from "../../../../components/exception/QR.js"; +import { CreatedSuccessfully as Template } from "../../../../components/notifications/CreatedSuccessfully.js"; +import { useSessionContext } from "../../../../context/session.js"; + +type Entity = TalerMerchantApi.OtpDeviceAddDetails; + +interface Props { + entity: Entity; + onConfirm: () => void; +} + +export function CreatedSuccessfully({ + entity, + onConfirm, +}: Props): VNode { + const { i18n } = useTranslationContext(); + const { state } = useSessionContext(); + const issuer = state.backendUrl.href; + const qrText = `otpauth://totp/${state.instance}/${entity.otp_device_id}?issuer=${issuer}&algorithm=SHA1&digits=8&period=30&secret=${entity.otp_key}`; + const qrTextSafe = `otpauth://totp/${state.instance}/${entity.otp_device_id}?issuer=${issuer}&algorithm=SHA1&digits=8&period=30&secret=${entity.otp_key.substring(0, 6)}...`; + + return ( + <Template onConfirm={onConfirm} > + <p class="is-size-5"> + <i18n.Translate> + You can scan the next QR code with your device or save the key before continuing. + </i18n.Translate> + </p> + <div class="field is-horizontal"> + <div class="field-label is-normal"> + <label class="label">ID</label> + </div> + <div class="field-body is-flex-grow-3"> + <div class="field"> + <p class="control"> + <input + readonly + class="input" + value={entity.otp_device_id} + /> + </p> + </div> + </div> + </div> + <div class="field is-horizontal"> + <div class="field-label is-normal"> + <label class="label"><i18n.Translate>Description</i18n.Translate></label> + </div> + <div class="field-body is-flex-grow-3"> + <div class="field"> + <p class="control"> + <input + class="input" + readonly + value={entity.otp_device_description} + /> + </p> + </div> + </div> + </div> + <QR + text={qrText} + /> + <div + style={{ + color: "grey", + fontSize: "small", + width: 200, + textAlign: "center", + margin: "auto", + wordBreak: "break-all", + }} + > + {qrTextSafe} + </div> + </Template> + ); +} + diff --git a/packages/merchant-backoffice-ui/src/paths/instance/reserves/create/index.tsx b/packages/merchant-backoffice-ui/src/paths/instance/otp_devices/create/index.tsx index c00261d8c..8ab0e1f26 100644 --- a/packages/merchant-backoffice-ui/src/paths/instance/reserves/create/index.tsx +++ b/packages/merchant-backoffice-ui/src/paths/instance/otp_devices/create/index.tsx @@ -1,6 +1,6 @@ /* This file is part of GNU Taler - (C) 2021 Taler Systems S.A. + (C) 2021-2024 Taler Systems S.A. GNU Taler is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -19,53 +19,52 @@ * @author Sebastian Javier Marchano (sebasjm) */ -import { Fragment, h, VNode } from "preact"; +import { TalerMerchantApi } from "@gnu-taler/taler-util"; +import { useTranslationContext } from "@gnu-taler/web-util/browser"; +import { Fragment, VNode, h } from "preact"; import { useState } from "preact/hooks"; import { NotificationCard } from "../../../../components/menu/index.js"; -import { MerchantBackend } from "../../../../declaration.js"; -import { useReservesAPI } from "../../../../hooks/reserves.js"; -import { useTranslator } from "../../../../i18n/index.js"; +import { useSessionContext } from "../../../../context/session.js"; import { Notification } from "../../../../utils/types.js"; -import { CreatedSuccessfully } from "./CreatedSuccessfully.js"; import { CreatePage } from "./CreatePage.js"; +import { CreatedSuccessfully } from "./CreatedSuccessfully.js"; + +export type Entity = TalerMerchantApi.OtpDeviceAddDetails; interface Props { - onBack: () => void; + onBack?: () => void; onConfirm: () => void; } -export default function CreateReserve({ onBack, onConfirm }: Props): VNode { - const { createReserve } = useReservesAPI(); - const [notif, setNotif] = useState<Notification | undefined>(undefined); - const i18n = useTranslator(); - const [createdOk, setCreatedOk] = useState< - | { - request: MerchantBackend.Tips.ReserveCreateRequest; - response: MerchantBackend.Tips.ReserveCreateConfirmation; - } - | undefined - >(undefined); +export default function CreateValidator({ onConfirm, onBack }: Props): VNode { + const { lib: api } = useSessionContext(); + const { state } = useSessionContext(); + const [notif, setNotif] = useState<Notification | undefined>(undefined); + const { i18n } = useTranslationContext(); + const [created, setCreated] = useState<TalerMerchantApi.OtpDeviceAddDetails | null>(null) - if (createdOk) { - return <CreatedSuccessfully entity={createdOk} onConfirm={onConfirm} />; + if (created) { + return <CreatedSuccessfully entity={created} onConfirm={onConfirm} /> } return ( - <Fragment> + <> <NotificationCard notification={notif} /> <CreatePage onBack={onBack} - onCreate={(request: MerchantBackend.Tips.ReserveCreateRequest) => { - return createReserve(request) - .then((r) => setCreatedOk({ request, response: r.data })) + onCreate={(request: Entity) => { + return api.instance.addOtpDevice(state.token, request) + .then((d) => { + setCreated(request) + }) .catch((error) => { setNotif({ - message: i18n`could not create reserve`, + message: i18n.str`could not create device`, type: "ERROR", description: error.message, }); }); }} /> - </Fragment> + </> ); } diff --git a/packages/merchant-backoffice-ui/src/paths/instance/otp_devices/list/List.stories.tsx b/packages/merchant-backoffice-ui/src/paths/instance/otp_devices/list/List.stories.tsx new file mode 100644 index 000000000..49032c80e --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/otp_devices/list/List.stories.tsx @@ -0,0 +1,28 @@ +/* + This file is part of GNU Taler + (C) 2021-2024 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +/** + * + * @author Sebastian Javier Marchano (sebasjm) + */ + +import { FunctionalComponent, h } from "preact"; +import { ListPage as TestedComponent } from "./ListPage.js"; + +export default { + title: "Pages/OtpDevices/List", + component: TestedComponent, +}; diff --git a/packages/merchant-backoffice-ui/src/paths/instance/otp_devices/list/ListPage.tsx b/packages/merchant-backoffice-ui/src/paths/instance/otp_devices/list/ListPage.tsx new file mode 100644 index 000000000..8ca0a9c58 --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/otp_devices/list/ListPage.tsx @@ -0,0 +1,59 @@ +/* + This file is part of GNU Taler + (C) 2021-2024 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +/** + * + * @author Sebastian Javier Marchano (sebasjm) + */ + +import { TalerMerchantApi } from "@gnu-taler/taler-util"; +import { h, VNode } from "preact"; +import { CardTable } from "./Table.js"; + +export interface Props { + devices: TalerMerchantApi.OtpDeviceEntry[]; + onLoadMoreBefore?: () => void; + onLoadMoreAfter?: () => void; + onCreate: () => void; + onDelete: (e: TalerMerchantApi.OtpDeviceEntry) => void; + onSelect: (e: TalerMerchantApi.OtpDeviceEntry) => void; +} + +export function ListPage({ + devices, + onCreate, + onDelete, + onSelect, + onLoadMoreBefore, + onLoadMoreAfter, +}: Props): VNode { + + return ( + <section class="section is-main-section"> + <CardTable + devices={devices.map((o) => ({ + ...o, + id: String(o.otp_device_id), + }))} + onCreate={onCreate} + onDelete={onDelete} + onSelect={onSelect} + onLoadMoreBefore={onLoadMoreBefore} + onLoadMoreAfter={onLoadMoreAfter} + /> + </section> + ); +} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/otp_devices/list/Table.tsx b/packages/merchant-backoffice-ui/src/paths/instance/otp_devices/list/Table.tsx new file mode 100644 index 000000000..afe3c98e2 --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/otp_devices/list/Table.tsx @@ -0,0 +1,196 @@ +/* + This file is part of GNU Taler + (C) 2021-2024 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +/** + * + * @author Sebastian Javier Marchano (sebasjm) + */ + +import { TalerMerchantApi } from "@gnu-taler/taler-util"; +import { useTranslationContext } from "@gnu-taler/web-util/browser"; +import { h, VNode } from "preact"; +import { StateUpdater, useState } from "preact/hooks"; + +type Entity = TalerMerchantApi.OtpDeviceEntry; + +interface Props { + devices: Entity[]; + onDelete: (e: Entity) => void; + onSelect: (e: Entity) => void; + onCreate: () => void; + onLoadMoreBefore?: () => void; + onLoadMoreAfter?: () => void; +} + +export function CardTable({ + devices, + onCreate, + onDelete, + onSelect, + onLoadMoreAfter, + onLoadMoreBefore, +}: Props): VNode { + const [rowSelection, rowSelectionHandler] = useState<string[]>([]); + + const { i18n } = useTranslationContext(); + + return ( + <div class="card has-table"> + <header class="card-header"> + <p class="card-header-title"> + <span class="icon"> + <i class="mdi mdi-newspaper" /> + </span> + <i18n.Translate>OTP Devices</i18n.Translate> + </p> + <div class="card-header-icon" aria-label="more options"> + <span + class="has-tooltip-left" + data-tooltip={i18n.str`add new devices`} + > + <button class="button is-info" type="button" onClick={onCreate}> + <span class="icon is-small"> + <i class="mdi mdi-plus mdi-36px" /> + </span> + </button> + </span> + </div> + </header> + <div class="card-content"> + <div class="b-table has-pagination"> + <div class="table-wrapper has-mobile-cards"> + {devices.length > 0 ? ( + <Table + instances={devices} + onDelete={onDelete} + onSelect={onSelect} + rowSelection={rowSelection} + rowSelectionHandler={rowSelectionHandler} + onLoadMoreAfter={onLoadMoreAfter} + onLoadMoreBefore={onLoadMoreBefore} + /> + ) : ( + <EmptyTable /> + )} + </div> + </div> + </div> + </div> + ); +} +interface TableProps { + rowSelection: string[]; + instances: Entity[]; + onDelete: (e: Entity) => void; + onSelect: (e: Entity) => void; + rowSelectionHandler: StateUpdater<string[]>; + onLoadMoreBefore?: () => void; + onLoadMoreAfter?: () => void; +} + +function Table({ + instances, + onLoadMoreAfter, + onDelete, + onSelect, + onLoadMoreBefore, +}: TableProps): VNode { + const { i18n } = useTranslationContext(); + return ( + <div class="table-container"> + {onLoadMoreBefore && ( + <button + class="button is-fullwidth" + data-tooltip={i18n.str`load more devices before the first one`} + onClick={onLoadMoreBefore} + > + <i18n.Translate>load first page</i18n.Translate> + </button> + )} + <table class="table is-fullwidth is-striped is-hoverable is-fullwidth"> + <thead> + <tr> + <th> + <i18n.Translate>ID</i18n.Translate> + </th> + <th> + <i18n.Translate>Description</i18n.Translate> + </th> + <th /> + </tr> + </thead> + <tbody> + {instances.map((i) => { + return ( + <tr key={i.otp_device_id}> + <td + onClick={(): void => onSelect(i)} + style={{ cursor: "pointer" }} + > + {i.otp_device_id} + </td> + <td + onClick={(): void => onSelect(i)} + style={{ cursor: "pointer" }} + > + {i.device_description} + </td> + <td class="is-actions-cell right-sticky"> + <div class="buttons is-right"> + <button + class="button is-danger is-small has-tooltip-left" + data-tooltip={i18n.str`delete selected devices from the database`} + onClick={() => onDelete(i)} + > + Delete + </button> + </div> + </td> + </tr> + ); + })} + </tbody> + </table> + {onLoadMoreAfter && ( + <button + class="button is-fullwidth" + data-tooltip={i18n.str`load more devices after the last one`} + onClick={onLoadMoreAfter} + > + <i18n.Translate>load next page</i18n.Translate> + </button> + )} + </div> + ); +} + +function EmptyTable(): VNode { + const { i18n } = useTranslationContext(); + return ( + <div class="content has-text-grey has-text-centered"> + <p> + <span class="icon is-large"> + <i class="mdi mdi-magnify mdi-48px" /> + </span> + </p> + <p> + <i18n.Translate> + There is no devices yet, add more pressing the + sign + </i18n.Translate> + </p> + </div> + ); +} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/otp_devices/list/index.tsx b/packages/merchant-backoffice-ui/src/paths/instance/otp_devices/list/index.tsx new file mode 100644 index 000000000..b6a077863 --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/otp_devices/list/index.tsx @@ -0,0 +1,106 @@ +/* + This file is part of GNU Taler + (C) 2021-2024 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +/** + * + * @author Sebastian Javier Marchano (sebasjm) + */ + +import { + HttpStatusCode, + TalerError, + TalerMerchantApi, + assertUnreachable +} from "@gnu-taler/taler-util"; +import { + useTranslationContext +} from "@gnu-taler/web-util/browser"; +import { Fragment, VNode, h } from "preact"; +import { useState } from "preact/hooks"; +import { ErrorLoadingMerchant } from "../../../../components/ErrorLoadingMerchant.js"; +import { Loading } from "../../../../components/exception/loading.js"; +import { NotificationCard } from "../../../../components/menu/index.js"; +import { useSessionContext } from "../../../../context/session.js"; +import { useInstanceOtpDevices } from "../../../../hooks/otp.js"; +import { Notification } from "../../../../utils/types.js"; +import { LoginPage } from "../../../login/index.js"; +import { NotFoundPageOrAdminCreate } from "../../../notfound/index.js"; +import { ListPage } from "./ListPage.js"; + +interface Props { + onCreate: () => void; + onSelect: (id: string) => void; +} + +export default function ListOtpDevices({ onCreate, onSelect }: Props): VNode { + // const [position, setPosition] = useState<string | undefined>(undefined); + const { i18n } = useTranslationContext(); + const [notif, setNotif] = useState<Notification | undefined>(undefined); + const { lib } = useSessionContext(); + const { state } = useSessionContext(); + const result = useInstanceOtpDevices(); + + if (!result) return <Loading />; + if (result instanceof TalerError) { + return <ErrorLoadingMerchant error={result} />; + } + if (result.type === "fail") { + switch (result.case) { + case HttpStatusCode.NotFound: { + return <NotFoundPageOrAdminCreate />; + } + case HttpStatusCode.Unauthorized: { + return <LoginPage /> + } + default: { + assertUnreachable(result); + } + } + } + + return ( + <Fragment> + <NotificationCard notification={notif} /> + + <ListPage + devices={result.body.otp_devices} + onLoadMoreBefore={undefined} //result.isFirstPage ? undefined : result.loadFirst} + onLoadMoreAfter={undefined} //result.isLastPage ? undefined : result.loadNext} + onCreate={onCreate} + onSelect={(e) => { + onSelect(e.otp_device_id); + }} + onDelete={(e: TalerMerchantApi.OtpDeviceEntry) => { + return lib.instance + .deleteOtpDevice(state.token, e.otp_device_id) + .then(() => + setNotif({ + message: i18n.str`validator delete successfully`, + type: "SUCCESS", + }), + ) + .catch((error) => + setNotif({ + message: i18n.str`could not delete the validator`, + type: "ERROR", + description: error.message, + }), + ); + }} + /> + </Fragment> + ); +} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/otp_devices/update/Update.stories.tsx b/packages/merchant-backoffice-ui/src/paths/instance/otp_devices/update/Update.stories.tsx new file mode 100644 index 000000000..06ea9d07a --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/otp_devices/update/Update.stories.tsx @@ -0,0 +1,32 @@ +/* + This file is part of GNU Taler + (C) 2021-2024 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +/** + * + * @author Sebastian Javier Marchano (sebasjm) + */ + +import { h, VNode, FunctionalComponent } from "preact"; +import { UpdatePage as TestedComponent } from "./UpdatePage.js"; + +export default { + title: "Pages/OtpDevices/Update", + component: TestedComponent, + argTypes: { + onUpdate: { action: "onUpdate" }, + onBack: { action: "onBack" }, + }, +}; diff --git a/packages/merchant-backoffice-ui/src/paths/instance/otp_devices/update/UpdatePage.tsx b/packages/merchant-backoffice-ui/src/paths/instance/otp_devices/update/UpdatePage.tsx new file mode 100644 index 000000000..35d67cbc6 --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/otp_devices/update/UpdatePage.tsx @@ -0,0 +1,185 @@ +/* + This file is part of GNU Taler + (C) 2021-2024 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +/** + * + * @author Sebastian Javier Marchano (sebasjm) + */ + +import { randomRfc3548Base32Key, TalerMerchantApi } from "@gnu-taler/taler-util"; +import { useTranslationContext } from "@gnu-taler/web-util/browser"; +import { Fragment, h, VNode } from "preact"; +import { useState } from "preact/hooks"; +import { AsyncButton } from "../../../../components/exception/AsyncButton.js"; +import { + FormErrors, + FormProvider, +} from "../../../../components/form/FormProvider.js"; +import { Input } from "../../../../components/form/Input.js"; +import { InputSelector } from "../../../../components/form/InputSelector.js"; +import { InputWithAddon } from "../../../../components/form/InputWithAddon.js"; + +type Entity = TalerMerchantApi.OtpDevicePatchDetails & WithId; + +interface Props { + onUpdate: (d: Entity) => Promise<void>; + onBack?: () => void; + device: Entity; +} +const algorithms = [0, 1, 2]; +const algorithmsNames = ["off", "30s 8d TOTP-SHA1", "30s 8d eTOTP-SHA1"]; +export function UpdatePage({ device, onUpdate, onBack }: Props): VNode { + const { i18n } = useTranslationContext(); + + const [state, setState] = useState<Partial<Entity>>(device); + const [showKey, setShowKey] = useState(false); + + const errors: FormErrors<Entity> = {}; + + const hasErrors = Object.keys(errors).some( + (k) => (errors as any)[k] !== undefined, + ); + + const submitForm = () => { + if (hasErrors) return Promise.reject(); + return onUpdate(state as any); + }; + + return ( + <div> + <section class="section"> + <section class="hero is-hero-bar"> + <div class="hero-body"> + <div class="level"> + <div class="level-left"> + <div class="level-item"> + <span class="is-size-4"> + Device: <b>{device.id}</b> + </span> + </div> + </div> + </div> + </div> + </section> + <hr /> + + <section class="section is-main-section"> + <div class="columns"> + <div class="column is-four-fifths"> + <FormProvider + object={state} + valueHandler={setState} + errors={errors} + > + <Input<Entity> + name="otp_device_description" + label={i18n.str`Description`} + tooltip={i18n.str`Useful to identify the device physically`} + /> + <InputSelector<Entity> + name="otp_algorithm" + label={i18n.str`Verification algorithm`} + tooltip={i18n.str`Algorithm to use to verify transaction in offline mode`} + values={algorithms} + toStr={(v) => algorithmsNames[v]} + fromStr={(v) => Number(v)} + /> + {state.otp_algorithm && state.otp_algorithm > 0 ? ( + <Fragment> + <InputWithAddon<Entity> + name="otp_key" + label={i18n.str`Device key`} + readonly={state.otp_key === undefined} + inputType={showKey ? "text" : "password"} + help={ + state.otp_key === undefined + ? "Not modified" + : "Be sure to be very hard to guess or use the random generator" + } + tooltip={i18n.str`Your device need to have exactly the same value`} + fromStr={(v) => v.toUpperCase()} + addonAfterAction={() => { + setShowKey(!showKey); + }} + addonAfter={ + <span + class="icon" + onClick={() => { + setShowKey(!showKey); + }} + > + {showKey ? ( + <i class="mdi mdi-eye" /> + ) : ( + <i class="mdi mdi-eye-off" /> + )} + </span> + } + side={ + state.otp_key === undefined ? ( + <button + onClick={(e) => { + setState((s) => ({ ...s, otp_key: "" })); + }} + class="button" + > + change key + </button> + ) : ( + <button + data-tooltip={i18n.str`generate random secret key`} + class="button is-info mr-3" + onClick={(e) => { + setState((s) => ({ + ...s, + otp_key: randomRfc3548Base32Key(), + })); + }} + > + <i18n.Translate>random</i18n.Translate> + </button> + ) + } + /> + </Fragment> + ) : undefined}{" "} + </FormProvider> + + <div class="buttons is-right mt-5"> + {onBack && ( + <button class="button" onClick={onBack}> + <i18n.Translate>Cancel</i18n.Translate> + </button> + )} + <AsyncButton + disabled={hasErrors} + data-tooltip={ + hasErrors + ? i18n.str`Need to complete marked fields` + : "confirm operation" + } + onClick={submitForm} + > + <i18n.Translate>Confirm</i18n.Translate> + </AsyncButton> + </div> + </div> + </div> + </section> + </section> + </div> + ); +} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/otp_devices/update/index.tsx b/packages/merchant-backoffice-ui/src/paths/instance/otp_devices/update/index.tsx new file mode 100644 index 000000000..99edb95c3 --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/otp_devices/update/index.tsx @@ -0,0 +1,147 @@ +/* + This file is part of GNU Taler + (C) 2021-2024 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +/** + * + * @author Sebastian Javier Marchano (sebasjm) + */ + +import { + HttpStatusCode, + TalerError, + TalerMerchantApi, + assertUnreachable +} from "@gnu-taler/taler-util"; +import { + useTranslationContext +} from "@gnu-taler/web-util/browser"; +import { Fragment, VNode, h } from "preact"; +import { useState } from "preact/hooks"; +import { ErrorLoadingMerchant } from "../../../../components/ErrorLoadingMerchant.js"; +import { Loading } from "../../../../components/exception/loading.js"; +import { NotificationCard } from "../../../../components/menu/index.js"; +import { useSessionContext } from "../../../../context/session.js"; +import { useOtpDeviceDetails } from "../../../../hooks/otp.js"; +import { Notification } from "../../../../utils/types.js"; +import { LoginPage } from "../../../login/index.js"; +import { NotFoundPageOrAdminCreate } from "../../../notfound/index.js"; +import { CreatedSuccessfully } from "../create/CreatedSuccessfully.js"; +import { UpdatePage } from "./UpdatePage.js"; + +export type Entity = TalerMerchantApi.OtpDevicePatchDetails & WithId; + +interface Props { + onBack?: () => void; + onConfirm: () => void; + vid: string; +} +export default function UpdateValidator({ + vid, + onConfirm, + onBack, +}: Props): VNode { + const result = useOtpDeviceDetails(vid); + const [notif, setNotif] = useState<Notification | undefined>(undefined); + const [keyUpdated, setKeyUpdated] = + useState<TalerMerchantApi.OtpDeviceAddDetails | null>(null); + const { lib } = useSessionContext(); + const { state } = useSessionContext(); + + const { i18n } = useTranslationContext(); + + if (!result) return <Loading />; + if (result instanceof TalerError) { + return <ErrorLoadingMerchant error={result} />; + } + if (result.type === "fail") { + switch (result.case) { + case HttpStatusCode.NotFound: { + return <NotFoundPageOrAdminCreate />; + } + case HttpStatusCode.Unauthorized: { + return <LoginPage /> + } + default: { + assertUnreachable(result); + } + } + } + + if (keyUpdated) { + return <CreatedSuccessfully entity={keyUpdated} onConfirm={onConfirm} />; + } + + return ( + <Fragment> + <NotificationCard notification={notif} /> + <UpdatePage + device={{ + id: vid, + otp_algorithm: result.body.otp_algorithm, + otp_device_description: result.body.device_description, + otp_key: "", + otp_ctr: result.body.otp_ctr, + }} + onBack={onBack} + onUpdate={async (newInfo) => { + return lib.instance + .updateOtpDevice(state.token, vid, newInfo) + .then((d) => { + if (d.type === "ok") { + if (newInfo.otp_key) { + setKeyUpdated({ + otp_algorithm: newInfo.otp_algorithm, + otp_device_description: newInfo.otp_device_description, + otp_device_id: newInfo.id, + otp_key: newInfo.otp_key, + otp_ctr: newInfo.otp_ctr, + }); + } else { + onConfirm(); + } + } else { + switch(d.case) { + case HttpStatusCode.NotFound: { + setNotif({ + message: i18n.str`Could not update template`, + type: "ERROR", + description: i18n.str`Template id is unknown`, + }); + break; + } + case HttpStatusCode.Conflict: { + setNotif({ + message: i18n.str`Could not update template`, + type: "ERROR", + description: i18n.str`The provided information is inconsistent with the current state of the template`, + }); + break; + } + } + } + }) + .catch((error) => { + setNotif({ + message: i18n.str`could not update template`, + type: "ERROR", + description: error.message, + }); + }); + }} + /> + </Fragment> + ); +} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/products/create/Create.stories.tsx b/packages/merchant-backoffice-ui/src/paths/instance/products/create/Create.stories.tsx index b42b9f929..22bbfe28a 100644 --- a/packages/merchant-backoffice-ui/src/paths/instance/products/create/Create.stories.tsx +++ b/packages/merchant-backoffice-ui/src/paths/instance/products/create/Create.stories.tsx @@ -1,6 +1,6 @@ /* This file is part of GNU Taler - (C) 2021 Taler Systems S.A. + (C) 2021-2024 Taler Systems S.A. GNU Taler is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -15,28 +15,29 @@ */ /** -* -* @author Sebastian Javier Marchano (sebasjm) -*/ + * + * @author Sebastian Javier Marchano (sebasjm) + */ -import { h, VNode, FunctionalComponent } from 'preact'; +import { h, VNode, FunctionalComponent } from "preact"; import { CreatePage as TestedComponent } from "./CreatePage.js"; - export default { - title: 'Pages/Product/Create', + title: "Pages/Product/Create", component: TestedComponent, argTypes: { - onCreate: { action: 'onCreate' }, - onBack: { action: 'onBack' }, + onCreate: { action: "onCreate" }, + onBack: { action: "onBack" }, }, }; -function createExample<Props>(Component: FunctionalComponent<Props>, props: Partial<Props>) { - const r = (args: any) => <Component {...args} /> - r.args = props - return r +function createExample<Props>( + Component: FunctionalComponent<Props>, + props: Partial<Props>, +) { + const r = (args: any) => <Component {...args} />; + r.args = props; + return r; } -export const Example = createExample(TestedComponent, { -}); +export const Example = createExample(TestedComponent, {}); diff --git a/packages/merchant-backoffice-ui/src/paths/instance/products/create/CreatePage.tsx b/packages/merchant-backoffice-ui/src/paths/instance/products/create/CreatePage.tsx index 434a55aab..64b174f64 100644 --- a/packages/merchant-backoffice-ui/src/paths/instance/products/create/CreatePage.tsx +++ b/packages/merchant-backoffice-ui/src/paths/instance/products/create/CreatePage.tsx @@ -1,6 +1,6 @@ /* This file is part of GNU Taler - (C) 2021 Taler Systems S.A. + (C) 2021-2024 Taler Systems S.A. GNU Taler is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -15,51 +15,66 @@ */ /** -* -* @author Sebastian Javier Marchano (sebasjm) -*/ + * + * @author Sebastian Javier Marchano (sebasjm) + */ +import { TalerMerchantApi } from "@gnu-taler/taler-util"; +import { useTranslationContext } from "@gnu-taler/web-util/browser"; import { h, VNode } from "preact"; import { AsyncButton } from "../../../../components/exception/AsyncButton.js"; import { ProductForm } from "../../../../components/product/ProductForm.js"; -import { MerchantBackend } from "../../../../declaration.js"; import { useListener } from "../../../../hooks/listener.js"; -import { Translate, useTranslator } from "../../../../i18n/index.js"; -type Entity = MerchantBackend.Products.ProductAddDetail & { product_id: string} +type Entity = TalerMerchantApi.ProductAddDetail & { + product_id: string; +}; interface Props { onCreate: (d: Entity) => Promise<void>; onBack?: () => void; } - export function CreatePage({ onCreate, onBack }: Props): VNode { + const [submitForm, addFormSubmitter] = useListener<Entity | undefined>( + (result) => { + if (result) return onCreate(result); + return Promise.reject(); + }, + ); - const [submitForm, addFormSubmitter] = useListener<Entity | undefined>((result) => { - if (result) return onCreate(result) - return Promise.reject() - }) - - const i18n = useTranslator() + const { i18n } = useTranslationContext(); - return <div> - <section class="section is-main-section"> - <div class="columns"> - <div class="column" /> - <div class="column is-four-fifths"> - <ProductForm onSubscribe={addFormSubmitter} /> + return ( + <div> + <section class="section is-main-section"> + <div class="columns"> + <div class="column" /> + <div class="column is-four-fifths"> + <ProductForm onSubscribe={addFormSubmitter} /> - <div class="buttons is-right mt-5"> - {onBack && <button class="button" onClick={onBack} ><Translate>Cancel</Translate></button>} - <AsyncButton onClick={submitForm} data-tooltip={ - !submitForm ? i18n`Need to complete marked fields` : 'confirm operation' - } disabled={!submitForm}><Translate>Confirm</Translate></AsyncButton> + <div class="buttons is-right mt-5"> + {onBack && ( + <button class="button" onClick={onBack}> + <i18n.Translate>Cancel</i18n.Translate> + </button> + )} + <AsyncButton + onClick={submitForm} + data-tooltip={ + !submitForm + ? i18n.str`Need to complete marked fields` + : "confirm operation" + } + disabled={!submitForm} + > + <i18n.Translate>Confirm</i18n.Translate> + </AsyncButton> + </div> </div> - + <div class="column" /> </div> - <div class="column" /> - </div> - </section> - </div> -}
\ No newline at end of file + </section> + </div> + ); +} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/products/create/CreatedSuccessfully.tsx b/packages/merchant-backoffice-ui/src/paths/instance/products/create/CreatedSuccessfully.tsx index 9bbdc4070..2b6ebed45 100644 --- a/packages/merchant-backoffice-ui/src/paths/instance/products/create/CreatedSuccessfully.tsx +++ b/packages/merchant-backoffice-ui/src/paths/instance/products/create/CreatedSuccessfully.tsx @@ -1,6 +1,6 @@ /* This file is part of GNU Taler - (C) 2021 Taler Systems S.A. + (C) 2021-2024 Taler Systems S.A. GNU Taler is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -24,44 +24,49 @@ interface Props { onCreateAnother?: () => void; } -export function CreatedSuccessfully({ entity, onConfirm, onCreateAnother }: Props): VNode { - - return <Template onConfirm={onConfirm} onCreateAnother={onCreateAnother}> - <div class="field is-horizontal"> - <div class="field-label is-normal"> - <label class="label">Image</label> - </div> - <div class="field-body is-flex-grow-3"> - <div class="field"> - <p class="control"> - <img src={entity.image} style={{ width: 200, height: 200 }} /> - </p> +export function CreatedSuccessfully({ + entity, + onConfirm, + onCreateAnother, +}: Props): VNode { + return ( + <Template onConfirm={onConfirm} onCreateAnother={onCreateAnother}> + <div class="field is-horizontal"> + <div class="field-label is-normal"> + <label class="label">Image</label> </div> - </div> - </div> - <div class="field is-horizontal"> - <div class="field-label is-normal"> - <label class="label">Description</label> - </div> - <div class="field-body is-flex-grow-3"> - <div class="field"> - <p class="control"> - <textarea class="input" readonly value={entity.description} /> - </p> + <div class="field-body is-flex-grow-3"> + <div class="field"> + <p class="control"> + <img src={entity.image} style={{ width: 200, height: 200 }} /> + </p> + </div> </div> </div> - </div> - <div class="field is-horizontal"> - <div class="field-label is-normal"> - <label class="label">Price</label> + <div class="field is-horizontal"> + <div class="field-label is-normal"> + <label class="label">Description</label> + </div> + <div class="field-body is-flex-grow-3"> + <div class="field"> + <p class="control"> + <textarea class="input" readonly value={entity.description} /> + </p> + </div> + </div> </div> - <div class="field-body is-flex-grow-3"> - <div class="field"> - <p class="control"> - <input class="input" readonly value={entity.price} /> - </p> + <div class="field is-horizontal"> + <div class="field-label is-normal"> + <label class="label">Price</label> + </div> + <div class="field-body is-flex-grow-3"> + <div class="field"> + <p class="control"> + <input class="input" readonly value={entity.price} /> + </p> + </div> </div> </div> - </div> - </Template>; + </Template> + ); } diff --git a/packages/merchant-backoffice-ui/src/paths/instance/products/create/index.tsx b/packages/merchant-backoffice-ui/src/paths/instance/products/create/index.tsx index 51dc63431..9de5cae78 100644 --- a/packages/merchant-backoffice-ui/src/paths/instance/products/create/index.tsx +++ b/packages/merchant-backoffice-ui/src/paths/instance/products/create/index.tsx @@ -1,6 +1,6 @@ /* This file is part of GNU Taler - (C) 2021 Taler Systems S.A. + (C) 2021-2024 Taler Systems S.A. GNU Taler is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -15,41 +15,47 @@ */ /** -* -* @author Sebastian Javier Marchano (sebasjm) -*/ + * + * @author Sebastian Javier Marchano (sebasjm) + */ -import { Fragment, h, VNode } from 'preact'; -import { useState } from 'preact/hooks'; +import { TalerMerchantApi } from "@gnu-taler/taler-util"; +import { useTranslationContext } from "@gnu-taler/web-util/browser"; +import { Fragment, VNode, h } from "preact"; +import { useState } from "preact/hooks"; import { NotificationCard } from "../../../../components/menu/index.js"; -import { MerchantBackend } from "../../../../declaration.js"; -import { useProductAPI } from "../../../../hooks/product.js"; -import { useTranslator } from '../../../../i18n/index.js'; +import { useSessionContext } from "../../../../context/session.js"; import { Notification } from "../../../../utils/types.js"; import { CreatePage } from "./CreatePage.js"; -export type Entity = MerchantBackend.Products.ProductAddDetail +export type Entity = TalerMerchantApi.ProductAddDetail; interface Props { onBack?: () => void; onConfirm: () => void; } export default function CreateProduct({ onConfirm, onBack }: Props): VNode { - const { createProduct } = useProductAPI() - const [notif, setNotif] = useState<Notification | undefined>(undefined) - const i18n = useTranslator() - - return <Fragment> - <NotificationCard notification={notif} /> - <CreatePage - onBack={onBack} - onCreate={(request: MerchantBackend.Products.ProductAddDetail) => { - return createProduct(request).then(() => onConfirm()).catch((error) => { - setNotif({ - message: i18n`could not create product`, - type: "ERROR", - description: error.message - }) - }) - }} /> - </Fragment> -}
\ No newline at end of file + const { lib } = useSessionContext(); + const { state } = useSessionContext(); + const [notif, setNotif] = useState<Notification | undefined>(undefined); + const { i18n } = useTranslationContext(); + + return ( + <Fragment> + <NotificationCard notification={notif} /> + <CreatePage + onBack={onBack} + onCreate={(request: TalerMerchantApi.ProductAddDetail) => { + return lib.instance.addProduct(state.token, request) + .then(() => onConfirm()) + .catch((error) => { + setNotif({ + message: i18n.str`could not create product`, + type: "ERROR", + description: error.message, + }); + }); + }} + /> + </Fragment> + ); +} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/products/list/List.stories.tsx b/packages/merchant-backoffice-ui/src/paths/instance/products/list/List.stories.tsx index 53217d051..580a92cdc 100644 --- a/packages/merchant-backoffice-ui/src/paths/instance/products/list/List.stories.tsx +++ b/packages/merchant-backoffice-ui/src/paths/instance/products/list/List.stories.tsx @@ -1,6 +1,6 @@ /* This file is part of GNU Taler - (C) 2021 Taler Systems S.A. + (C) 2021-2024 Taler Systems S.A. GNU Taler is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -15,44 +15,48 @@ */ /** -* -* @author Sebastian Javier Marchano (sebasjm) -*/ + * + * @author Sebastian Javier Marchano (sebasjm) + */ -import { h, VNode, FunctionalComponent } from 'preact'; +import { AmountString } from "@gnu-taler/taler-util"; +import { FunctionalComponent, h } from "preact"; import { CardTable as TestedComponent } from "./Table.js"; - export default { - title: 'Pages/Product/List', + title: "Pages/Product/List", component: TestedComponent, argTypes: { - onCreate: { action: 'onCreate' }, - onSelect: { action: 'onSelect' }, - onDelete: { action: 'onDelete' }, - onUpdate: { action: 'onUpdate' }, + onCreate: { action: "onCreate" }, + onSelect: { action: "onSelect" }, + onDelete: { action: "onDelete" }, + onUpdate: { action: "onUpdate" }, }, }; -function createExample<Props>(Component: FunctionalComponent<Props>, props: Partial<Props>) { - const r = (args: any) => <Component {...args} /> - r.args = props - return r +function createExample<Props>( + Component: FunctionalComponent<Props>, + props: Partial<Props>, +) { + const r = (args: any) => <Component {...args} />; + r.args = props; + return r; } - export const Example = createExample(TestedComponent, { - instances: [{ - id: 'orderid', - description: 'description1', - description_i18n: {} as any, - image: '', - price: 'TESTKUDOS:10', - taxes: [], - total_lost: 10, - total_sold: 5, - total_stock: 15, - unit: 'bar', - address: {} - }] + instances: [ + { + id: "orderid", + description: "description1", + description_i18n: {} as any, + image: "", + price: "TESTKUDOS:10" as AmountString, + taxes: [], + total_lost: 10, + total_sold: 5, + total_stock: 15, + unit: "bar", + address: {}, + }, + ], }); diff --git a/packages/merchant-backoffice-ui/src/paths/instance/products/list/Table.tsx b/packages/merchant-backoffice-ui/src/paths/instance/products/list/Table.tsx index 81acb9876..39e2fd0c7 100644 --- a/packages/merchant-backoffice-ui/src/paths/instance/products/list/Table.tsx +++ b/packages/merchant-backoffice-ui/src/paths/instance/products/list/Table.tsx @@ -1,6 +1,6 @@ /* This file is part of GNU Taler - (C) 2021 Taler Systems S.A. + (C) 2021-2024 Taler Systems S.A. GNU Taler is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -19,21 +19,21 @@ * @author Sebastian Javier Marchano (sebasjm) */ +import { AmountString, Amounts, TalerMerchantApi } from "@gnu-taler/taler-util"; +import { useTranslationContext } from "@gnu-taler/web-util/browser"; import { format } from "date-fns"; -import { ComponentChildren, Fragment, h, VNode } from "preact"; +import { ComponentChildren, Fragment, VNode, h } from "preact"; import { StateUpdater, useState } from "preact/hooks"; +import emptyImage from "../../../../assets/empty.png"; import { - FormProvider, FormErrors, + FormProvider, } from "../../../../components/form/FormProvider.js"; import { InputCurrency } from "../../../../components/form/InputCurrency.js"; import { InputNumber } from "../../../../components/form/InputNumber.js"; -import { MerchantBackend, WithId } from "../../../../declaration.js"; -import emptyImage from "../../../../assets/empty.png"; -import { Translate, useTranslator } from "../../../../i18n/index.js"; -import { Amounts } from "@gnu-taler/taler-util"; +import { dateFormatForSettings, usePreference } from "../../../../hooks/preference.js"; -type Entity = MerchantBackend.Products.ProductDetail & WithId; +type Entity = TalerMerchantApi.ProductDetail & WithId; interface Props { instances: Entity[]; @@ -41,10 +41,12 @@ interface Props { onSelect: (product: Entity) => void; onUpdate: ( id: string, - data: MerchantBackend.Products.ProductPatchDetail + data: TalerMerchantApi.ProductPatchDetail, ) => Promise<void>; onCreate: () => void; selected?: boolean; + onLoadMoreBefore?: () => void; + onLoadMoreAfter?: () => void; } export function CardTable({ @@ -53,11 +55,13 @@ export function CardTable({ onSelect, onUpdate, onDelete, + onLoadMoreAfter, + onLoadMoreBefore }: Props): VNode { const [rowSelection, rowSelectionHandler] = useState<string | undefined>( - undefined + undefined, ); - const i18n = useTranslator(); + const { i18n } = useTranslationContext(); return ( <div class="card has-table"> <header class="card-header"> @@ -65,12 +69,12 @@ export function CardTable({ <span class="icon"> <i class="mdi mdi-shopping" /> </span> - <Translate>Products</Translate> + <i18n.Translate>Inventory</i18n.Translate> </p> <div class="card-header-icon" aria-label="more options"> <span class="has-tooltip-left" - data-tooltip={i18n`add product to inventory`} + data-tooltip={i18n.str`add product to inventory`} > <button class="button is-info" type="button" onClick={onCreate}> <span class="icon is-small"> @@ -89,6 +93,8 @@ export function CardTable({ onSelect={onSelect} onDelete={onDelete} onUpdate={onUpdate} + onLoadMoreAfter={onLoadMoreAfter} + onLoadMoreBefore={onLoadMoreBefore} rowSelection={rowSelection} rowSelectionHandler={rowSelectionHandler} /> @@ -107,10 +113,12 @@ interface TableProps { onSelect: (id: Entity) => void; onUpdate: ( id: string, - data: MerchantBackend.Products.ProductPatchDetail + data: TalerMerchantApi.ProductPatchDetail, ) => Promise<void>; onDelete: (id: Entity) => void; rowSelectionHandler: StateUpdater<string | undefined>; + onLoadMoreBefore?: () => void; + onLoadMoreAfter?: () => void; } function Table({ @@ -120,33 +128,41 @@ function Table({ onSelect, onUpdate, onDelete, + onLoadMoreAfter, + onLoadMoreBefore }: TableProps): VNode { - const i18n = useTranslator(); + const { i18n } = useTranslationContext(); + const [settings] = usePreference(); return ( <div class="table-container"> + {onLoadMoreBefore && ( + <button class="button is-fullwidth" onClick={onLoadMoreBefore}> + <i18n.Translate>load first page</i18n.Translate> + </button> + )} <table class="table is-fullwidth is-striped is-hoverable is-fullwidth"> <thead> <tr> <th> - <Translate>Image</Translate> + <i18n.Translate>Image</i18n.Translate> </th> <th> - <Translate>Description</Translate> + <i18n.Translate>Description</i18n.Translate> </th> <th> - <Translate>Sell</Translate> + <i18n.Translate>Price per unit</i18n.Translate> </th> <th> - <Translate>Taxes</Translate> + <i18n.Translate>Taxes</i18n.Translate> </th> <th> - <Translate>Profit</Translate> + <i18n.Translate>Sales</i18n.Translate> </th> <th> - <Translate>Stock</Translate> + <i18n.Translate>Stock</i18n.Translate> </th> <th> - <Translate>Sold</Translate> + <i18n.Translate>Sold</i18n.Translate> </th> <th /> </tr> @@ -156,10 +172,10 @@ function Table({ const restStockInfo = !i.next_restock ? "" : i.next_restock.t_s === "never" - ? "never" - : `restock at ${format( + ? "never" + : `restock at ${format( new Date(i.next_restock.t_s * 1000), - "yyyy/MM/dd" + dateFormatForSettings(settings), )}`; let stockInfo: ComponentChildren = ""; if (i.total_stock < 0) { @@ -188,18 +204,21 @@ function Table({ src={i.image ? i.image : emptyImage} style={{ border: "solid black 1px", - width: 100, - height: 100, + maxHeight: "2em", + width: "auto", + height: "auto", }} /> </td> <td + class="has-tooltip-right" + data-tooltip={i.description} onClick={() => rowSelection !== i.id && rowSelectionHandler(i.id) } style={{ cursor: "pointer" }} > - {i.description} + {i.description.length > 30 ? i.description.substring(0, 30) + "..." : i.description} </td> <td onClick={() => @@ -207,7 +226,7 @@ function Table({ } style={{ cursor: "pointer" }} > - {isFree ? i18n`free` : `${i.price} / ${i.unit}`} + {isFree ? i18n.str`free` : `${i.price} / ${i.unit}`} </td> <td onClick={() => @@ -239,32 +258,35 @@ function Table({ } style={{ cursor: "pointer" }} > - {i.total_sold} {i.unit} + <span style={{ "whiteSpace": "nowrap" }}> + + {i.total_sold} {i.unit} + </span> </td> <td class="is-actions-cell right-sticky"> <div class="buttons is-right"> <span class="has-tooltip-bottom" - data-tooltip={i18n`go to product update page`} + data-tooltip={i18n.str`go to product update page`} > <button class="button is-small is-success " type="button" onClick={(): void => onSelect(i)} > - <Translate>Update</Translate> + <i18n.Translate>Update</i18n.Translate> </button> </span> <span class="has-tooltip-left" - data-tooltip={i18n`remove this product from the database`} + data-tooltip={i18n.str`remove this product from the database`} > <button class="button is-small is-danger" type="button" onClick={(): void => onDelete(i)} > - <Translate>Delete</Translate> + <i18n.Translate>Delete</i18n.Translate> </button> </span> </div> @@ -276,8 +298,8 @@ function Table({ <FastProductUpdateForm product={i} onUpdate={(prod) => - onUpdate(i.id, prod).then((r) => - rowSelectionHandler(undefined) + onUpdate(i.id, prod).then(() => + rowSelectionHandler(undefined), ) } onCancel={() => rowSelectionHandler(undefined)} @@ -290,6 +312,13 @@ function Table({ })} </tbody> </table> + {onLoadMoreAfter && ( + <button class="button is-fullwidth" + data-tooltip={i18n.str`load more products after the last one`} + onClick={onLoadMoreAfter}> + <i18n.Translate>load next page</i18n.Translate> + </button> + )} </div> ); } @@ -297,7 +326,7 @@ function Table({ interface FastProductUpdateFormProps { product: Entity; onUpdate: ( - data: MerchantBackend.Products.ProductPatchDetail + data: TalerMerchantApi.ProductPatchDetail, ) => Promise<void>; onCancel: () => void; } @@ -316,7 +345,7 @@ function FastProductWithInfiniteStockUpdateForm({ onCancel, }: FastProductUpdateFormProps) { const [value, valueHandler] = useState<UpdatePrice>({ price: product.price }); - const i18n = useTranslator(); + const { i18n } = useTranslationContext(); return ( <Fragment> @@ -327,31 +356,34 @@ function FastProductWithInfiniteStockUpdateForm({ > <InputCurrency<FastProductUpdate> name="price" - label={i18n`Price`} - tooltip={i18n`update the product with new price`} + label={i18n.str`Price`} + tooltip={i18n.str`update the product with new price`} /> </FormProvider> - <div class="buttons is-right mt-5"> - <button class="button" onClick={onCancel}> - <Translate>Cancel</Translate> - </button> - <span - class="has-tooltip-left" - data-tooltip={i18n`update product with new price`} - > - <button - class="button is-info" - onClick={() => - onUpdate({ - ...product, - price: value.price, - }) - } - > - <Translate>Confirm</Translate> + <div class="buttons is-expanded"> + + <div class="buttons is-right mt-5"> + <button class="button" onClick={onCancel}> + <i18n.Translate>Cancel</i18n.Translate> </button> - </span> + <span + class="has-tooltip-left" + data-tooltip={i18n.str`update product with new price`} + > + <button + class="button is-info" + onClick={() => + onUpdate({ + ...product, + price: value.price as AmountString, + }) + } + > + <i18n.Translate>Confirm update</i18n.Translate> + </button> + </span> + </div> </div> </Fragment> ); @@ -374,16 +406,15 @@ function FastProductWithManagedStockUpdateForm({ const errors: FormErrors<FastProductUpdate> = { lost: currentStock + value.incoming < value.lost - ? `lost cannot be greater that current + incoming (max ${ - currentStock + value.incoming - })` + ? `lost cannot be greater that current + incoming (max ${currentStock + value.incoming + })` : undefined, }; const hasErrors = Object.keys(errors).some( - (k) => (errors as any)[k] !== undefined + (k) => (errors as Record<string,unknown>)[k] !== undefined, ); - const i18n = useTranslator(); + const { i18n } = useTranslationContext(); return ( <Fragment> @@ -395,31 +426,31 @@ function FastProductWithManagedStockUpdateForm({ > <InputNumber<FastProductUpdate> name="incoming" - label={i18n`Incoming`} - tooltip={i18n`add more elements to the inventory`} + label={i18n.str`Incoming`} + tooltip={i18n.str`add more elements to the inventory`} /> <InputNumber<FastProductUpdate> name="lost" - label={i18n`Lost`} - tooltip={i18n`report elements lost in the inventory`} + label={i18n.str`Lost`} + tooltip={i18n.str`report elements lost in the inventory`} /> <InputCurrency<FastProductUpdate> name="price" - label={i18n`Price`} - tooltip={i18n`new price for the product`} + label={i18n.str`Price`} + tooltip={i18n.str`new price for the product`} /> </FormProvider> <div class="buttons is-right mt-5"> <button class="button" onClick={onCancel}> - <Translate>Cancel</Translate> + <i18n.Translate>Cancel</i18n.Translate> </button> <span class="has-tooltip-left" data-tooltip={ hasErrors - ? i18n`the are value with errors` - : i18n`update product with new stock and price` + ? i18n.str`the are value with errors` + : i18n.str`update product with new stock and price` } > <button @@ -430,11 +461,11 @@ function FastProductWithManagedStockUpdateForm({ ...product, total_stock: product.total_stock + value.incoming, total_lost: product.total_lost + value.lost, - price: value.price, + price: value.price as AmountString, }) } > - <Translate>Confirm</Translate> + <i18n.Translate>Confirm</i18n.Translate> </button> </span> </div> @@ -451,17 +482,18 @@ function FastProductUpdateForm(props: FastProductUpdateFormProps) { } function EmptyTable(): VNode { + const { i18n } = useTranslationContext(); return ( <div class="content has-text-grey has-text-centered"> <p> <span class="icon is-large"> - <i class="mdi mdi-emoticon-sad mdi-48px" /> + <i class="mdi mdi-magnify mdi-48px" /> </span> </p> <p> - <Translate> + <i18n.Translate> There is no products yet, add more pressing the + sign - </Translate> + </i18n.Translate> </p> </div> ); @@ -474,6 +506,7 @@ function difference(price: string, tax: number) { ps[1] = `${p - tax}`; return ps.join(":"); } -function sum(taxes: MerchantBackend.Tax[]) { +function sum(taxes: TalerMerchantApi.Tax[] | undefined) { + if (taxes === undefined) return 0; return taxes.reduce((p, c) => p + parseInt(c.tax.split(":")[1], 10), 0); } diff --git a/packages/merchant-backoffice-ui/src/paths/instance/products/list/index.tsx b/packages/merchant-backoffice-ui/src/paths/instance/products/list/index.tsx index eb98d7871..6ad0d4598 100644 --- a/packages/merchant-backoffice-ui/src/paths/instance/products/list/index.tsx +++ b/packages/merchant-backoffice-ui/src/paths/instance/products/list/index.tsx @@ -1,6 +1,6 @@ /* This file is part of GNU Taler - (C) 2021 Taler Systems S.A. + (C) 2021-2024 Taler Systems S.A. GNU Taler is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -15,66 +15,139 @@ */ /** -* -* @author Sebastian Javier Marchano (sebasjm) -*/ + * + * @author Sebastian Javier Marchano (sebasjm) + */ -import { h, VNode } from 'preact'; -import { useState } from 'preact/hooks'; +import { HttpStatusCode, TalerError, TalerMerchantApi, assertUnreachable } from "@gnu-taler/taler-util"; +import { + useTranslationContext +} from "@gnu-taler/web-util/browser"; +import { VNode, h } from "preact"; +import { useState } from "preact/hooks"; +import { ErrorLoadingMerchant } from "../../../../components/ErrorLoadingMerchant.js"; import { Loading } from "../../../../components/exception/loading.js"; +import { JumpToElementById } from "../../../../components/form/JumpToElementById.js"; import { NotificationCard } from "../../../../components/menu/index.js"; -import { MerchantBackend, WithId } from "../../../../declaration.js"; -import { HttpError } from "../../../../hooks/backend.js"; -import { useInstanceProducts, useProductAPI } from "../../../../hooks/product.js"; -import { useTranslator } from '../../../../i18n/index.js'; +import { ConfirmModal } from "../../../../components/modal/index.js"; +import { useSessionContext } from "../../../../context/session.js"; +import { + useInstanceProducts +} from "../../../../hooks/product.js"; import { Notification } from "../../../../utils/types.js"; +import { LoginPage } from "../../../login/index.js"; +import { NotFoundPageOrAdminCreate } from "../../../notfound/index.js"; import { CardTable } from "./Table.js"; interface Props { - onUnauthorized: () => VNode; - onNotFound: () => VNode; onCreate: () => void; onSelect: (id: string) => void; - onLoadError: (e: HttpError) => VNode; } -export default function ProductList({ onUnauthorized, onLoadError, onCreate, onSelect, onNotFound }: Props): VNode { - const result = useInstanceProducts() - const { deleteProduct, updateProduct } = useProductAPI() - const [notif, setNotif] = useState<Notification | undefined>(undefined) - - const i18n = useTranslator() - - if (result.clientError && result.isUnauthorized) return onUnauthorized() - if (result.clientError && result.isNotfound) return onNotFound() - if (result.loading) return <Loading /> - if (!result.ok) return onLoadError(result) +export default function ProductList({ + onCreate, + onSelect, +}: Props): VNode { + const result = useInstanceProducts(); + const { lib } = useSessionContext(); + const { state } = useSessionContext(); + const [deleting, setDeleting] = + useState<TalerMerchantApi.ProductDetail & WithId | null>(null); + const [notif, setNotif] = useState<Notification | undefined>(undefined); - return <section class="section is-main-section"> - <NotificationCard notification={notif} /> + const { i18n } = useTranslationContext(); - <CardTable instances={result.data} - onCreate={onCreate} - onUpdate={(id, prod) => updateProduct(id, prod) - .then(() => setNotif({ - message: i18n`product updated successfully`, - type: "SUCCESS" - })).catch((error) => setNotif({ - message: i18n`could not update the product`, - type: "ERROR", - description: error.message - })) + if (!result) return <Loading />; + if (result instanceof TalerError) { + return <ErrorLoadingMerchant error={result} />; + } + if (result.type === "fail") { + switch (result.case) { + case HttpStatusCode.NotFound: { + return <NotFoundPageOrAdminCreate />; } - onSelect={(product) => onSelect(product.id)} - onDelete={(prod: (MerchantBackend.Products.ProductDetail & WithId)) => deleteProduct(prod.id) - .then(() => setNotif({ - message: i18n`product delete successfully`, - type: "SUCCESS" - })).catch((error) => setNotif({ - message: i18n`could not delete the product`, - type: "ERROR", - description: error.message - })) + case HttpStatusCode.Unauthorized: { + return <LoginPage /> } - /> - </section> -}
\ No newline at end of file + default: { + assertUnreachable(result); + } + } + } + + return ( + <section class="section is-main-section"> + <NotificationCard notification={notif} /> + + <JumpToElementById + testIfExist={async (id) => { + const resp = await lib.instance.getProductDetails(state.token, id); + return resp.type === "ok"; + }} + onSelect={onSelect} + description={i18n.str`jump to product with the given product ID`} + placeholder={i18n.str`product id`} + /> + + <CardTable + instances={result.body} + onLoadMoreBefore={result.isFirstPage ? undefined : result.loadFirst} + onLoadMoreAfter={result.isLastPage ? undefined : result.loadNext} + onCreate={onCreate} + onUpdate={async (id, prod) => { + try { + await lib.instance.updateProduct(state.token, id, prod); + setNotif({ + message: i18n.str`product updated successfully`, + type: "SUCCESS", + }); + } catch (error) { + setNotif({ + message: i18n.str`could not update the product`, + type: "ERROR", + description: error instanceof Error ? error.message : undefined, + }); + } + return + }} + onSelect={(product) => onSelect(product.id)} + onDelete={(prod: TalerMerchantApi.ProductDetail & WithId) => + setDeleting(prod) + } + /> + + {deleting && ( + <ConfirmModal + label={`Delete product`} + description={`Delete the product "${deleting.description}"`} + danger + active + onCancel={() => setDeleting(null)} + onConfirm={async (): Promise<void> => { + try { + await lib.instance.deleteProduct(state.token, deleting.id); + setNotif({ + message: i18n.str`Product "${deleting.description}" (ID: ${deleting.id}) has been deleted`, + type: "SUCCESS", + }); + } catch (error) { + setNotif({ + message: i18n.str`Failed to delete product`, + type: "ERROR", + description: error instanceof Error ? error.message : undefined, + }); + } + setDeleting(null); + }} + > + <p> + If you delete the product named <b>"{deleting.description}"</b> (ID:{" "} + <b>{deleting.id}</b>), the stock and related information will be lost + </p> + <p class="warning"> + Deleting an product <b>cannot be undone</b>. + </p> + </ConfirmModal> + )} + </section> + ); +} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/products/update/Update.stories.tsx b/packages/merchant-backoffice-ui/src/paths/instance/products/update/Update.stories.tsx index f97d6d367..7aa93b186 100644 --- a/packages/merchant-backoffice-ui/src/paths/instance/products/update/Update.stories.tsx +++ b/packages/merchant-backoffice-ui/src/paths/instance/products/update/Update.stories.tsx @@ -1,6 +1,6 @@ /* This file is part of GNU Taler - (C) 2021 Taler Systems S.A. + (C) 2021-2024 Taler Systems S.A. GNU Taler is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -15,57 +15,60 @@ */ /** -* -* @author Sebastian Javier Marchano (sebasjm) -*/ + * + * @author Sebastian Javier Marchano (sebasjm) + */ -import { h, VNode, FunctionalComponent } from 'preact'; +import { AmountString } from "@gnu-taler/taler-util"; +import { FunctionalComponent, h } from "preact"; import { UpdatePage as TestedComponent } from "./UpdatePage.js"; - export default { - title: 'Pages/Product/Update', + title: "Pages/Product/Update", component: TestedComponent, argTypes: { - onUpdate: { action: 'onUpdate' }, - onBack: { action: 'onBack' }, + onUpdate: { action: "onUpdate" }, + onBack: { action: "onBack" }, }, }; -function createExample<Props>(Component: FunctionalComponent<Props>, props: Partial<Props>) { - const r = (args: any) => <Component {...args} /> - r.args = props - return r +function createExample<Props>( + Component: FunctionalComponent<Props>, + props: Partial<Props>, +) { + const r = (args: any) => <Component {...args} />; + r.args = props; + return r; } export const WithManagedStock = createExample(TestedComponent, { product: { - product_id: '20102-ASDAS-QWE', - description: 'description1', + product_id: "20102-ASDAS-QWE", + description: "description1", description_i18n: {} as any, - image: '', - price: 'TESTKUDOS:10', + image: "", + price: "TESTKUDOS:10" as AmountString, taxes: [], total_lost: 10, total_sold: 5, total_stock: 15, - unit: 'bar', - address: {} - } + unit: "bar", + address: {}, + }, }); export const WithInfiniteStock = createExample(TestedComponent, { product: { - product_id: '20102-ASDAS-QWE', - description: 'description1', + product_id: "20102-ASDAS-QWE", + description: "description1", description_i18n: {} as any, - image: '', - price: 'TESTKUDOS:10', + image: "", + price: "TESTKUDOS:10" as AmountString, taxes: [], total_lost: 10, total_sold: 5, total_stock: -1, - unit: 'bar', - address: {} - } + unit: "bar", + address: {}, + }, }); diff --git a/packages/merchant-backoffice-ui/src/paths/instance/products/update/UpdatePage.tsx b/packages/merchant-backoffice-ui/src/paths/instance/products/update/UpdatePage.tsx index ff1b3979d..5395ae40f 100644 --- a/packages/merchant-backoffice-ui/src/paths/instance/products/update/UpdatePage.tsx +++ b/packages/merchant-backoffice-ui/src/paths/instance/products/update/UpdatePage.tsx @@ -1,6 +1,6 @@ /* This file is part of GNU Taler - (C) 2021 Taler Systems S.A. + (C) 2021-2024 Taler Systems S.A. GNU Taler is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -15,18 +15,18 @@ */ /** -* -* @author Sebastian Javier Marchano (sebasjm) -*/ + * + * @author Sebastian Javier Marchano (sebasjm) + */ +import { TalerMerchantApi } from "@gnu-taler/taler-util"; +import { useTranslationContext } from "@gnu-taler/web-util/browser"; import { h, VNode } from "preact"; import { AsyncButton } from "../../../../components/exception/AsyncButton.js"; import { ProductForm } from "../../../../components/product/ProductForm.js"; -import { MerchantBackend, WithId } from "../../../../declaration.js"; import { useListener } from "../../../../hooks/listener.js"; -import { Translate, useTranslator } from "../../../../i18n/index.js"; -type Entity = MerchantBackend.Products.ProductDetail & { product_id: string } +type Entity = TalerMerchantApi.ProductDetail & { product_id: string }; interface Props { onUpdate: (d: Entity) => Promise<void>; @@ -35,43 +35,65 @@ interface Props { } export function UpdatePage({ product, onUpdate, onBack }: Props): VNode { - const [submitForm, addFormSubmitter] = useListener<Entity | undefined>((result) => { - if (result) return onUpdate(result) - return Promise.resolve() - }) - - const i18n = useTranslator() + const [submitForm, addFormSubmitter] = useListener<Entity | undefined>( + (result) => { + if (result) return onUpdate(result); + return Promise.resolve(); + }, + ); - return <div> - <section class="section"> - <section class="hero is-hero-bar"> - <div class="hero-body"> + const { i18n } = useTranslationContext(); - <div class="level"> - <div class="level-left"> - <div class="level-item"> - <span class="is-size-4"><Translate>Product id:</Translate><b>{product.product_id}</b></span> + return ( + <div> + <section class="section"> + <section class="hero is-hero-bar"> + <div class="hero-body"> + <div class="level"> + <div class="level-left"> + <div class="level-item"> + <span class="is-size-4"> + <i18n.Translate>Product id:</i18n.Translate> + <b>{product.product_id}</b> + </span> + </div> </div> </div> </div> - </div> - </section> - <hr /> + </section> + <hr /> - <div class="columns"> - <div class="column" /> - <div class="column is-four-fifths"> - <ProductForm initial={product} onSubscribe={addFormSubmitter} alreadyExist /> + <div class="columns"> + <div class="column" /> + <div class="column is-four-fifths"> + <ProductForm + initial={product} + onSubscribe={addFormSubmitter} + alreadyExist + /> - <div class="buttons is-right mt-5"> - {onBack && <button class="button" onClick={onBack} ><Translate>Cancel</Translate></button>} - <AsyncButton onClick={submitForm} data-tooltip={ - !submitForm ? i18n`Need to complete marked fields` : 'confirm operation' - } disabled={!submitForm}><Translate>Confirm</Translate></AsyncButton> + <div class="buttons is-right mt-5"> + {onBack && ( + <button class="button" onClick={onBack}> + <i18n.Translate>Cancel</i18n.Translate> + </button> + )} + <AsyncButton + onClick={submitForm} + data-tooltip={ + !submitForm + ? i18n.str`Need to complete marked fields` + : "confirm operation" + } + disabled={!submitForm} + > + <i18n.Translate>Confirm</i18n.Translate> + </AsyncButton> + </div> </div> + <div class="column" /> </div> - <div class="column" /> - </div> - </section> - </div> -}
\ No newline at end of file + </section> + </div> + ); +} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/products/update/index.tsx b/packages/merchant-backoffice-ui/src/paths/instance/products/update/index.tsx index 59cfec15a..5e3e58d80 100644 --- a/packages/merchant-backoffice-ui/src/paths/instance/products/update/index.tsx +++ b/packages/merchant-backoffice-ui/src/paths/instance/products/update/index.tsx @@ -1,6 +1,6 @@ /* This file is part of GNU Taler - (C) 2021 Taler Systems S.A. + (C) 2021-2024 Taler Systems S.A. GNU Taler is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -15,57 +15,80 @@ */ /** -* -* @author Sebastian Javier Marchano (sebasjm) -*/ + * + * @author Sebastian Javier Marchano (sebasjm) + */ -import { Fragment, h, VNode } from 'preact'; -import { useState } from 'preact/hooks'; +import { HttpStatusCode, TalerError, TalerMerchantApi, assertUnreachable } from "@gnu-taler/taler-util"; +import { + useTranslationContext +} from "@gnu-taler/web-util/browser"; +import { Fragment, VNode, h } from "preact"; +import { useState } from "preact/hooks"; +import { ErrorLoadingMerchant } from "../../../../components/ErrorLoadingMerchant.js"; import { Loading } from "../../../../components/exception/loading.js"; import { NotificationCard } from "../../../../components/menu/index.js"; -import { MerchantBackend } from "../../../../declaration.js"; -import { HttpError } from "../../../../hooks/backend.js"; -import { useProductAPI, useProductDetails } from "../../../../hooks/product.js"; -import { useTranslator } from '../../../../i18n/index.js'; +import { useSessionContext } from "../../../../context/session.js"; +import { useProductDetails } from "../../../../hooks/product.js"; import { Notification } from "../../../../utils/types.js"; +import { LoginPage } from "../../../login/index.js"; +import { NotFoundPageOrAdminCreate } from "../../../notfound/index.js"; import { UpdatePage } from "./UpdatePage.js"; -export type Entity = MerchantBackend.Products.ProductAddDetail +export type Entity = TalerMerchantApi.ProductAddDetail; interface Props { onBack?: () => void; onConfirm: () => void; - onUnauthorized: () => VNode; - onNotFound: () => VNode; - onLoadError: (e: HttpError) => VNode; pid: string; } -export default function UpdateProduct({ pid, onConfirm, onBack, onUnauthorized, onNotFound, onLoadError }: Props): VNode { - const { updateProduct } = useProductAPI() - const result = useProductDetails(pid) - const [notif, setNotif] = useState<Notification | undefined>(undefined) +export default function UpdateProduct({ + pid, + onConfirm, + onBack, +}: Props): VNode { + const result = useProductDetails(pid); + const [notif, setNotif] = useState<Notification | undefined>(undefined); + const { lib } = useSessionContext(); + const { state } = useSessionContext(); - const i18n = useTranslator() + const { i18n } = useTranslationContext(); - if (result.clientError && result.isUnauthorized) return onUnauthorized() - if (result.clientError && result.isNotfound) return onNotFound() - if (result.loading) return <Loading /> - if (!result.ok) return onLoadError(result) + if (!result) return <Loading />; + if (result instanceof TalerError) { + return <ErrorLoadingMerchant error={result} />; + } + if (result.type === "fail") { + switch (result.case) { + case HttpStatusCode.NotFound: { + return <NotFoundPageOrAdminCreate />; + } + case HttpStatusCode.Unauthorized: { + return <LoginPage /> + } + default: { + assertUnreachable(result); + } + } + } - return <Fragment> - <NotificationCard notification={notif} /> - <UpdatePage - product={{ ...result.data, product_id: pid }} - onBack={onBack} - onUpdate={(data) => { - return updateProduct(pid, data) - .then(onConfirm) - .catch((error) => { - setNotif({ - message: i18n`could not create product`, - type: "ERROR", - description: error.message - }) - }) - }} /> - </Fragment> -}
\ No newline at end of file + return ( + <Fragment> + <NotificationCard notification={notif} /> + <UpdatePage + product={{ ...result.body, product_id: pid }} + onBack={onBack} + onUpdate={(data) => { + return lib.instance.updateProduct(state.token, pid, data) + .then(onConfirm) + .catch((error) => { + setNotif({ + message: i18n.str`could not create product`, + type: "ERROR", + description: error.message, + }); + }); + }} + /> + </Fragment> + ); +} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/reserves/create/CreatePage.tsx b/packages/merchant-backoffice-ui/src/paths/instance/reserves/create/CreatePage.tsx deleted file mode 100644 index 4d92e812f..000000000 --- a/packages/merchant-backoffice-ui/src/paths/instance/reserves/create/CreatePage.tsx +++ /dev/null @@ -1,168 +0,0 @@ -/* - This file is part of GNU Taler - (C) 2021 Taler Systems S.A. - - GNU Taler is free software; you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation; either version 3, or (at your option) any later version. - - GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License along with - GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> - */ - -/** -* -* @author Sebastian Javier Marchano (sebasjm) -*/ - -import { Fragment, h, VNode } from "preact"; -import { StateUpdater, useEffect, useState } from "preact/hooks"; -import { FormErrors, FormProvider } from "../../../../components/form/FormProvider.js"; -import { Input } from "../../../../components/form/Input.js"; -import { InputCurrency } from "../../../../components/form/InputCurrency.js"; -import { ExchangeBackend, MerchantBackend } from "../../../../declaration.js"; -import { Translate, useTranslator } from "../../../../i18n/index.js"; -import { AsyncButton } from "../../../../components/exception/AsyncButton.js"; -import { canonicalizeBaseUrl, ExchangeKeysJson } from "@gnu-taler/taler-util" -import { PAYTO_WIRE_METHOD_LOOKUP, URL_REGEX } from "../../../../utils/constants.js"; -import { request } from "../../../../hooks/backend.js"; -import { InputSelector } from "../../../../components/form/InputSelector.js"; - -type Entity = MerchantBackend.Tips.ReserveCreateRequest - -interface Props { - onCreate: (d: Entity) => Promise<void>; - onBack?: () => void; -} - - -enum Steps { - EXCHANGE, - WIRE_METHOD, -} - -interface ViewProps { - step: Steps, - setCurrentStep: (s: Steps) => void; - reserve: Partial<Entity>; - onBack?: () => void; - submitForm: () => Promise<void>; - setReserve: StateUpdater<Partial<Entity>>; -} -function ViewStep({ step, setCurrentStep, reserve, onBack, submitForm, setReserve }: ViewProps): VNode { - const i18n = useTranslator() - const [wireMethods, setWireMethods] = useState<Array<string>>([]) - const [exchangeQueryError, setExchangeQueryError] = useState<string | undefined>(undefined) - - useEffect(() => { - setExchangeQueryError(undefined) - }, [reserve.exchange_url]) - - switch (step) { - case Steps.EXCHANGE: { - const errors: FormErrors<Entity> = { - initial_balance: !reserve.initial_balance ? 'cannot be empty' : !(parseInt(reserve.initial_balance.split(':')[1], 10) > 0) ? i18n`it should be greater than 0` : undefined, - exchange_url: !reserve.exchange_url ? i18n`cannot be empty` : !URL_REGEX.test(reserve.exchange_url) ? i18n`must be a valid URL` : !exchangeQueryError ? undefined : exchangeQueryError, - } - - const hasErrors = Object.keys(errors).some(k => (errors as any)[k] !== undefined) - - return <Fragment> - <FormProvider<Entity> object={reserve} errors={errors} valueHandler={setReserve}> - <InputCurrency<Entity> name="initial_balance" label={i18n`Initial balance`} tooltip={i18n`balance prior to deposit`} /> - <Input<Entity> name="exchange_url" label={i18n`Exchange URL`} tooltip={i18n`URL of exchange`} /> - </FormProvider> - - <div class="buttons is-right mt-5"> - {onBack && <button class="button" onClick={onBack} ><Translate>Cancel</Translate></button>} - <AsyncButton class="has-tooltip-left" onClick={() => { - return request<ExchangeBackend.WireResponse>(`${reserve.exchange_url}wire`).then(r => { - const wireMethods = r.data.accounts.map(a => { - const match = PAYTO_WIRE_METHOD_LOOKUP.exec(a.payto_uri) - return match && match[1] || '' - }) - setWireMethods(wireMethods) - setCurrentStep(Steps.WIRE_METHOD) - return - }).catch((r: any) => { - setExchangeQueryError(r.message) - }) - }} data-tooltip={ - hasErrors ? i18n`Need to complete marked fields` : 'confirm operation' - } disabled={hasErrors} ><Translate>Next</Translate></AsyncButton> - </div> - </Fragment> - } - - case Steps.WIRE_METHOD: { - const errors: FormErrors<Entity> = { - wire_method: !reserve.wire_method ? i18n`cannot be empty` : undefined, - } - - const hasErrors = Object.keys(errors).some(k => (errors as any)[k] !== undefined) - return <Fragment> - <FormProvider<Entity> object={reserve} errors={errors} valueHandler={setReserve}> - <InputCurrency<Entity> name="initial_balance" label={i18n`Initial balance`} tooltip={i18n`balance prior to deposit`} readonly /> - <Input<Entity> name="exchange_url" label={i18n`Exchange URL`} tooltip={i18n`URL of exchange`} readonly /> - <InputSelector<Entity> name="wire_method" label={i18n`Wire method`} tooltip={i18n`method to use for wire transfer`} values={wireMethods} placeholder={i18n`Select one wire method`} /> - </FormProvider> - <div class="buttons is-right mt-5"> - {onBack && <button class="button" onClick={() => setCurrentStep(Steps.EXCHANGE)} ><Translate>Back</Translate></button>} - <AsyncButton onClick={submitForm} data-tooltip={ - hasErrors ? i18n`Need to complete marked fields` : 'confirm operation' - } disabled={hasErrors} ><Translate>Confirm</Translate></AsyncButton> - </div> - </Fragment> - - } - } -} - -export function CreatePage({ onCreate, onBack }: Props): VNode { - const [reserve, setReserve] = useState<Partial<Entity>>({}) - - - const submitForm = () => { - return onCreate(reserve as Entity) - } - - const [currentStep, setCurrentStep] = useState(Steps.EXCHANGE) - - - return <div> - <section class="section is-main-section"> - <div class="columns"> - <div class="column" /> - <div class="column is-four-fifths"> - - <div class="tabs is-toggle is-fullwidth is-small"> - <ul> - <li class={currentStep === Steps.EXCHANGE ? "is-active" : ""}> - <a style={{ cursor: 'initial' }}> - <span>Step 1: Specify exchange</span> - </a> - </li> - <li class={currentStep === Steps.WIRE_METHOD ? "is-active" : ""}> - <a style={{ cursor: 'initial' }}> - <span>Step 2: Select wire method</span> - </a> - </li> - </ul> - </div> - - <ViewStep step={currentStep} reserve={reserve} - setCurrentStep={setCurrentStep} - setReserve={setReserve} - submitForm={submitForm} - onBack={onBack} - /> - </div> - <div class="column" /> - </div> - </section> - </div> -} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/reserves/create/CreatedSuccessfully.stories.tsx b/packages/merchant-backoffice-ui/src/paths/instance/reserves/create/CreatedSuccessfully.stories.tsx deleted file mode 100644 index 0cea361fd..000000000 --- a/packages/merchant-backoffice-ui/src/paths/instance/reserves/create/CreatedSuccessfully.stories.tsx +++ /dev/null @@ -1,53 +0,0 @@ -/* - This file is part of GNU Taler - (C) 2021 Taler Systems S.A. - - GNU Taler is free software; you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation; either version 3, or (at your option) any later version. - - GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License along with - GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> - */ - -/** -* -* @author Sebastian Javier Marchano (sebasjm) -*/ - -import { h, VNode, FunctionalComponent } from 'preact'; -import { CreatedSuccessfully as TestedComponent } from "./CreatedSuccessfully.js"; - - -export default { - title: 'Pages/Reserve/CreatedSuccessfully', - component: TestedComponent, - argTypes: { - onCreate: { action: 'onCreate' }, - onBack: { action: 'onBack' }, - }, -}; - -function createExample<Props>(Component: FunctionalComponent<Props>, props: Partial<Props>) { - const r = (args: any) => <Component {...args} /> - r.args = props - return r -} - -export const Example = createExample(TestedComponent, { - entity: { - request: { - exchange_url: 'http://exchange.taler/', - initial_balance: 'TESTKUDOS:1', - wire_method: 'x-taler-bank', - }, - response: { - payto_uri: 'payto://x-taler-bank/bank.taler:8080/exchange_account', - reserve_pub: 'WEQWDASDQWEASDADASDQWEQWEASDAS' - } - } -}); diff --git a/packages/merchant-backoffice-ui/src/paths/instance/reserves/create/CreatedSuccessfully.tsx b/packages/merchant-backoffice-ui/src/paths/instance/reserves/create/CreatedSuccessfully.tsx deleted file mode 100644 index 68ddc70b5..000000000 --- a/packages/merchant-backoffice-ui/src/paths/instance/reserves/create/CreatedSuccessfully.tsx +++ /dev/null @@ -1,79 +0,0 @@ -/* - This file is part of GNU Taler - (C) 2021 Taler Systems S.A. - - GNU Taler is free software; you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation; either version 3, or (at your option) any later version. - - GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License along with - GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> - */ - -import { h, VNode } from "preact"; -import { CreatedSuccessfully as Template } from "../../../../components/notifications/CreatedSuccessfully.js"; -import { MerchantBackend } from "../../../../declaration.js"; -import { Translate } from "../../../../i18n/index.js"; -import { QR } from "../../../../components/exception/QR.js"; - -type Entity = { request: MerchantBackend.Tips.ReserveCreateRequest, response: MerchantBackend.Tips.ReserveCreateConfirmation }; - -interface Props { - entity: Entity; - onConfirm: () => void; - onCreateAnother?: () => void; -} - -export function CreatedSuccessfully({ entity, onConfirm, onCreateAnother }: Props): VNode { - const link = `${entity.response.payto_uri}?message=${entity.response.reserve_pub}&amount=${entity.request.initial_balance}` - - return <Template onConfirm={onConfirm} onCreateAnother={onCreateAnother}> - <div class="field is-horizontal"> - <div class="field-label is-normal"> - <label class="label">Amount</label> - </div> - <div class="field-body is-flex-grow-3"> - <div class="field"> - <p class="control"> - <input readonly class="input" value={entity.request.initial_balance} /> - </p> - </div> - </div> - </div> - <div class="field is-horizontal"> - <div class="field-label is-normal"> - <label class="label">Exchange bank account</label> - </div> - <div class="field-body is-flex-grow-3"> - <div class="field"> - <p class="control"> - <input readonly class="input" value={entity.response.payto_uri} /> - </p> - </div> - </div> - </div> - <div class="field is-horizontal"> - <div class="field-label is-normal"> - <label class="label">Wire transfer subject</label> - </div> - <div class="field-body is-flex-grow-3"> - <div class="field"> - <p class="control"> - <input class="input" readonly value={entity.response.reserve_pub} /> - </p> - </div> - </div> - </div> - <p class="is-size-5"><Translate>To complete the setup of the reserve, you must now initiate a wire transfer using the given wire transfer subject and crediting the specified amount to the indicated account of the exchange.</Translate></p> - <p class="is-size-5"><Translate>If your system supports RFC 8905, you can do this by opening this URI:</Translate></p> - <pre> - <a target="_blank" rel="noreferrer" href={link}>{link}</a> - </pre> - <QR text={link} /> - </Template>; -} - diff --git a/packages/merchant-backoffice-ui/src/paths/instance/reserves/details/DetailPage.tsx b/packages/merchant-backoffice-ui/src/paths/instance/reserves/details/DetailPage.tsx deleted file mode 100644 index ad1089eb5..000000000 --- a/packages/merchant-backoffice-ui/src/paths/instance/reserves/details/DetailPage.tsx +++ /dev/null @@ -1,278 +0,0 @@ -/* - This file is part of GNU Taler - (C) 2021 Taler Systems S.A. - - GNU Taler is free software; you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation; either version 3, or (at your option) any later version. - - GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License along with - GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> - */ - -/** - * - * @author Sebastian Javier Marchano (sebasjm) - */ - -import { Amounts } from "@gnu-taler/taler-util"; -import { format } from "date-fns"; -import { Fragment, h, VNode } from "preact"; -import { useState } from "preact/hooks"; -import { QR } from "../../../../components/exception/QR.js"; -import { FormProvider } from "../../../../components/form/FormProvider.js"; -import { Input } from "../../../../components/form/Input.js"; -import { InputCurrency } from "../../../../components/form/InputCurrency.js"; -import { InputDate } from "../../../../components/form/InputDate.js"; -import { TextField } from "../../../../components/form/TextField.js"; -import { ContinueModal, SimpleModal } from "../../../../components/modal/index.js"; -import { MerchantBackend } from "../../../../declaration.js"; -import { useTipDetails } from "../../../../hooks/reserves.js"; -import { Translate, useTranslator } from "../../../../i18n/index.js"; -import { TipInfo } from "./TipInfo.js"; - -type Entity = MerchantBackend.Tips.ReserveDetail; -type CT = MerchantBackend.ContractTerms; - -interface Props { - onBack: () => void; - selected: Entity; - id: string; -} - -export function DetailPage({ id, selected, onBack }: Props): VNode { - const i18n = useTranslator(); - const didExchangeAckTransfer = Amounts.isNonZero( - Amounts.parseOrThrow(selected.exchange_initial_amount) - ); - const link = `${selected.payto_uri}?message=${id}&amount=${selected.merchant_initial_amount}`; - - return ( - <div class="columns"> - <div class="column" /> - <div class="column is-four-fifths"> - <div class="section main-section"> - <FormProvider object={{ ...selected, id }} valueHandler={null}> - <InputDate<Entity> - name="creation_time" - label={i18n`Created at`} - readonly - /> - <InputDate<Entity> - name="expiration_time" - label={i18n`Valid until`} - readonly - /> - <InputCurrency<Entity> - name="merchant_initial_amount" - label={i18n`Created balance`} - readonly - /> - <TextField<Entity> - name="exchange_url" - label={i18n`Exchange URL`} - readonly - > - <a target="_blank" rel="noreferrer" href={selected.exchange_url}> - {selected.exchange_url} - </a> - </TextField> - - {didExchangeAckTransfer && ( - <Fragment> - <InputCurrency<Entity> - name="exchange_initial_amount" - label={i18n`Exchange balance`} - readonly - /> - <InputCurrency<Entity> - name="pickup_amount" - label={i18n`Picked up`} - readonly - /> - <InputCurrency<Entity> - name="committed_amount" - label={i18n`Committed`} - readonly - /> - </Fragment> - )} - <Input<Entity> - name="payto_uri" - label={i18n`Account address`} - readonly - /> - <Input name="id" label={i18n`Subject`} readonly /> - </FormProvider> - - {didExchangeAckTransfer ? ( - <Fragment> - <div class="card has-table"> - <header class="card-header"> - <p class="card-header-title"> - <span class="icon"> - <i class="mdi mdi-cash-register" /> - </span> - <Translate>Tips</Translate> - </p> - </header> - <div class="card-content"> - <div class="b-table has-pagination"> - <div class="table-wrapper has-mobile-cards"> - {selected.tips && selected.tips.length > 0 ? ( - <Table tips={selected.tips} /> - ) : ( - <EmptyTable /> - )} - </div> - </div> - </div> - </div> - </Fragment> - ) : ( - <Fragment> - <p class="is-size-5"> - <Translate> - To complete the setup of the reserve, you must now initiate a - wire transfer using the given wire transfer subject and - crediting the specified amount to the indicated account of the - exchange. - </Translate> - </p> - <p class="is-size-5"> - <Translate> - If your system supports RFC 8905, you can do this by opening - this URI: - </Translate> - </p> - <pre> - <a target="_blank" rel="noreferrer" href={link}> - {link} - </a> - </pre> - <QR text={link} /> - </Fragment> - )} - - <div class="buttons is-right mt-5"> - <button class="button" onClick={onBack}> - <Translate>Back</Translate> - </button> - </div> - </div> - </div> - <div class="column" /> - </div> - ); -} - -function EmptyTable(): VNode { - return ( - <div class="content has-text-grey has-text-centered"> - <p> - <span class="icon is-large"> - <i class="mdi mdi-emoticon-sad mdi-48px" /> - </span> - </p> - <p> - <Translate>No tips has been authorized from this reserve</Translate> - </p> - </div> - ); -} - -interface TableProps { - tips: MerchantBackend.Tips.TipStatusEntry[]; -} - -function Table({ tips }: TableProps): VNode { - return ( - <div class="table-container"> - <table class="table is-fullwidth is-striped is-hoverable is-fullwidth"> - <thead> - <tr> - <th> - <Translate>Authorized</Translate> - </th> - <th> - <Translate>Picked up</Translate> - </th> - <th> - <Translate>Reason</Translate> - </th> - <th> - <Translate>Expiration</Translate> - </th> - </tr> - </thead> - <tbody> - {tips.map((t, i) => { - return <TipRow id={t.tip_id} key={i} entry={t} />; - })} - </tbody> - </table> - </div> - ); -} - -function TipRow({ - id, - entry, -}: { - id: string; - entry: MerchantBackend.Tips.TipStatusEntry; -}) { - const [selected, setSelected] = useState(false); - const result = useTipDetails(id); - if (result.loading) { - return ( - <tr> - <td>...</td> - <td>...</td> - <td>...</td> - <td>...</td> - </tr> - ); - } - if (!result.ok) { - return ( - <tr> - <td>...</td> {/* authorized */} - <td>{entry.total_amount}</td> - <td>{entry.reason}</td> - <td>...</td> {/* expired */} - </tr> - ); - } - const info = result.data; - function onSelect() { - setSelected(true); - } - return ( - <Fragment> - {selected && ( - <SimpleModal - description="tip" - active - onCancel={() => setSelected(false)} - > - <TipInfo id={id} amount={info.total_authorized} entity={info} /> - </SimpleModal> - )} - <tr> - <td onClick={onSelect}>{info.total_authorized}</td> - <td onClick={onSelect}>{info.total_picked_up}</td> - <td onClick={onSelect}>{info.reason}</td> - <td onClick={onSelect}> - {info.expiration.t_s === "never" - ? "never" - : format(info.expiration.t_s * 1000, "yyyy/MM/dd HH:mm:ss")} - </td> - </tr> - </Fragment> - ); -} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/reserves/details/Details.stories.tsx b/packages/merchant-backoffice-ui/src/paths/instance/reserves/details/Details.stories.tsx deleted file mode 100644 index 48a12f02a..000000000 --- a/packages/merchant-backoffice-ui/src/paths/instance/reserves/details/Details.stories.tsx +++ /dev/null @@ -1,105 +0,0 @@ -/* - This file is part of GNU Taler - (C) 2021 Taler Systems S.A. - - GNU Taler is free software; you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation; either version 3, or (at your option) any later version. - - GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License along with - GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> - */ - -/** - * - * @author Sebastian Javier Marchano (sebasjm) - */ - -import { h, VNode, FunctionalComponent } from "preact"; -import { DetailPage as TestedComponent } from "./DetailPage.js"; - -export default { - title: "Pages/Reserve/Detail", - component: TestedComponent, - argTypes: { - onUpdate: { action: "onUpdate" }, - onBack: { action: "onBack" }, - }, -}; - -function createExample<Props>( - Component: FunctionalComponent<Props>, - props: Partial<Props> -) { - const r = (args: any) => <Component {...args} />; - r.args = props; - return r; -} - -export const Funded = createExample(TestedComponent, { - id: "THISISTHERESERVEID", - selected: { - active: true, - committed_amount: "TESTKUDOS:10", - creation_time: { - t_s: new Date().getTime() / 1000, - }, - exchange_initial_amount: "TESTKUDOS:10", - expiration_time: { - t_s: new Date().getTime() / 1000, - }, - merchant_initial_amount: "TESTKUDOS:10", - pickup_amount: "TESTKUDOS:10", - payto_uri: "payto://x-taler-bank/bank.taler:8080/account", - exchange_url: "http://exchange.taler/", - }, -}); - -export const NotYetFunded = createExample(TestedComponent, { - id: "THISISTHERESERVEID", - selected: { - active: true, - committed_amount: "TESTKUDOS:10", - creation_time: { - t_s: new Date().getTime() / 1000, - }, - exchange_initial_amount: "TESTKUDOS:0", - expiration_time: { - t_s: new Date().getTime() / 1000, - }, - merchant_initial_amount: "TESTKUDOS:10", - pickup_amount: "TESTKUDOS:10", - payto_uri: "payto://x-taler-bank/bank.taler:8080/account", - exchange_url: "http://exchange.taler/", - }, -}); - -export const FundedWithEmptyTips = createExample(TestedComponent, { - id: "THISISTHERESERVEID", - selected: { - active: true, - committed_amount: "TESTKUDOS:10", - creation_time: { - t_s: new Date().getTime() / 1000, - }, - exchange_initial_amount: "TESTKUDOS:10", - expiration_time: { - t_s: new Date().getTime() / 1000, - }, - merchant_initial_amount: "TESTKUDOS:10", - pickup_amount: "TESTKUDOS:10", - payto_uri: "payto://x-taler-bank/bank.taler:8080/account", - exchange_url: "http://exchange.taler/", - tips: [ - { - reason: "asdasd", - tip_id: "123", - total_amount: "TESTKUDOS:1", - }, - ], - }, -}); diff --git a/packages/merchant-backoffice-ui/src/paths/instance/reserves/details/TipInfo.tsx b/packages/merchant-backoffice-ui/src/paths/instance/reserves/details/TipInfo.tsx deleted file mode 100644 index 02bc6f6df..000000000 --- a/packages/merchant-backoffice-ui/src/paths/instance/reserves/details/TipInfo.tsx +++ /dev/null @@ -1,87 +0,0 @@ -/* - This file is part of GNU Taler - (C) 2021 Taler Systems S.A. - - GNU Taler is free software; you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation; either version 3, or (at your option) any later version. - - GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License along with - GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> - */ -import { format } from "date-fns"; -import { Fragment, h, VNode } from "preact"; -import { useBackendContext } from "../../../../context/backend.js"; -import { MerchantBackend } from "../../../../declaration.js"; - -type Entity = MerchantBackend.Tips.TipDetails; - -interface Props { - id: string; - entity: Entity; - amount: string; -} - -export function TipInfo({ id, amount, entity }: Props): VNode { - const { url } = useBackendContext(); - const tipHost = url.replace(/.*:\/\//, ""); // remove protocol part - const proto = url.startsWith("http://") ? "taler+http" : "taler"; - const tipURL = `${proto}://tip/${tipHost}/${id}`; - return ( - <Fragment> - <div class="field is-horizontal"> - <div class="field-label is-normal"> - <label class="label">Amount</label> - </div> - <div class="field-body is-flex-grow-3"> - <div class="field"> - <p class="control"> - <input readonly class="input" value={amount} /> - </p> - </div> - </div> - </div> - <div class="field is-horizontal"> - <div class="field-label is-normal"> - <label class="label">URL</label> - </div> - <div class="field-body is-flex-grow-3"> - <div class="field" style={{ overflowWrap: "anywhere" }}> - <p class="control"> - <a target="_blank" rel="noreferrer" href={tipURL}> - {tipURL} - </a> - </p> - </div> - </div> - </div> - <div class="field is-horizontal"> - <div class="field-label is-normal"> - <label class="label">Valid until</label> - </div> - <div class="field-body is-flex-grow-3"> - <div class="field"> - <p class="control"> - <input - class="input" - readonly - value={ - !entity.expiration || entity.expiration.t_s === "never" - ? "never" - : format( - entity.expiration.t_s * 1000, - "yyyy/MM/dd HH:mm:ss" - ) - } - /> - </p> - </div> - </div> - </div> - </Fragment> - ); -} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/reserves/details/index.tsx b/packages/merchant-backoffice-ui/src/paths/instance/reserves/details/index.tsx deleted file mode 100644 index 882c2adac..000000000 --- a/packages/merchant-backoffice-ui/src/paths/instance/reserves/details/index.tsx +++ /dev/null @@ -1,56 +0,0 @@ -/* - This file is part of GNU Taler - (C) 2021 Taler Systems S.A. - - GNU Taler is free software; you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation; either version 3, or (at your option) any later version. - - GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License along with - GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> - */ - -/** - * - * @author Sebastian Javier Marchano (sebasjm) - */ - -import { Fragment, h, VNode } from "preact"; -import { Loading } from "../../../../components/exception/loading.js"; -import { HttpError } from "../../../../hooks/backend.js"; -import { useReserveDetails } from "../../../../hooks/reserves.js"; -import { DetailPage } from "./DetailPage.js"; - -interface Props { - rid: string; - - onUnauthorized: () => VNode; - onLoadError: (error: HttpError) => VNode; - onNotFound: () => VNode; - onDelete: () => void; - onBack: () => void; -} -export default function DetailReserve({ - rid, - onUnauthorized, - onLoadError, - onNotFound, - onBack, - onDelete, -}: Props): VNode { - const result = useReserveDetails(rid); - - if (result.clientError && result.isUnauthorized) return onUnauthorized(); - if (result.clientError && result.isNotfound) return onNotFound(); - if (result.loading) return <Loading />; - if (!result.ok) return onLoadError(result); - return ( - <Fragment> - <DetailPage selected={result.data} onBack={onBack} id={rid} /> - </Fragment> - ); -} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/reserves/list/AutorizeTipModal.tsx b/packages/merchant-backoffice-ui/src/paths/instance/reserves/list/AutorizeTipModal.tsx deleted file mode 100644 index e72bfa1f7..000000000 --- a/packages/merchant-backoffice-ui/src/paths/instance/reserves/list/AutorizeTipModal.tsx +++ /dev/null @@ -1,85 +0,0 @@ -/* - This file is part of GNU Taler - (C) 2021 Taler Systems S.A. - - GNU Taler is free software; you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation; either version 3, or (at your option) any later version. - - GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License along with - GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> - */ - -/** -* -* @author Sebastian Javier Marchano (sebasjm) -*/ - -import { h, VNode } from "preact"; -import { useState } from "preact/hooks"; -import { FormErrors, FormProvider } from "../../../../components/form/FormProvider.js"; -import { Input } from "../../../../components/form/Input.js"; -import { InputCurrency } from "../../../../components/form/InputCurrency.js"; -import { ConfirmModal, ContinueModal } from "../../../../components/modal/index.js"; -import { MerchantBackend } from "../../../../declaration.js"; -import { useTranslator } from "../../../../i18n/index.js"; -import { AuthorizeTipSchema } from "../../../../schemas/index.js"; -import { CreatedSuccessfully } from "./CreatedSuccessfully.js"; -import * as yup from 'yup'; - -interface AuthorizeTipModalProps { - onCancel: () => void; - onConfirm: (value: MerchantBackend.Tips.TipCreateRequest) => void; - tipAuthorized?: { - response: MerchantBackend.Tips.TipCreateConfirmation; - request: MerchantBackend.Tips.TipCreateRequest; - }; -} - -export function AuthorizeTipModal({ onCancel, onConfirm, tipAuthorized }: AuthorizeTipModalProps): VNode { - // const result = useOrderDetails(id) - type State = MerchantBackend.Tips.TipCreateRequest - const [form, setValue] = useState<Partial<State>>({}) - const i18n = useTranslator(); - - // const [errors, setErrors] = useState<FormErrors<State>>({}) - let errors: FormErrors<State> = {} - try { - AuthorizeTipSchema.validateSync(form, { abortEarly: false }) - } catch (err) { - if (err instanceof yup.ValidationError) { - const yupErrors = err.inner as any[] - errors = yupErrors.reduce((prev, cur) => !cur.path ? prev : ({ ...prev, [cur.path]: cur.message }), {}) - } - } - const hasErrors = Object.keys(errors).some(k => (errors as any)[k] !== undefined) - - const validateAndConfirm = () => { - onConfirm(form as State) - } - if (tipAuthorized) { - return <ContinueModal description="tip" active onConfirm={onCancel}> - <CreatedSuccessfully - entity={tipAuthorized.response} - request={tipAuthorized.request} - onConfirm={onCancel} - /> - </ContinueModal> - } - - return <ConfirmModal description="tip" active onCancel={onCancel} disabled={hasErrors} onConfirm={validateAndConfirm}> - - <FormProvider<State> errors={errors} object={form} valueHandler={setValue} > - <InputCurrency<State> name="amount" label={i18n`Amount`} tooltip={i18n`amount of tip`} /> - <Input<State> name="justification" label={i18n`Justification`} inputType="multiline" tooltip={i18n`reason for the tip`} /> - <Input<State> name="next_url" label={i18n`URL after tip`} tooltip={i18n`URL to visit after tip payment`} /> - </FormProvider> - - </ConfirmModal> -} - - diff --git a/packages/merchant-backoffice-ui/src/paths/instance/reserves/list/CreatedSuccessfully.tsx b/packages/merchant-backoffice-ui/src/paths/instance/reserves/list/CreatedSuccessfully.tsx deleted file mode 100644 index 92a21bfd1..000000000 --- a/packages/merchant-backoffice-ui/src/paths/instance/reserves/list/CreatedSuccessfully.tsx +++ /dev/null @@ -1,100 +0,0 @@ -/* - This file is part of GNU Taler - (C) 2021 Taler Systems S.A. - - GNU Taler is free software; you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation; either version 3, or (at your option) any later version. - - GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License along with - GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> - */ -import { format } from "date-fns"; -import { Fragment, h, VNode } from "preact"; -import { CreatedSuccessfully as Template } from "../../../../components/notifications/CreatedSuccessfully.js"; -import { MerchantBackend } from "../../../../declaration.js"; - -type Entity = MerchantBackend.Tips.TipCreateConfirmation; - -interface Props { - entity: Entity; - request: MerchantBackend.Tips.TipCreateRequest; - onConfirm: () => void; - onCreateAnother?: () => void; -} - -export function CreatedSuccessfully({ - request, - entity, - onConfirm, - onCreateAnother, -}: Props): VNode { - return ( - <Fragment> - <div class="field is-horizontal"> - <div class="field-label is-normal"> - <label class="label">Amount</label> - </div> - <div class="field-body is-flex-grow-3"> - <div class="field"> - <p class="control"> - <input readonly class="input" value={request.amount} /> - </p> - </div> - </div> - </div> - <div class="field is-horizontal"> - <div class="field-label is-normal"> - <label class="label">Justification</label> - </div> - <div class="field-body is-flex-grow-3"> - <div class="field"> - <p class="control"> - <input readonly class="input" value={request.justification} /> - </p> - </div> - </div> - </div> - <div class="field is-horizontal"> - <div class="field-label is-normal"> - <label class="label">URL</label> - </div> - <div class="field-body is-flex-grow-3"> - <div class="field"> - <p class="control"> - <input readonly class="input" value={entity.tip_status_url} /> - </p> - </div> - </div> - </div> - <div class="field is-horizontal"> - <div class="field-label is-normal"> - <label class="label">Valid until</label> - </div> - <div class="field-body is-flex-grow-3"> - <div class="field"> - <p class="control"> - <input - class="input" - readonly - value={ - !entity.tip_expiration || - entity.tip_expiration.t_s === "never" - ? "never" - : format( - entity.tip_expiration.t_s * 1000, - "yyyy/MM/dd HH:mm:ss" - ) - } - /> - </p> - </div> - </div> - </div> - </Fragment> - ); -} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/reserves/list/List.stories.tsx b/packages/merchant-backoffice-ui/src/paths/instance/reserves/list/List.stories.tsx deleted file mode 100644 index 7a4e9ff42..000000000 --- a/packages/merchant-backoffice-ui/src/paths/instance/reserves/list/List.stories.tsx +++ /dev/null @@ -1,102 +0,0 @@ -/* - This file is part of GNU Taler - (C) 2021 Taler Systems S.A. - - GNU Taler is free software; you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation; either version 3, or (at your option) any later version. - - GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License along with - GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> - */ - -/** - * - * @author Sebastian Javier Marchano (sebasjm) - */ - -import { h, VNode, FunctionalComponent } from "preact"; -import { CardTable as TestedComponent } from "./Table.js"; - -export default { - title: "Pages/Reserve/List", - component: TestedComponent, - argTypes: { - onCreate: { action: "onCreate" }, - onDelete: { action: "onDelete" }, - onNewTip: { action: "onNewTip" }, - onSelect: { action: "onSelect" }, - }, -}; - -function createExample<Props>( - Component: FunctionalComponent<Props>, - props: Partial<Props> -) { - const r = (args: any) => <Component {...args} />; - r.args = props; - return r; -} - -export const AllFunded = createExample(TestedComponent, { - instances: [ - { - id: "reseverId", - active: true, - committed_amount: "TESTKUDOS:10", - creation_time: { - t_s: new Date().getTime() / 1000, - }, - exchange_initial_amount: "TESTKUDOS:10", - expiration_time: { - t_s: new Date().getTime() / 1000, - }, - merchant_initial_amount: "TESTKUDOS:10", - pickup_amount: "TESTKUDOS:10", - reserve_pub: "WEQWDASDQWEASDADASDQWEQWEASDAS", - }, - { - id: "reseverId2", - active: true, - committed_amount: "TESTKUDOS:13", - creation_time: { - t_s: new Date().getTime() / 1000, - }, - exchange_initial_amount: "TESTKUDOS:10", - expiration_time: { - t_s: new Date().getTime() / 1000, - }, - merchant_initial_amount: "TESTKUDOS:10", - pickup_amount: "TESTKUDOS:10", - reserve_pub: "WEQWDASDQWEASDADASDQWEQWEASDAS", - }, - ], -}); - -export const Empty = createExample(TestedComponent, { - instances: [], -}); - -export const OneNotYetFunded = createExample(TestedComponent, { - instances: [ - { - id: "reseverId", - active: true, - committed_amount: "TESTKUDOS:0", - creation_time: { - t_s: new Date().getTime() / 1000, - }, - exchange_initial_amount: "TESTKUDOS:0", - expiration_time: { - t_s: new Date().getTime() / 1000, - }, - merchant_initial_amount: "TESTKUDOS:10", - pickup_amount: "TESTKUDOS:10", - reserve_pub: "WEQWDASDQWEASDADASDQWEQWEASDAS", - }, - ], -}); diff --git a/packages/merchant-backoffice-ui/src/paths/instance/reserves/list/Table.tsx b/packages/merchant-backoffice-ui/src/paths/instance/reserves/list/Table.tsx deleted file mode 100644 index 0d094d9aa..000000000 --- a/packages/merchant-backoffice-ui/src/paths/instance/reserves/list/Table.tsx +++ /dev/null @@ -1,313 +0,0 @@ -/* - This file is part of GNU Taler - (C) 2021 Taler Systems S.A. - - GNU Taler is free software; you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation; either version 3, or (at your option) any later version. - - GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License along with - GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> - */ - -/** - * - * @author Sebastian Javier Marchano (sebasjm) - */ - -import { format } from "date-fns"; -import { Fragment, h, VNode } from "preact"; -import { MerchantBackend, WithId } from "../../../../declaration.js"; -import { Translate, useTranslator } from "../../../../i18n/index.js"; - -type Entity = MerchantBackend.Tips.ReserveStatusEntry & WithId; - -interface Props { - instances: Entity[]; - onNewTip: (id: Entity) => void; - onSelect: (id: Entity) => void; - onDelete: (id: Entity) => void; - onCreate: () => void; -} - -export function CardTable({ - instances, - onCreate, - onSelect, - onNewTip, - onDelete, -}: Props): VNode { - const [withoutFunds, withFunds] = instances.reduce((prev, current) => { - const amount = current.exchange_initial_amount; - if (amount.endsWith(":0")) { - prev[0] = prev[0].concat(current); - } else { - prev[1] = prev[1].concat(current); - } - return prev; - }, new Array<Array<Entity>>([], [])); - - const i18n = useTranslator(); - - return ( - <Fragment> - {withoutFunds.length > 0 && ( - <div class="card has-table"> - <header class="card-header"> - <p class="card-header-title"> - <span class="icon"> - <i class="mdi mdi-cash" /> - </span> - <Translate>Reserves not yet funded</Translate> - </p> - </header> - <div class="card-content"> - <div class="b-table has-pagination"> - <div class="table-wrapper has-mobile-cards"> - <TableWithoutFund - instances={withoutFunds} - onNewTip={onNewTip} - onSelect={onSelect} - onDelete={onDelete} - /> - </div> - </div> - </div> - </div> - )} - - <div class="card has-table"> - <header class="card-header"> - <p class="card-header-title"> - <span class="icon"> - <i class="mdi mdi-cash" /> - </span> - <Translate>Reserves ready</Translate> - </p> - <div class="card-header-icon" aria-label="more options" /> - <div class="card-header-icon" aria-label="more options"> - <span class="has-tooltip-left" data-tooltip={i18n`add new reserve`}> - <button class="button is-info" type="button" onClick={onCreate}> - <span class="icon is-small"> - <i class="mdi mdi-plus mdi-36px" /> - </span> - </button> - </span> - </div> - </header> - <div class="card-content"> - <div class="b-table has-pagination"> - <div class="table-wrapper has-mobile-cards"> - {withFunds.length > 0 ? ( - <Table - instances={withFunds} - onNewTip={onNewTip} - onSelect={onSelect} - onDelete={onDelete} - /> - ) : ( - <EmptyTable /> - )} - </div> - </div> - </div> - </div> - </Fragment> - ); -} -interface TableProps { - instances: Entity[]; - onNewTip: (id: Entity) => void; - onDelete: (id: Entity) => void; - onSelect: (id: Entity) => void; -} - -function Table({ instances, onNewTip, onSelect, onDelete }: TableProps): VNode { - const i18n = useTranslator(); - return ( - <div class="table-container"> - <table class="table is-fullwidth is-striped is-hoverable is-fullwidth"> - <thead> - <tr> - <th> - <Translate>Created at</Translate> - </th> - <th> - <Translate>Expires at</Translate> - </th> - <th> - <Translate>Initial</Translate> - </th> - <th> - <Translate>Picked up</Translate> - </th> - <th> - <Translate>Committed</Translate> - </th> - <th /> - </tr> - </thead> - <tbody> - {instances.map((i) => { - return ( - <tr key={i.id}> - <td - onClick={(): void => onSelect(i)} - style={{ cursor: "pointer" }} - > - {i.creation_time.t_s === "never" - ? "never" - : format(i.creation_time.t_s * 1000, "yyyy/MM/dd HH:mm:ss")} - </td> - <td - onClick={(): void => onSelect(i)} - style={{ cursor: "pointer" }} - > - {i.expiration_time.t_s === "never" - ? "never" - : format( - i.expiration_time.t_s * 1000, - "yyyy/MM/dd HH:mm:ss" - )} - </td> - <td - onClick={(): void => onSelect(i)} - style={{ cursor: "pointer" }} - > - {i.exchange_initial_amount} - </td> - <td - onClick={(): void => onSelect(i)} - style={{ cursor: "pointer" }} - > - {i.pickup_amount} - </td> - <td - onClick={(): void => onSelect(i)} - style={{ cursor: "pointer" }} - > - {i.committed_amount} - </td> - <td class="is-actions-cell right-sticky"> - <div class="buttons is-right"> - <button - class="button is-small is-danger has-tooltip-left" - data-tooltip={i18n`delete selected reserve from the database`} - type="button" - onClick={(): void => onDelete(i)} - > - Delete - </button> - <button - class="button is-small is-info has-tooltip-left" - data-tooltip={i18n`authorize new tip from selected reserve`} - type="button" - onClick={(): void => onNewTip(i)} - > - New Tip - </button> - </div> - </td> - </tr> - ); - })} - </tbody> - </table> - </div> - ); -} - -function EmptyTable(): VNode { - return ( - <div class="content has-text-grey has-text-centered"> - <p> - <span class="icon is-large"> - <i class="mdi mdi-emoticon-sad mdi-48px" /> - </span> - </p> - <p> - <Translate> - There is no ready reserves yet, add more pressing the + sign or fund - them - </Translate> - </p> - </div> - ); -} - -function TableWithoutFund({ - instances, - onSelect, - onDelete, -}: TableProps): VNode { - const i18n = useTranslator(); - return ( - <div class="table-container"> - <table class="table is-fullwidth is-striped is-hoverable is-fullwidth"> - <thead> - <tr> - <th> - <Translate>Created at</Translate> - </th> - <th> - <Translate>Expires at</Translate> - </th> - <th> - <Translate>Expected Balance</Translate> - </th> - <th /> - </tr> - </thead> - <tbody> - {instances.map((i) => { - return ( - <tr key={i.id}> - <td - onClick={(): void => onSelect(i)} - style={{ cursor: "pointer" }} - > - {i.creation_time.t_s === "never" - ? "never" - : format(i.creation_time.t_s * 1000, "yyyy/MM/dd HH:mm:ss")} - </td> - <td - onClick={(): void => onSelect(i)} - style={{ cursor: "pointer" }} - > - {i.expiration_time.t_s === "never" - ? "never" - : format( - i.expiration_time.t_s * 1000, - "yyyy/MM/dd HH:mm:ss" - )} - </td> - <td - onClick={(): void => onSelect(i)} - style={{ cursor: "pointer" }} - > - {i.merchant_initial_amount} - </td> - <td class="is-actions-cell right-sticky"> - <div class="buttons is-right"> - <button - class="button is-small is-danger jb-modal has-tooltip-left" - type="button" - data-tooltip={i18n`delete selected reserve from the database`} - onClick={(): void => onDelete(i)} - > - Delete - </button> - </div> - </td> - </tr> - ); - })} - </tbody> - </table> - </div> - ); -} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/reserves/list/index.tsx b/packages/merchant-backoffice-ui/src/paths/instance/reserves/list/index.tsx deleted file mode 100644 index 9d0b4054d..000000000 --- a/packages/merchant-backoffice-ui/src/paths/instance/reserves/list/index.tsx +++ /dev/null @@ -1,117 +0,0 @@ -/* - This file is part of GNU Taler - (C) 2021 Taler Systems S.A. - - GNU Taler is free software; you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation; either version 3, or (at your option) any later version. - - GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License along with - GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> - */ - -/** - * - * @author Sebastian Javier Marchano (sebasjm) - */ - -import { h, VNode } from "preact"; -import { useState } from "preact/hooks"; -import { Loading } from "../../../../components/exception/loading.js"; -import { NotificationCard } from "../../../../components/menu/index.js"; -import { MerchantBackend } from "../../../../declaration.js"; -import { HttpError } from "../../../../hooks/backend.js"; -import { - useInstanceReserves, - useReservesAPI, -} from "../../../../hooks/reserves.js"; -import { useTranslator } from "../../../../i18n/index.js"; -import { Notification } from "../../../../utils/types.js"; -import { CardTable } from "./Table.js"; -import { AuthorizeTipModal } from "./AutorizeTipModal.js"; - -interface Props { - onUnauthorized: () => VNode; - onLoadError: (e: HttpError) => VNode; - onSelect: (id: string) => void; - onNotFound: () => VNode; - onCreate: () => void; -} - -interface TipConfirmation { - response: MerchantBackend.Tips.TipCreateConfirmation; - request: MerchantBackend.Tips.TipCreateRequest; -} - -export default function ListTips({ - onUnauthorized, - onLoadError, - onNotFound, - onSelect, - onCreate, -}: Props): VNode { - const result = useInstanceReserves(); - const { deleteReserve, authorizeTipReserve } = useReservesAPI(); - const [notif, setNotif] = useState<Notification | undefined>(undefined); - const i18n = useTranslator(); - const [reserveForTip, setReserveForTip] = useState<string | undefined>( - undefined - ); - const [tipAuthorized, setTipAuthorized] = useState< - TipConfirmation | undefined - >(undefined); - - if (result.clientError && result.isUnauthorized) return onUnauthorized(); - if (result.clientError && result.isNotfound) return onNotFound(); - if (result.loading) return <Loading />; - if (!result.ok) return onLoadError(result); - - return ( - <section class="section is-main-section"> - <NotificationCard notification={notif} /> - - {reserveForTip && ( - <AuthorizeTipModal - onCancel={() => { - setReserveForTip(undefined); - setTipAuthorized(undefined); - }} - tipAuthorized={tipAuthorized} - onConfirm={async (request) => { - try { - const response = await authorizeTipReserve( - reserveForTip, - request - ); - setTipAuthorized({ - request, - response: response.data, - }); - } catch (error) { - setNotif({ - message: i18n`could not create the tip`, - type: "ERROR", - description: error instanceof Error ? error.message : undefined, - }); - setReserveForTip(undefined); - } - }} - /> - )} - - <CardTable - instances={result.data.reserves - .filter((r) => r.active) - .map((o) => ({ ...o, id: o.reserve_pub }))} - onCreate={onCreate} - onDelete={(reserve) => deleteReserve(reserve.reserve_pub)} - onSelect={(reserve) => onSelect(reserve.id)} - onNewTip={(reserve) => setReserveForTip(reserve.id)} - /> - </section> - ); -} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/templates/create/Create.stories.tsx b/packages/merchant-backoffice-ui/src/paths/instance/templates/create/Create.stories.tsx new file mode 100644 index 000000000..53025f153 --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/templates/create/Create.stories.tsx @@ -0,0 +1,28 @@ +/* + This file is part of GNU Taler + (C) 2021-2024 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +/** + * + * @author Sebastian Javier Marchano (sebasjm) + */ + +import { h, VNode, FunctionalComponent } from "preact"; +import { CreatePage as TestedComponent } from "./CreatePage.js"; + +export default { + title: "Pages/Templates/Create", + component: TestedComponent, +}; diff --git a/packages/merchant-backoffice-ui/src/paths/instance/templates/create/CreatePage.tsx b/packages/merchant-backoffice-ui/src/paths/instance/templates/create/CreatePage.tsx new file mode 100644 index 000000000..50262be17 --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/templates/create/CreatePage.tsx @@ -0,0 +1,298 @@ +/* + This file is part of GNU Taler + (C) 2021-2024 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +/** + * + * @author Sebastian Javier Marchano (sebasjm) + */ + +import { + AmountString, + Amounts, + Duration, + TalerError, + TalerMerchantApi, + TranslatedString, +} from "@gnu-taler/taler-util"; +import { + useTranslationContext +} from "@gnu-taler/web-util/browser"; +import { Fragment, VNode, h } from "preact"; +import { useState } from "preact/hooks"; +import { AsyncButton } from "../../../../components/exception/AsyncButton.js"; +import { + FormErrors, + FormProvider, +} from "../../../../components/form/FormProvider.js"; +import { Input } from "../../../../components/form/Input.js"; +import { InputCurrency } from "../../../../components/form/InputCurrency.js"; +import { InputDuration } from "../../../../components/form/InputDuration.js"; +import { InputNumber } from "../../../../components/form/InputNumber.js"; +import { InputSelector } from "../../../../components/form/InputSelector.js"; +import { InputToggle } from "../../../../components/form/InputToggle.js"; +import { InputWithAddon } from "../../../../components/form/InputWithAddon.js"; +import { TextField } from "../../../../components/form/TextField.js"; +import { useSessionContext } from "../../../../context/session.js"; +import { useInstanceOtpDevices } from "../../../../hooks/otp.js"; + +// type Entity = TalerMerchantApi.TemplateAddDetails & { type: Steps }; +type Entity = { + id?: string; + description?: string; + otpId?: string; + summary?: string; + amount?: AmountString; + minimum_age?: number; + pay_duration?: Duration; + summary_editable?: boolean; + amount_editable?: boolean; + currency_editable?: boolean; +}; + +interface Props { + onCreate: (d: TalerMerchantApi.TemplateAddDetails) => Promise<void>; + onBack?: () => void; +} + +export function CreatePage({ onCreate, onBack }: Props): VNode { + const { i18n } = useTranslationContext(); + const { config } = useSessionContext(); + const { state: session } = useSessionContext(); + const devices = useInstanceOtpDevices(); + + const [state, setState] = useState<Partial<Entity>>({ + minimum_age: 0, + pay_duration: { + d_ms: 1000 * 60 * 30, //30 min + }, + }); + + function updateState(up: (s: Partial<Entity>) => Partial<Entity>) { + setState((old) => { + const newState = up(old); + if (!newState.amount_editable) { + newState.currency_editable = false; + } + return newState; + }); + } + + const parsedPrice = !state.amount ? undefined : Amounts.parse(state.amount); + + const errors: FormErrors<Entity> = { + id: !state.id + ? i18n.str`should not be empty` + : !/[a-zA-Z0-9]*/.test(state.id) + ? i18n.str`no valid. only characters and numbers` + : undefined, + description: !state.description ? i18n.str`should not be empty` : undefined, + amount: !state.amount + ? state.amount_editable ? undefined : i18n.str`required` + : !parsedPrice + ? i18n.str`not valid` + : Amounts.isZero(parsedPrice) + ? state.amount_editable ? undefined : i18n.str`must be greater than 0` + : undefined, + minimum_age: + state.minimum_age && state.minimum_age < 0 + ? i18n.str`should be greater that 0` + : undefined, + pay_duration: !state.pay_duration + ? i18n.str`can't be empty` + : state.pay_duration.d_ms === "forever" + ? undefined + : state.pay_duration.d_ms < 1000 //less than one second + ? i18n.str`to short` + : undefined, + }; + + const cList = Object.values(config.currencies).map((d) => d.name); + + const hasErrors = Object.keys(errors).some( + (k) => (errors as Record<string, unknown>)[k] !== undefined, + ); + + const zero = Amounts.stringify(Amounts.zeroOfCurrency(config.currency)) + + const submitForm = () => { + if (hasErrors) return Promise.reject(); + const contract_amount = state.amount_editable ? undefined : state.amount as AmountString + const contract_summary = state.summary_editable ? undefined : state.summary + const template_contract: TalerMerchantApi.TemplateContractDetails = { + minimum_age: state.minimum_age!, + pay_duration: Duration.toTalerProtocolDuration(state.pay_duration!), + amount: contract_amount, + summary: contract_summary, + currency: + cList.length > 1 && state.currency_editable + ? undefined + : config.currency, + } + return onCreate({ + template_id: state.id!, + template_description: state.description!, + template_contract, + required_currency: contract_amount !== undefined ? undefined : config.currency, + editable_defaults: { + amount: !state.amount_editable ? undefined : (state.amount ?? zero), + summary: !state.summary_editable ? undefined : (state.summary ?? ""), + currency: + cList.length === 1 || !state.currency_editable + ? undefined + : config.currency, + }, + otp_id: state.otpId!, + }); + }; + const deviceList = + !devices || devices instanceof TalerError || devices.type === "fail" + ? [] + : devices.body.otp_devices; + const deviceMap = deviceList.reduce( + (prev, cur) => { + prev[cur.otp_device_id] = cur.device_description as TranslatedString; + return prev; + }, + {} as Record<string, TranslatedString>, + ); + return ( + <div> + <section class="section is-main-section"> + <div class="columns"> + <div class="column" /> + <div class="column is-four-fifths"> + <FormProvider + object={state} + valueHandler={updateState} + errors={errors} + > + <InputWithAddon<Entity> + name="id" + help={ + new URL(`templates/${state.id ?? ""}`, session.backendUrl.href).href + } + label={i18n.str`Identifier`} + tooltip={i18n.str`Name of the template in URLs.`} + /> + <Input<Entity> + name="description" + label={i18n.str`Description`} + help="" + tooltip={i18n.str`Describe what this template stands for`} + /> + + <Input<Entity> + name="summary" + inputType="multiline" + label={i18n.str`Summary`} + tooltip={i18n.str`If specified, this template will create order with the same summary`} + /> + <InputToggle<Entity> + name="summary_editable" + label={i18n.str`Summary is editable`} + tooltip={i18n.str`Allow the user to change the summary.`} + /> + + <InputCurrency<Entity> + name="amount" + label={i18n.str`Amount`} + tooltip={i18n.str`If specified, this template will create order with the same price`} + /> + <InputToggle<Entity> + name="amount_editable" + label={i18n.str`Amount is editable`} + tooltip={i18n.str`Allow the user to select the amount to pay.`} + /> + {cList.length > 1 && ( + <Fragment> + <InputToggle<Entity> + name="currency_editable" + readonly={!state.amount_editable} + label={i18n.str`Currency is editable`} + tooltip={i18n.str`Allow the user to change currency.`} + /> + <TextField name="sc" label={i18n.str`Supported currencies`}> + <i18n.Translate>supported currencies: {cList.join(", ")}</i18n.Translate> + </TextField> + </Fragment> + )} + <InputNumber<Entity> + name="minimum_age" + label={i18n.str`Minimum age`} + help="" + tooltip={i18n.str`Is this contract restricted to some age?`} + /> + <InputDuration<Entity> + name="pay_duration" + label={i18n.str`Payment timeout`} + help="" + tooltip={i18n.str`How much time has the customer to complete the payment once the order was created.`} + /> + {!deviceList.length ? ( + <TextField + name="otpId" + label={i18n.str`OTP device`} + tooltip={i18n.str`Use to verify transaction while offline.`} + > + <i18n.Translate>No OTP device.</i18n.Translate> + <a href="/otp-devices/new"> + <i18n.Translate>Add one first</i18n.Translate> + </a> + </TextField> + ) : ( + <InputSelector<Entity> + name="otpId" + label={i18n.str`OTP device`} + values={[ + undefined, + ...deviceList.map((e) => e.otp_device_id), + ]} + toStr={(v?: string) => { + if (!v) { + return i18n.str`No device`; + } + return deviceMap[v]; + }} + tooltip={i18n.str`Use to verify transaction in offline mode.`} + /> + )} + </FormProvider> + + <div class="buttons is-right mt-5"> + {onBack && ( + <button class="button" onClick={onBack}> + <i18n.Translate>Cancel</i18n.Translate> + </button> + )} + <AsyncButton + disabled={hasErrors} + data-tooltip={ + hasErrors + ? i18n.str`Need to complete marked fields` + : "confirm operation" + } + onClick={submitForm} + > + <i18n.Translate>Confirm</i18n.Translate> + </AsyncButton> + </div> + </div> + <div class="column" /> + </div> + </section> + </div> + ); +} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/templates/create/index.tsx b/packages/merchant-backoffice-ui/src/paths/instance/templates/create/index.tsx new file mode 100644 index 000000000..499c7c859 --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/templates/create/index.tsx @@ -0,0 +1,62 @@ +/* + This file is part of GNU Taler + (C) 2021-2024 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +/** + * + * @author Sebastian Javier Marchano (sebasjm) + */ + +import { TalerMerchantApi } from "@gnu-taler/taler-util"; +import { useTranslationContext } from "@gnu-taler/web-util/browser"; +import { Fragment, VNode, h } from "preact"; +import { useState } from "preact/hooks"; +import { NotificationCard } from "../../../../components/menu/index.js"; +import { useSessionContext } from "../../../../context/session.js"; +import { Notification } from "../../../../utils/types.js"; +import { CreatePage } from "./CreatePage.js"; + +export type Entity = TalerMerchantApi.TransferInformation; +interface Props { + onBack?: () => void; + onConfirm: () => void; +} + +export default function CreateTransfer({ onConfirm, onBack }: Props): VNode { + const { lib } = useSessionContext(); + const { state } = useSessionContext(); + const [notif, setNotif] = useState<Notification | undefined>(undefined); + const { i18n } = useTranslationContext(); + + return ( + <> + <NotificationCard notification={notif} /> + <CreatePage + onBack={onBack} + onCreate={(request: TalerMerchantApi.TemplateAddDetails) => { + return lib.instance.addTemplate(state.token, request) + .then(() => onConfirm()) + .catch((error) => { + setNotif({ + message: i18n.str`could not inform template`, + type: "ERROR", + description: error.message, + }); + }); + }} + /> + </> + ); +} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/templates/list/List.stories.tsx b/packages/merchant-backoffice-ui/src/paths/instance/templates/list/List.stories.tsx new file mode 100644 index 000000000..707324d40 --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/templates/list/List.stories.tsx @@ -0,0 +1,28 @@ +/* + This file is part of GNU Taler + (C) 2021-2024 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +/** + * + * @author Sebastian Javier Marchano (sebasjm) + */ + +import { FunctionalComponent, h } from "preact"; +import { ListPage as TestedComponent } from "./ListPage.js"; + +export default { + title: "Pages/Templates/List", + component: TestedComponent, +}; diff --git a/packages/merchant-backoffice-ui/src/paths/instance/templates/list/ListPage.tsx b/packages/merchant-backoffice-ui/src/paths/instance/templates/list/ListPage.tsx new file mode 100644 index 000000000..66d8a2f7e --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/templates/list/ListPage.tsx @@ -0,0 +1,63 @@ +/* + This file is part of GNU Taler + (C) 2021-2024 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +/** + * + * @author Sebastian Javier Marchano (sebasjm) + */ + +import { TalerMerchantApi } from "@gnu-taler/taler-util"; +import { h, VNode } from "preact"; +import { CardTable } from "./Table.js"; + +export interface Props { + templates: TalerMerchantApi.TemplateEntry[]; + onLoadMoreBefore?: () => void; + onLoadMoreAfter?: () => void; + onCreate: () => void; + onDelete: (e: TalerMerchantApi.TemplateEntry) => void; + onSelect: (e: TalerMerchantApi.TemplateEntry) => void; + onNewOrder: (e: TalerMerchantApi.TemplateEntry) => void; + onQR: (e: TalerMerchantApi.TemplateEntry) => void; +} + +export function ListPage({ + templates, + onCreate, + onDelete, + onSelect, + onNewOrder, + onQR, + onLoadMoreBefore, + onLoadMoreAfter, +}: Props): VNode { + + return ( + <CardTable + templates={templates.map((o) => ({ + ...o, + id: String(o.template_id), + }))} + onQR={onQR} + onCreate={onCreate} + onDelete={onDelete} + onSelect={onSelect} + onNewOrder={onNewOrder} + onLoadMoreBefore={onLoadMoreBefore} + onLoadMoreAfter={onLoadMoreAfter} + /> + ); +} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/templates/list/Table.tsx b/packages/merchant-backoffice-ui/src/paths/instance/templates/list/Table.tsx new file mode 100644 index 000000000..082e622e3 --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/templates/list/Table.tsx @@ -0,0 +1,220 @@ +/* + This file is part of GNU Taler + (C) 2021-2024 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +/** + * + * @author Sebastian Javier Marchano (sebasjm) + */ + +import { TalerMerchantApi } from "@gnu-taler/taler-util"; +import { useTranslationContext } from "@gnu-taler/web-util/browser"; +import { h, VNode } from "preact"; +import { StateUpdater, useState } from "preact/hooks"; + +type Entity = TalerMerchantApi.TemplateEntry; + +interface Props { + templates: Entity[]; + onDelete: (e: Entity) => void; + onSelect: (e: Entity) => void; + onNewOrder: (e: Entity) => void; + onQR: (e: Entity) => void; + onCreate: () => void; + onLoadMoreBefore?: () => void; + onLoadMoreAfter?: () => void; +} + +export function CardTable({ + templates, + onCreate, + onDelete, + onSelect, + onQR, + onNewOrder, + onLoadMoreAfter, + onLoadMoreBefore, +}: Props): VNode { + const [rowSelection, rowSelectionHandler] = useState<string[]>([]); + + const { i18n } = useTranslationContext(); + + return ( + <div class="card has-table"> + <header class="card-header"> + <p class="card-header-title"> + <span class="icon"> + <i class="mdi mdi-newspaper" /> + </span> + <i18n.Translate>Templates</i18n.Translate> + </p> + <div class="card-header-icon" aria-label="more options"> + <span + class="has-tooltip-left" + data-tooltip={i18n.str`add new templates`} + > + <button class="button is-info" type="button" onClick={onCreate}> + <span class="icon is-small"> + <i class="mdi mdi-plus mdi-36px" /> + </span> + </button> + </span> + </div> + </header> + <div class="card-content"> + <div class="b-table has-pagination"> + <div class="table-wrapper has-mobile-cards"> + {templates.length > 0 ? ( + <Table + instances={templates} + onDelete={onDelete} + onSelect={onSelect} + onNewOrder={onNewOrder} + onQR={onQR} + rowSelection={rowSelection} + rowSelectionHandler={rowSelectionHandler} + onLoadMoreAfter={onLoadMoreAfter} + onLoadMoreBefore={onLoadMoreBefore} + /> + ) : ( + <EmptyTable /> + )} + </div> + </div> + </div> + </div> + ); +} +interface TableProps { + rowSelection: string[]; + instances: Entity[]; + onDelete: (e: Entity) => void; + onNewOrder: (e: Entity) => void; + onQR: (e: Entity) => void; + onSelect: (e: Entity) => void; + rowSelectionHandler: StateUpdater<string[]>; + onLoadMoreBefore?: () => void; + onLoadMoreAfter?: () => void; +} + +function Table({ + instances, + onLoadMoreAfter, + onDelete, + onNewOrder, + onQR, + onSelect, + onLoadMoreBefore, +}: TableProps): VNode { + const { i18n } = useTranslationContext(); + return ( + <div class="table-container"> + {onLoadMoreBefore && ( + <button + class="button is-fullwidth" + data-tooltip={i18n.str`load more templates before the first one`} + onClick={onLoadMoreBefore} + > + <i18n.Translate>load first page</i18n.Translate> + </button> + )} + <table class="table is-fullwidth is-striped is-hoverable is-fullwidth"> + <thead> + <tr> + <th> + <i18n.Translate>ID</i18n.Translate> + </th> + <th> + <i18n.Translate>Description</i18n.Translate> + </th> + <th /> + </tr> + </thead> + <tbody> + {instances.map((i) => { + return ( + <tr key={i.template_id}> + <td + onClick={(): void => onSelect(i)} + style={{ cursor: "pointer" }} + > + {i.template_id} + </td> + <td + onClick={(): void => onSelect(i)} + style={{ cursor: "pointer" }} + > + {i.template_description} + </td> + <td class="is-actions-cell right-sticky"> + <div class="buttons is-right"> + <button + class="button is-danger is-small has-tooltip-left" + data-tooltip={i18n.str`delete selected templates from the database`} + onClick={() => onDelete(i)} + > + Delete + </button> + <button + class="button is-info is-small has-tooltip-left" + data-tooltip={i18n.str`use template to create new order`} + onClick={() => onNewOrder(i)} + > + Use template + </button> + <button + class="button is-info is-small has-tooltip-left" + data-tooltip={i18n.str`create qr code for the template`} + onClick={() => onQR(i)} + > + QR + </button> + </div> + </td> + </tr> + ); + })} + </tbody> + </table> + {onLoadMoreAfter && ( + <button + class="button is-fullwidth" + data-tooltip={i18n.str`load more templates after the last one`} + onClick={onLoadMoreAfter} + > + <i18n.Translate>load next page</i18n.Translate> + </button> + )} + </div> + ); +} + +function EmptyTable(): VNode { + const { i18n } = useTranslationContext(); + return ( + <div class="content has-text-grey has-text-centered"> + <p> + <span class="icon is-large"> + <i class="mdi mdi-magnify mdi-48px" /> + </span> + </p> + <p> + <i18n.Translate> + There is no templates yet, add more pressing the + sign + </i18n.Translate> + </p> + </div> + ); +} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/templates/list/index.tsx b/packages/merchant-backoffice-ui/src/paths/instance/templates/list/index.tsx new file mode 100644 index 000000000..9e59609c7 --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/templates/list/index.tsx @@ -0,0 +1,152 @@ +/* + This file is part of GNU Taler + (C) 2021-2024 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +/** + * + * @author Sebastian Javier Marchano (sebasjm) + */ + +import { HttpStatusCode, TalerError, TalerMerchantApi, assertUnreachable } from "@gnu-taler/taler-util"; +import { + useTranslationContext +} from "@gnu-taler/web-util/browser"; +import { VNode, h } from "preact"; +import { useState } from "preact/hooks"; +import { ErrorLoadingMerchant } from "../../../../components/ErrorLoadingMerchant.js"; +import { Loading } from "../../../../components/exception/loading.js"; +import { JumpToElementById } from "../../../../components/form/JumpToElementById.js"; +import { NotificationCard } from "../../../../components/menu/index.js"; +import { ConfirmModal } from "../../../../components/modal/index.js"; +import { useSessionContext } from "../../../../context/session.js"; +import { + useInstanceTemplates +} from "../../../../hooks/templates.js"; +import { Notification } from "../../../../utils/types.js"; +import { LoginPage } from "../../../login/index.js"; +import { NotFoundPageOrAdminCreate } from "../../../notfound/index.js"; +import { ListPage } from "./ListPage.js"; + +interface Props { + onCreate: () => void; + onSelect: (id: string) => void; + onNewOrder: (id: string) => void; + onQR: (id: string) => void; +} + +export default function ListTemplates({ + onCreate, + onQR, + onSelect, + onNewOrder, +}: Props): VNode { + const { i18n } = useTranslationContext(); + const [notif, setNotif] = useState<Notification | undefined>(undefined); + const { lib } = useSessionContext(); + const result = useInstanceTemplates(); + const [deleting, setDeleting] = + useState<TalerMerchantApi.TemplateEntry | null>(null); + const { state } = useSessionContext(); + + if (!result) return <Loading /> + if (result instanceof TalerError) { + return <ErrorLoadingMerchant error={result} /> + } + if (result.type === "fail") { + switch(result.case) { + case HttpStatusCode.NotFound: { + return <NotFoundPageOrAdminCreate /> + } + case HttpStatusCode.Unauthorized: { + return <LoginPage /> + } + default: { + assertUnreachable(result) + } + } + } + + return ( + <section class="section is-main-section"> + <NotificationCard notification={notif} /> + + <JumpToElementById + testIfExist={async (id) => { + const resp = await lib.instance.getTemplateDetails(state.token, id) + return resp.type === "ok" + }} + onSelect={onSelect} + description={i18n.str`jump to template with the given template ID`} + placeholder={i18n.str`template id`} + /> + + <ListPage + templates={result.body} + onLoadMoreBefore={ + result.isFirstPage ? undefined: result.loadFirst + } + onLoadMoreAfter={result.isLastPage ? undefined : result.loadNext} + onCreate={onCreate} + onSelect={(e) => { + onSelect(e.template_id); + }} + onNewOrder={(e) => { + onNewOrder(e.template_id); + }} + onQR={(e) => { + onQR(e.template_id); + }} + onDelete={(e: TalerMerchantApi.TemplateEntry) => { + setDeleting(e) + } + } + /> + + {deleting && ( + <ConfirmModal + label={`Delete template`} + description={`Delete the template "${deleting.template_description}"`} + danger + active + onCancel={() => setDeleting(null)} + onConfirm={async (): Promise<void> => { + try { + await lib.instance.deleteTemplate(state.token, deleting.template_id); + setNotif({ + message: i18n.str`Template "${deleting.template_description}" (ID: ${deleting.template_id}) has been deleted`, + type: "SUCCESS", + }); + } catch (error) { + setNotif({ + message: i18n.str`Failed to delete template`, + type: "ERROR", + description: error instanceof Error ? error.message : undefined, + }); + } + setDeleting(null); + }} + > + <p> + If you delete the template <b>"{deleting.template_description}"</b> (ID:{" "} + <b>{deleting.template_id}</b>) you may loose information + </p> + <p class="warning"> + Deleting an template <b>cannot be undone</b>. + </p> + </ConfirmModal> + )} + </section> + ); +} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/templates/qr/Qr.stories.tsx b/packages/merchant-backoffice-ui/src/paths/instance/templates/qr/Qr.stories.tsx new file mode 100644 index 000000000..c0059c7bc --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/templates/qr/Qr.stories.tsx @@ -0,0 +1,27 @@ +/* + This file is part of GNU Taler + (C) 2021-2024 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +/** + * + * @author Sebastian Javier Marchano (sebasjm) + */ + +import { QrPage as TestedComponent } from "./QrPage.js"; + +export default { + title: "Pages/Templates/QR", + component: TestedComponent, +}; diff --git a/packages/merchant-backoffice-ui/src/paths/instance/templates/qr/QrPage.tsx b/packages/merchant-backoffice-ui/src/paths/instance/templates/qr/QrPage.tsx new file mode 100644 index 000000000..05cced06d --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/templates/qr/QrPage.tsx @@ -0,0 +1,155 @@ +/* + This file is part of GNU Taler + (C) 2021-2024 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +/** + * + * @author Sebastian Javier Marchano (sebasjm) + */ + +import { + TalerMerchantApi, + stringifyPayTemplateUri +} from "@gnu-taler/taler-util"; +import { + useTranslationContext +} from "@gnu-taler/web-util/browser"; +import { VNode, h } from "preact"; +import { QR } from "../../../../components/exception/QR.js"; +import { useSessionContext } from "../../../../context/session.js"; + +// type Entity = TalerMerchantApi.UsingTemplateDetails; + +interface Props { + contract: TalerMerchantApi.TemplateContractDetails; + id: string; + onBack?: () => void; +} + +export function QrPage({ id: templateId, onBack }: Props): VNode { + const { i18n } = useTranslationContext(); + const { state } = useSessionContext(); + + // const [state, setState] = useState<Partial<Entity>>({ + // amount: contract.amount, + // summary: contract.summary, + // }); + + // const errors: FormErrors<Entity> = {}; + + // const fixedAmount = !!contract.amount; + // const fixedSummary = !!contract.summary; + + // const templateParams: Record<string, string> = {}; + // if (!fixedAmount) { + // if (state.amount) { + // templateParams.amount = state.amount; + // } else { + // templateParams.amount = config.currency; + // } + // } + + // if (!fixedSummary) { + // templateParams.summary = state.summary ?? ""; + // } + + const merchantBaseUrl = state.backendUrl.href; + + const payTemplateUri = stringifyPayTemplateUri({ + merchantBaseUrl, + templateId, + // FIXME! + //templateParams: {}, + }); + + return ( + <div> + <section id="printThis"> + <QR text={payTemplateUri} /> + <pre style={{ textAlign: "center" }}> + <a href={payTemplateUri}>{payTemplateUri}</a> + </pre> + </section> + + <section class="section is-main-section"> + <div class="columns"> + <div class="column" /> + <div class="column is-four-fifths"> + {/* <p class="is-size-5 mt-5 mb-5"> + <i18n.Translate> + Here you can specify a default value for fields that are not + fixed. Default values can be edited by the customer before the + payment. + </i18n.Translate> + </p> */} + + <p></p> + {/* <FormProvider + object={state} + valueHandler={setState} + errors={errors} + > + <InputCurrency<Entity> + name="amount" + label={i18n.str`Amount`} + readonly + tooltip={i18n.str`Amount of the order`} + /> + <Input<Entity> + name="summary" + inputType="multiline" + readonly + label={i18n.str`Summary`} + tooltip={i18n.str`Title of the order to be shown to the customer`} + /> + </FormProvider> */} + + <div class="buttons is-right mt-5"> + {onBack && ( + <button class="button" onClick={onBack}> + <i18n.Translate>Cancel</i18n.Translate> + </button> + )} + <button + class="button is-info" + onClick={() => saveAsPDF(templateId)} + > + <i18n.Translate>Print</i18n.Translate> + </button> + </div> + </div> + <div class="column" /> + </div> + </section> + </div> + ); +} + +function saveAsPDF(name: string): void { + const printWindow = window.open("", "", "height=400,width=800"); + if (!printWindow) return; + const divContents = document.getElementById("printThis"); + if (!divContents) return; + printWindow.document.write( + `<html><head><title>Order template for ${name}</title><style>`, + ); + printWindow.document.write("</style></head><body> </body></html>"); + printWindow.document.close(); + printWindow.document.body.appendChild(divContents.cloneNode(true)); + printWindow.addEventListener("load", () => { + printWindow.print(); + // printWindow.close(); + }); +} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/templates/qr/index.tsx b/packages/merchant-backoffice-ui/src/paths/instance/templates/qr/index.tsx new file mode 100644 index 000000000..ed809c7b3 --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/templates/qr/index.tsx @@ -0,0 +1,66 @@ +/* + This file is part of GNU Taler + (C) 2021-2024 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +/** + * + * @author Sebastian Javier Marchano (sebasjm) + */ + +import { HttpStatusCode, TalerError, TalerMerchantApi, assertUnreachable } from "@gnu-taler/taler-util"; +import { VNode, h } from "preact"; +import { ErrorLoadingMerchant } from "../../../../components/ErrorLoadingMerchant.js"; +import { Loading } from "../../../../components/exception/loading.js"; +import { + useTemplateDetails +} from "../../../../hooks/templates.js"; +import { NotFoundPageOrAdminCreate } from "../../../notfound/index.js"; +import { QrPage } from "./QrPage.js"; +import { LoginPage } from "../../../login/index.js"; + +export type Entity = TalerMerchantApi.TransferInformation; +interface Props { + onBack?: () => void; + tid: string; +} + +export default function TemplateQrPage({ + tid, + onBack, +}: Props): VNode { + const result = useTemplateDetails(tid); + if (!result) return <Loading /> + if (result instanceof TalerError) { + return <ErrorLoadingMerchant error={result} /> + } + if (result.type === "fail") { + switch(result.case) { + case HttpStatusCode.NotFound: { + return <NotFoundPageOrAdminCreate /> + } + case HttpStatusCode.Unauthorized: { + return <LoginPage /> + } + default: { + assertUnreachable(result) + } + } + } + + + return ( + <QrPage contract={result.body.template_contract} id={tid} onBack={onBack} /> + ); +} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/templates/update/Update.stories.tsx b/packages/merchant-backoffice-ui/src/paths/instance/templates/update/Update.stories.tsx new file mode 100644 index 000000000..303d17b72 --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/templates/update/Update.stories.tsx @@ -0,0 +1,32 @@ +/* + This file is part of GNU Taler + (C) 2021-2024 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +/** + * + * @author Sebastian Javier Marchano (sebasjm) + */ + +import { h, VNode, FunctionalComponent } from "preact"; +import { UpdatePage as TestedComponent } from "./UpdatePage.js"; + +export default { + title: "Pages/Templates/Update", + component: TestedComponent, + argTypes: { + onUpdate: { action: "onUpdate" }, + onBack: { action: "onBack" }, + }, +}; diff --git a/packages/merchant-backoffice-ui/src/paths/instance/templates/update/UpdatePage.tsx b/packages/merchant-backoffice-ui/src/paths/instance/templates/update/UpdatePage.tsx new file mode 100644 index 000000000..32c5637aa --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/templates/update/UpdatePage.tsx @@ -0,0 +1,311 @@ +/* + This file is part of GNU Taler + (C) 2021-2024 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +/** + * + * @author Sebastian Javier Marchano (sebasjm) + */ + +import { + AmountString, + Amounts, + Duration, + TalerError, + TalerMerchantApi, + TranslatedString, +} from "@gnu-taler/taler-util"; +import { + useTranslationContext +} from "@gnu-taler/web-util/browser"; +import { Fragment, VNode, h } from "preact"; +import { useState } from "preact/hooks"; +import { AsyncButton } from "../../../../components/exception/AsyncButton.js"; +import { + FormErrors, + FormProvider, +} from "../../../../components/form/FormProvider.js"; +import { Input } from "../../../../components/form/Input.js"; +import { InputCurrency } from "../../../../components/form/InputCurrency.js"; +import { InputDuration } from "../../../../components/form/InputDuration.js"; +import { InputNumber } from "../../../../components/form/InputNumber.js"; +import { InputSelector } from "../../../../components/form/InputSelector.js"; +import { InputToggle } from "../../../../components/form/InputToggle.js"; +import { TextField } from "../../../../components/form/TextField.js"; +import { useSessionContext } from "../../../../context/session.js"; +import { useInstanceOtpDevices } from "../../../../hooks/otp.js"; + +type Entity = { + description?: string; + otpId?: string | null; + summary?: string; + amount?: string; + minimum_age?: number; + pay_duration?: Duration; + summary_editable?: boolean; + amount_editable?: boolean; + currency_editable?: boolean; +}; + +interface Props { + onUpdate: (d: TalerMerchantApi.TemplatePatchDetails) => Promise<void>; + onBack?: () => void; + template: TalerMerchantApi.TemplateDetails & WithId; +} + +export function UpdatePage({ template, onUpdate, onBack }: Props): VNode { + const { i18n } = useTranslationContext(); + const { config } = useSessionContext(); + const { state: session } = useSessionContext(); + + const [state, setState] = useState<Partial<Entity>>({ + description: template.template_description, + minimum_age: template.template_contract.minimum_age, + otpId: template.otp_id, + pay_duration: template.template_contract.pay_duration + ? Duration.fromTalerProtocolDuration( + template.template_contract.pay_duration, + ) + : undefined, + summary: + template.editable_defaults?.summary ?? template.template_contract.summary, + amount: + template.editable_defaults?.amount ?? + (template.template_contract.amount as AmountString | undefined), + currency_editable: !!template.editable_defaults?.currency, + summary_editable: template.editable_defaults?.summary !== undefined, + amount_editable: template.editable_defaults?.amount !== undefined, + }); + + function updateState(up: (s: Partial<Entity>) => Partial<Entity>) { + setState((old) => { + const newState = up(old); + if (!newState.amount_editable) { + newState.currency_editable = false; + } + return newState; + }); + } + + const devices = useInstanceOtpDevices(); + const deviceList = + !devices || devices instanceof TalerError || devices.type === "fail" + ? [] + : devices.body.otp_devices; + const deviceMap = deviceList.reduce( + (prev, cur) => { + prev[cur.otp_device_id] = cur.device_description as TranslatedString; + return prev; + }, + {} as Record<string, TranslatedString>, + ); + + const parsedPrice = !state.amount ? undefined : Amounts.parse(state.amount); + + const errors: FormErrors<Entity> = { + description: !state.description ? i18n.str`should not be empty` : undefined, + amount: !state.amount + ? state.amount_editable ? undefined : i18n.str`required` + : !parsedPrice + ? i18n.str`not valid` + : Amounts.isZero(parsedPrice) + ? state.amount_editable ? undefined : i18n.str`must be greater than 0` + : undefined, + minimum_age: + state.minimum_age && state.minimum_age < 0 + ? i18n.str`should be greater that 0` + : undefined, + pay_duration: !state.pay_duration + ? i18n.str`can't be empty` + : state.pay_duration.d_ms === "forever" + ? undefined + : state.pay_duration.d_ms < 1000 // less than one second + ? i18n.str`to short` + : undefined, + }; + + const cList = Object.values(config.currencies).map((d) => d.name); + + const hasErrors = Object.keys(errors).some( + (k) => (errors as Record<string, unknown>)[k] !== undefined, + ); + + const zero = Amounts.stringify(Amounts.zeroOfCurrency(config.currency)) + + const submitForm = () => { + if (hasErrors) return Promise.reject(); + const contract_amount = state.amount_editable ? undefined : state.amount as AmountString + const contract_summary = state.summary_editable ? undefined : state.summary + const template_contract: TalerMerchantApi.TemplateContractDetails = { + minimum_age: state.minimum_age!, + pay_duration: Duration.toTalerProtocolDuration(state.pay_duration!), + amount: contract_amount, + summary: contract_summary, + currency: + cList.length > 1 && state.currency_editable + ? undefined + : config.currency, + } + return onUpdate({ + template_description: state.description!, + template_contract, + required_currency: contract_amount !== undefined ? undefined : config.currency, + editable_defaults: { + amount: !state.amount_editable ? undefined : (state.amount ?? zero), + summary: !state.summary_editable ? undefined : (state.summary ?? ""), + currency: + cList.length === 1 || !state.currency_editable + ? undefined + : config.currency, + }, + otp_id: state.otpId!, + }); + }; + + return ( + <div> + <section class="section"> + <section class="hero is-hero-bar"> + <div class="hero-body"> + <div class="level"> + <div class="level-left"> + <div class="level-item"> + <span class="is-size-4"> + {new URL(`templates/${template.id}`, session.backendUrl.href).href} + </span> + </div> + </div> + </div> + </div> + </section> + <hr /> + + <section class="section is-main-section"> + <div class="columns"> + <div class="column is-four-fifths"> + <FormProvider + object={state} + valueHandler={updateState} + errors={errors} + > + <Input<Entity> + name="description" + label={i18n.str`Description`} + help="" + tooltip={i18n.str`Describe what this template stands for`} + /> + <Input<Entity> + name="summary" + inputType="multiline" + label={i18n.str`Summary`} + tooltip={i18n.str`If specified, this template will create order with the same summary`} + /> + <InputToggle<Entity> + name="summary_editable" + label={i18n.str`Summary is editable`} + tooltip={i18n.str`Allow the user to change the summary.`} + /> + <InputCurrency<Entity> + name="amount" + label={i18n.str`Amount`} + tooltip={i18n.str`If specified, this template will create order with the same price`} + /> + <InputToggle<Entity> + name="amount_editable" + label={i18n.str`Amount is editable`} + tooltip={i18n.str`Allow the user to select the amount to pay.`} + /> + {cList.length > 1 && ( + <Fragment> + <InputToggle<Entity> + name="currency_editable" + readonly={!state.amount_editable} + label={i18n.str`Currency is editable`} + tooltip={i18n.str`Allow the user to change currency.`} + /> + <TextField name="sc" label={i18n.str`Supported currencies`}> + <i18n.Translate> + supported currencies: {cList.join(", ")} + </i18n.Translate> + </TextField> + </Fragment> + )} + <InputNumber<Entity> + name="minimum_age" + label={i18n.str`Minimum age`} + help="" + tooltip={i18n.str`Is this contract restricted to some age?`} + /> + <InputDuration<Entity> + name="pay_duration" + label={i18n.str`Payment timeout`} + help="" + tooltip={i18n.str`How much time has the customer to complete the payment once the order was created.`} + /> + {!deviceList.length ? ( + <TextField + name="otpId" + label={i18n.str`OTP device`} + tooltip={i18n.str`Use to verify transaction while offline.`} + > + <i18n.Translate>No OTP device.</i18n.Translate> + <a href="/otp-devices/new"> + <i18n.Translate>Add one first</i18n.Translate> + </a> + </TextField> + ) : ( + <InputSelector<Entity> + name="otpId" + label={i18n.str`OTP device`} + values={[ + undefined, + ...deviceList.map((e) => e.otp_device_id), + ]} + toStr={(v?: string) => { + if (!v) { + return i18n.str`No device`; + } + return deviceMap[v]; + }} + tooltip={i18n.str`Use to verify transaction in offline mode.`} + /> + )} + </FormProvider> + + <div class="buttons is-right mt-5"> + {onBack && ( + <button class="button" onClick={onBack}> + <i18n.Translate>Cancel</i18n.Translate> + </button> + )} + <AsyncButton + disabled={hasErrors} + data-tooltip={ + hasErrors + ? i18n.str`Need to complete marked fields` + : "confirm operation" + } + onClick={submitForm} + > + <i18n.Translate>Confirm</i18n.Translate> + </AsyncButton> + </div> + </div> + </div> + </section> + </section> + </div> + ); +} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/templates/update/index.tsx b/packages/merchant-backoffice-ui/src/paths/instance/templates/update/index.tsx new file mode 100644 index 000000000..6185bd2a9 --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/templates/update/index.tsx @@ -0,0 +1,97 @@ +/* + This file is part of GNU Taler + (C) 2021-2024 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +/** + * + * @author Sebastian Javier Marchano (sebasjm) + */ + +import { HttpStatusCode, TalerError, TalerMerchantApi, assertUnreachable } from "@gnu-taler/taler-util"; +import { + useTranslationContext +} from "@gnu-taler/web-util/browser"; +import { Fragment, VNode, h } from "preact"; +import { useState } from "preact/hooks"; +import { ErrorLoadingMerchant } from "../../../../components/ErrorLoadingMerchant.js"; +import { Loading } from "../../../../components/exception/loading.js"; +import { NotificationCard } from "../../../../components/menu/index.js"; +import { useSessionContext } from "../../../../context/session.js"; +import { + useTemplateDetails, +} from "../../../../hooks/templates.js"; +import { Notification } from "../../../../utils/types.js"; +import { LoginPage } from "../../../login/index.js"; +import { NotFoundPageOrAdminCreate } from "../../../notfound/index.js"; +import { UpdatePage } from "./UpdatePage.js"; + +export type Entity = TalerMerchantApi.TemplatePatchDetails & WithId; + +interface Props { + onBack?: () => void; + onConfirm: () => void; + tid: string; +} +export default function UpdateTemplate({ + tid, + onConfirm, + onBack, +}: Props): VNode { + const { lib } = useSessionContext(); + const { state } = useSessionContext(); + const result = useTemplateDetails(tid); + const [notif, setNotif] = useState<Notification | undefined>(undefined); + + const { i18n } = useTranslationContext(); + + if (!result) return <Loading /> + if (result instanceof TalerError) { + return <ErrorLoadingMerchant error={result} /> + } + if (result.type === "fail") { + switch(result.case) { + case HttpStatusCode.NotFound: { + return <NotFoundPageOrAdminCreate /> + } + case HttpStatusCode.Unauthorized: { + return <LoginPage /> + } + default: { + assertUnreachable(result) + } + } + } + + return ( + <Fragment> + <NotificationCard notification={notif} /> + <UpdatePage + template={{...result.body, id: tid}} + onBack={onBack} + onUpdate={(data) => { + return lib.instance.updateTemplate(state.token, tid, data) + .then(onConfirm) + .catch((error) => { + setNotif({ + message: i18n.str`could not update template`, + type: "ERROR", + description: error.message, + }); + }); + }} + /> + </Fragment> + ); +} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/templates/use/Use.stories.tsx b/packages/merchant-backoffice-ui/src/paths/instance/templates/use/Use.stories.tsx new file mode 100644 index 000000000..d91888b97 --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/templates/use/Use.stories.tsx @@ -0,0 +1,27 @@ +/* + This file is part of GNU Taler + (C) 2021-2024 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +/** + * + * @author Sebastian Javier Marchano (sebasjm) + */ + +import { UsePage as TestedComponent } from "./UsePage.js"; + +export default { + title: "Pages/Templates/Create", + component: TestedComponent, +}; diff --git a/packages/merchant-backoffice-ui/src/paths/instance/templates/use/UsePage.tsx b/packages/merchant-backoffice-ui/src/paths/instance/templates/use/UsePage.tsx new file mode 100644 index 000000000..5b1404b55 --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/templates/use/UsePage.tsx @@ -0,0 +1,143 @@ +/* + This file is part of GNU Taler + (C) 2021-2024 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +/** + * + * @author Sebastian Javier Marchano (sebasjm) + */ + +import { AmountString, TalerMerchantApi } from "@gnu-taler/taler-util"; +import { useTranslationContext } from "@gnu-taler/web-util/browser"; +import { VNode, h } from "preact"; +import { useState } from "preact/hooks"; +import { AsyncButton } from "../../../../components/exception/AsyncButton.js"; +import { + FormErrors, + FormProvider, +} from "../../../../components/form/FormProvider.js"; +import { Input } from "../../../../components/form/Input.js"; +import { InputCurrency } from "../../../../components/form/InputCurrency.js"; + +type Entity = TalerMerchantApi.TemplateContractDetails; + +interface Props { + id: string; + template: TalerMerchantApi.TemplateDetails; + onCreateOrder: (d: Entity) => Promise<void>; + onBack?: () => void; +} + +export function UsePage({ id, template, onCreateOrder, onBack }: Props): VNode { + const { i18n } = useTranslationContext(); + + const [state, setState] = useState<Partial<Entity>>({ + currency: + template.editable_defaults?.currency ?? + template.template_contract.currency, + // FIXME: Add additional check here, editable default might be a plain string! + amount: (template.editable_defaults?.amount ?? + template.template_contract.amount) as AmountString, + summary: + template.editable_defaults?.summary ?? template.template_contract.summary, + }); + + const errors: FormErrors<Entity> = { + amount: !state.amount ? i18n.str`Amount is required` : undefined, + summary: !state.summary ? i18n.str`Order summary is required` : undefined, + }; + + const hasErrors = Object.keys(errors).some( + (k) => (errors as any)[k] !== undefined, + ); + + const submitForm = () => { + if (hasErrors) return Promise.reject(); + if (template.template_contract.amount) { + delete state.amount; + } + if (template.template_contract.summary) { + delete state.summary; + } + return onCreateOrder(state as any); + }; + + return ( + <div> + <section class="section"> + <section class="hero is-hero-bar"> + <div class="hero-body"> + <div class="level"> + <div class="level-left"> + <div class="level-item"> + <span class="is-size-4"> + <i18n.Translate>New order for template</i18n.Translate>:{" "} + <b>{id}</b> + </span> + </div> + </div> + </div> + </div> + </section> + </section> + <section class="section is-main-section"> + <div class="columns"> + <div class="column" /> + <div class="column is-four-fifths"> + <FormProvider + object={state} + valueHandler={setState} + errors={errors} + > + <InputCurrency<Entity> + name="amount" + label={i18n.str`Amount`} + readonly={!!template.template_contract.amount} + tooltip={i18n.str`Amount of the order`} + /> + <Input<Entity> + name="summary" + inputType="multiline" + label={i18n.str`Order summary`} + readonly={!!template.template_contract.summary} + tooltip={i18n.str`Title of the order to be shown to the customer`} + /> + </FormProvider> + + <div class="buttons is-right mt-5"> + {onBack && ( + <button class="button" onClick={onBack}> + <i18n.Translate>Cancel</i18n.Translate> + </button> + )} + <AsyncButton + disabled={hasErrors} + data-tooltip={ + hasErrors + ? i18n.str`Need to complete marked fields` + : "confirm operation" + } + onClick={submitForm} + > + <i18n.Translate>Confirm</i18n.Translate> + </AsyncButton> + </div> + </div> + <div class="column" /> + </div> + </section> + </div> + ); +} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/templates/use/index.tsx b/packages/merchant-backoffice-ui/src/paths/instance/templates/use/index.tsx new file mode 100644 index 000000000..00cb2b827 --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/templates/use/index.tsx @@ -0,0 +1,108 @@ +/* + This file is part of GNU Taler + (C) 2021-2024 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +/** + * + * @author Sebastian Javier Marchano (sebasjm) + */ + +import { HttpStatusCode, TalerError, TalerMerchantApi, assertUnreachable } from "@gnu-taler/taler-util"; +import { + useTranslationContext +} from "@gnu-taler/web-util/browser"; +import { Fragment, VNode, h } from "preact"; +import { useState } from "preact/hooks"; +import { ErrorLoadingMerchant } from "../../../../components/ErrorLoadingMerchant.js"; +import { Loading } from "../../../../components/exception/loading.js"; +import { NotificationCard } from "../../../../components/menu/index.js"; +import { + useTemplateDetails +} from "../../../../hooks/templates.js"; +import { Notification } from "../../../../utils/types.js"; +import { LoginPage } from "../../../login/index.js"; +import { NotFoundPageOrAdminCreate } from "../../../notfound/index.js"; +import { UsePage } from "./UsePage.js"; +import { useSessionContext } from "../../../../context/session.js"; + +export type Entity = TalerMerchantApi.TransferInformation; +interface Props { + onBack?: () => void; + onOrderCreated: (id: string) => void; + tid: string; +} + +export default function TemplateUsePage({ + tid, + onOrderCreated, + onBack, +}: Props): VNode { + const { lib } = useSessionContext(); + const result = useTemplateDetails(tid); + const [notif, setNotif] = useState<Notification | undefined>(undefined); + const { i18n } = useTranslationContext(); + + if (!result) return <Loading /> + if (result instanceof TalerError) { + return <ErrorLoadingMerchant error={result} /> + } + if (result.type === "fail") { + switch(result.case) { + case HttpStatusCode.NotFound: { + return <NotFoundPageOrAdminCreate /> + } + case HttpStatusCode.Unauthorized: { + return <LoginPage /> + } + default: { + assertUnreachable(result) + } + } + } + + return ( + <> + <NotificationCard notification={notif} /> + <UsePage + template={result.body} + id={tid} + onBack={onBack} + onCreateOrder={( + request: TalerMerchantApi.UsingTemplateDetails, + ) => { + + return lib.instance.useTemplateCreateOrder(tid, request) + .then((res) => { + if (res.type === "ok") { + onOrderCreated(res.body.order_id) + } else { + setNotif({ + message: i18n.str`could not create order from template`, + type: "ERROR", + }); + } + }) + .catch((error) => { + setNotif({ + message: i18n.str`could not create order from template`, + type: "ERROR", + description: error.message, + }); + }); + }} + /> + </> + ); +} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/token/DetailPage.tsx b/packages/merchant-backoffice-ui/src/paths/instance/token/DetailPage.tsx new file mode 100644 index 000000000..d718ffb69 --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/token/DetailPage.tsx @@ -0,0 +1,188 @@ +/* + This file is part of GNU Taler + (C) 2021-2024 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +/** + * + * @author Sebastian Javier Marchano (sebasjm) + */ + +import { useTranslationContext } from "@gnu-taler/web-util/browser"; +import { Fragment, h, VNode } from "preact"; +import { useState } from "preact/hooks"; +import { AsyncButton } from "../../../components/exception/AsyncButton.js"; +import { FormProvider } from "../../../components/form/FormProvider.js"; +import { Input } from "../../../components/form/Input.js"; +import { NotificationCard } from "../../../components/menu/index.js"; +import { useSessionContext } from "../../../context/session.js"; +import { AccessToken, createRFC8959AccessTokenPlain } from "@gnu-taler/taler-util"; + +interface Props { + hasToken: boolean | undefined; + onClearToken: (c: AccessToken | undefined) => void; + onNewToken: (c: AccessToken | undefined, s: AccessToken) => void; + onBack?: () => void; +} + +export function DetailPage({ + hasToken, + onBack, + onNewToken, + onClearToken, +}: Props): VNode { + type State = { old_token: string; new_token: string; repeat_token: string }; + const [form, setValue] = useState<Partial<State>>({ + old_token: "", + new_token: "", + repeat_token: "", + }); + const { i18n } = useTranslationContext(); + + const errors = { + old_token: + hasToken && !form.old_token + ? i18n.str`you need your access token to perform the operation` + : undefined, + new_token: !form.new_token + ? i18n.str`cannot be empty` + : form.new_token === form.old_token + ? i18n.str`cannot be the same as the old token` + : undefined, + repeat_token: + form.new_token !== form.repeat_token + ? i18n.str`is not the same` + : undefined, + }; + + const hasErrors = Object.keys(errors).some( + (k) => (errors as Record<string, unknown>)[k] !== undefined, + ); + + const { state } = useSessionContext(); + + const text = i18n.str`You are updating the access token from instance with id "${state.instance}"`; + + async function submitForm() { + if (hasErrors) return; + const oldToken = + form.old_token !== undefined && hasToken + ? createRFC8959AccessTokenPlain(form.old_token) + : undefined; + const newToken = createRFC8959AccessTokenPlain(form.new_token!); + onNewToken(oldToken, newToken); + } + + return ( + <div> + <section class="section"> + <section class="hero is-hero-bar"> + <div class="hero-body"> + <div class="level"> + <div class="level-left"> + <div class="level-item"> + <span class="is-size-4">{text}</span> + </div> + </div> + </div> + </div> + </section> + <hr /> + + {!hasToken && ( + <NotificationCard + notification={{ + message: i18n.str`This instance doesn't have authentication token.`, + description: i18n.str`You can leave it empty if there is another layer of security.`, + type: "WARN", + }} + /> + )} + + <div class="columns"> + <div class="column" /> + <div class="column is-four-fifths"> + <FormProvider errors={errors} object={form} valueHandler={setValue}> + <Fragment> + {hasToken && ( + <Fragment> + <Input<State> + name="old_token" + label={i18n.str`Current access token`} + tooltip={i18n.str`access token currently in use`} + inputType="password" + /> + <p> + <i18n.Translate> + Clearing the access token will mean public access to the + instance. + </i18n.Translate> + </p> + <div class="buttons is-right mt-5"> + <button + class="button" + onClick={() => { + if (hasToken) { + onClearToken(form.old_token ? createRFC8959AccessTokenPlain(form.old_token) : undefined); + } else { + onClearToken(undefined); + } + }} + > + <i18n.Translate>Clear token</i18n.Translate> + </button> + </div> + </Fragment> + )} + + <Input<State> + name="new_token" + label={i18n.str`New access token`} + tooltip={i18n.str`next access token to be used`} + inputType="password" + /> + <Input<State> + name="repeat_token" + label={i18n.str`Repeat access token`} + tooltip={i18n.str`confirm the same access token`} + inputType="password" + /> + </Fragment> + <div class="buttons is-right mt-5"> + {onBack && ( + <a class="button" onClick={onBack}> + <i18n.Translate>Cancel</i18n.Translate> + </a> + )} + <AsyncButton + type="submit" + disabled={hasErrors} + data-tooltip={ + hasErrors + ? i18n.str`Need to complete marked fields` + : "confirm operation" + } + onClick={submitForm} + > + <i18n.Translate>Confirm change</i18n.Translate> + </AsyncButton> + </div> + </FormProvider> + </div> + <div class="column" /> + </div> + </section> + </div> + ); +} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/token/index.tsx b/packages/merchant-backoffice-ui/src/paths/instance/token/index.tsx new file mode 100644 index 000000000..c23e5be17 --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/token/index.tsx @@ -0,0 +1,152 @@ +/* + This file is part of GNU Taler + (C) 2021-2024 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ +import { + HttpStatusCode, + TalerError, + assertUnreachable, +} from "@gnu-taler/taler-util"; +import { + useTranslationContext +} from "@gnu-taler/web-util/browser"; +import { Fragment, VNode, h } from "preact"; +import { useState } from "preact/hooks"; +import { ErrorLoadingMerchant } from "../../../components/ErrorLoadingMerchant.js"; +import { Loading } from "../../../components/exception/loading.js"; +import { NotificationCard } from "../../../components/menu/index.js"; +import { useSessionContext } from "../../../context/session.js"; +import { useInstanceDetails } from "../../../hooks/instance.js"; +import { Notification } from "../../../utils/types.js"; +import { LoginPage } from "../../login/index.js"; +import { NotFoundPageOrAdminCreate } from "../../notfound/index.js"; +import { DetailPage } from "./DetailPage.js"; + +interface Props { + onChange: () => void; + onCancel: () => void; +} + +export default function Token({ onChange, onCancel }: Props): VNode { + const { i18n } = useTranslationContext(); + const { lib } = useSessionContext(); + const { logIn } = useSessionContext(); + const [notif, setNotif] = useState<Notification | undefined>(undefined); + const result = useInstanceDetails(); + + if (!result) return <Loading />; + if (result instanceof TalerError) { + return <ErrorLoadingMerchant error={result} />; + } + if (result.type === "fail") { + switch (result.case) { + case HttpStatusCode.Unauthorized: { + return <LoginPage />; + } + case HttpStatusCode.NotFound: { + return <NotFoundPageOrAdminCreate />; + } + default: { + assertUnreachable(result); + } + } + } + + const hasToken = result.body.auth.method === "token"; + + return ( + <Fragment> + <NotificationCard notification={notif} /> + <DetailPage + onBack={onCancel} + hasToken={hasToken} + onClearToken={async (currentToken): Promise<void> => { + try { + const resp = await lib.instance.updateCurrentInstanceAuthentication( + currentToken, + { + method: "external", + }, + ); + if (resp.type === "ok") { + onChange(); + } else { + return setNotif({ + message: i18n.str`Failed to clear token`, + type: "ERROR", + description: resp.detail.hint, + }); + } + } catch (error) { + if (error instanceof Error) { + return setNotif({ + message: i18n.str`Failed to clear token`, + type: "ERROR", + description: error.message, + }); + } + } + }} + onNewToken={async (currentToken, newToken): Promise<void> => { + try { + { + const resp = + await lib.instance.updateCurrentInstanceAuthentication( + currentToken, + { + token: newToken, + method: "token", + }, + ); + if (resp.type === "fail") { + return setNotif({ + message: i18n.str`Failed to set new token`, + type: "ERROR", + description: resp.detail.hint, + }); + } + } + const resp = await lib.authenticate.createAccessTokenBearer( + newToken, + { + scope: "write", + duration: { + d_us: "forever", + }, + refreshable: true, + }, + ); + if (resp.type === "ok") { + logIn(resp.body.token); + return onChange(); + } else { + return setNotif({ + message: i18n.str`Failed to set new token`, + type: "ERROR", + }); + } + } catch (error) { + if (error instanceof Error) { + return setNotif({ + message: i18n.str`Failed to set new token`, + type: "ERROR", + description: error.message, + }); + } + } + }} + /> + </Fragment> + ); +} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/token/stories.tsx b/packages/merchant-backoffice-ui/src/paths/instance/token/stories.tsx new file mode 100644 index 000000000..581828657 --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/token/stories.tsx @@ -0,0 +1,28 @@ +/* + This file is part of GNU Taler + (C) 2021-2024 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +/** + * + * @author Sebastian Javier Marchano (sebasjm) + */ + +import { DetailPage as TestedComponent } from "./DetailPage.js"; + +export default { + title: "Pages/Token", + component: TestedComponent, +}; + diff --git a/packages/merchant-backoffice-ui/src/paths/instance/transfers/create/Create.stories.tsx b/packages/merchant-backoffice-ui/src/paths/instance/transfers/create/Create.stories.tsx index a21fe8e5b..ca38defc3 100644 --- a/packages/merchant-backoffice-ui/src/paths/instance/transfers/create/Create.stories.tsx +++ b/packages/merchant-backoffice-ui/src/paths/instance/transfers/create/Create.stories.tsx @@ -1,6 +1,6 @@ /* This file is part of GNU Taler - (C) 2021 Taler Systems S.A. + (C) 2021-2024 Taler Systems S.A. GNU Taler is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -15,29 +15,31 @@ */ /** -* -* @author Sebastian Javier Marchano (sebasjm) -*/ + * + * @author Sebastian Javier Marchano (sebasjm) + */ -import { h, VNode, FunctionalComponent } from 'preact'; +import { h, VNode, FunctionalComponent } from "preact"; import { CreatePage as TestedComponent } from "./CreatePage.js"; - export default { - title: 'Pages/Transfer/Create', + title: "Pages/Transfer/Create", component: TestedComponent, argTypes: { - onUpdate: { action: 'onUpdate' }, - onBack: { action: 'onBack' }, + onUpdate: { action: "onUpdate" }, + onBack: { action: "onBack" }, }, }; -function createExample<Props>(Component: FunctionalComponent<Props>, props: Partial<Props>) { - const r = (args: any) => <Component {...args} /> - r.args = props - return r +function createExample<Props>( + Component: FunctionalComponent<Props>, + props: Partial<Props>, +) { + const r = (args: any) => <Component {...args} />; + r.args = props; + return r; } export const Example = createExample(TestedComponent, { - accounts: ['payto://x-taler-bank/account1','payto://x-taler-bank/account2'] + accounts: ["payto://x-taler-bank/account1", "payto://x-taler-bank/account2"], }); diff --git a/packages/merchant-backoffice-ui/src/paths/instance/transfers/create/CreatePage.tsx b/packages/merchant-backoffice-ui/src/paths/instance/transfers/create/CreatePage.tsx index 15860381c..91aabe58e 100644 --- a/packages/merchant-backoffice-ui/src/paths/instance/transfers/create/CreatePage.tsx +++ b/packages/merchant-backoffice-ui/src/paths/instance/transfers/create/CreatePage.tsx @@ -1,6 +1,6 @@ /* This file is part of GNU Taler - (C) 2021 Taler Systems S.A. + (C) 2021-2024 Taler Systems S.A. GNU Taler is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -15,90 +15,130 @@ */ /** -* -* @author Sebastian Javier Marchano (sebasjm) -*/ + * + * @author Sebastian Javier Marchano (sebasjm) + */ -import { h, VNode } from "preact"; +import { AmountString, TalerMerchantApi } from "@gnu-taler/taler-util"; +import { useTranslationContext } from "@gnu-taler/web-util/browser"; +import { VNode, h } from "preact"; import { useState } from "preact/hooks"; import { AsyncButton } from "../../../../components/exception/AsyncButton.js"; -import { FormErrors, FormProvider } from "../../../../components/form/FormProvider.js"; +import { + FormErrors, + FormProvider, +} from "../../../../components/form/FormProvider.js"; import { Input } from "../../../../components/form/Input.js"; import { InputCurrency } from "../../../../components/form/InputCurrency.js"; import { InputSelector } from "../../../../components/form/InputSelector.js"; -import { useConfigContext } from "../../../../context/config.js"; -import { MerchantBackend } from "../../../../declaration.js"; -import { Translate, useTranslator } from "../../../../i18n/index.js"; -import { CROCKFORD_BASE32_REGEX, URL_REGEX } from "../../../../utils/constants.js"; +import { + CROCKFORD_BASE32_REGEX, + URL_REGEX, +} from "../../../../utils/constants.js"; -type Entity = MerchantBackend.Transfers.TransferInformation +type Entity = TalerMerchantApi.TransferInformation; interface Props { onCreate: (d: Entity) => Promise<void>; onBack?: () => void; - accounts: string[], + accounts: string[]; } export function CreatePage({ accounts, onCreate, onBack }: Props): VNode { - const i18n = useTranslator() - const { currency } = useConfigContext() + const { i18n } = useTranslationContext(); const [state, setState] = useState<Partial<Entity>>({ - wtid: '', + wtid: "", // payto_uri: , // exchange_url: 'http://exchange.taler:8081/', - credit_amount: ``, + credit_amount: `` as AmountString, }); const errors: FormErrors<Entity> = { - wtid: !state.wtid ? i18n`cannot be empty` : - (!CROCKFORD_BASE32_REGEX.test(state.wtid) ? i18n`check the id, does not look valid` : - (state.wtid.length !== 52 ? i18n`should have 52 characters, current ${state.wtid.length}` : - undefined)), - payto_uri: !state.payto_uri ? i18n`cannot be empty` : undefined, - credit_amount: !state.credit_amount ? i18n`cannot be empty` : undefined, - exchange_url: !state.exchange_url ? i18n`cannot be empty` : - (!URL_REGEX.test(state.exchange_url) ? i18n`URL doesn't have the right format` : undefined), - } - - const hasErrors = Object.keys(errors).some(k => (errors as any)[k] !== undefined) + wtid: !state.wtid + ? i18n.str`cannot be empty` + : !CROCKFORD_BASE32_REGEX.test(state.wtid) + ? i18n.str`check the id, does not look valid` + : state.wtid.length !== 52 + ? i18n.str`should have 52 characters, current ${state.wtid.length}` + : undefined, + payto_uri: !state.payto_uri ? i18n.str`cannot be empty` : undefined, + credit_amount: !state.credit_amount ? i18n.str`cannot be empty` : undefined, + exchange_url: !state.exchange_url + ? i18n.str`cannot be empty` + : !URL_REGEX.test(state.exchange_url) + ? i18n.str`URL doesn't have the right format` + : undefined, + }; + + const hasErrors = Object.keys(errors).some( + (k) => (errors as any)[k] !== undefined, + ); const submitForm = () => { - if (hasErrors) return Promise.reject() - return onCreate(state as any) - } - - return <div> - <section class="section is-main-section"> - <div class="columns"> - <div class="column" /> - <div class="column is-four-fifths"> - - <FormProvider object={state} valueHandler={setState} errors={errors}> - <InputSelector name="payto_uri" label={i18n`Credited bank account`} - values={accounts} - placeholder={i18n`Select one account`} - tooltip={i18n`Bank account of the merchant where the payment was received`} - /> - <Input<Entity> name="wtid" label={i18n`Wire transfer ID`} help="" tooltip={i18n`unique identifier of the wire transfer used by the exchange, must be 52 characters long`} /> - <Input<Entity> name="exchange_url" - label={i18n`Exchange URL`} - tooltip={i18n`Base URL of the exchange that made the transfer, should have been in the wire transfer subject`} - help="http://exchange.taler:8081/" /> - <InputCurrency<Entity> name="credit_amount" label={i18n`Amount credited`} tooltip={i18n`Actual amount that was wired to the merchant's bank account`} /> - - </FormProvider> - - <div class="buttons is-right mt-5"> - {onBack && <button class="button" onClick={onBack} ><Translate>Cancel</Translate></button>} - <AsyncButton disabled={hasErrors} data-tooltip={ - hasErrors ? i18n`Need to complete marked fields` : 'confirm operation' - } onClick={submitForm} ><Translate>Confirm</Translate></AsyncButton> + if (hasErrors) return Promise.reject(); + return onCreate(state as any); + }; + + return ( + <div> + <section class="section is-main-section"> + <div class="columns"> + <div class="column" /> + <div class="column is-four-fifths"> + <FormProvider + object={state} + valueHandler={setState} + errors={errors} + > + <InputSelector + name="payto_uri" + label={i18n.str`Credited bank account`} + values={accounts} + placeholder={i18n.str`Select one account`} + tooltip={i18n.str`Bank account of the merchant where the payment was received`} + /> + <Input<Entity> + name="wtid" + label={i18n.str`Wire transfer ID`} + help="" + tooltip={i18n.str`unique identifier of the wire transfer used by the exchange, must be 52 characters long`} + /> + <Input<Entity> + name="exchange_url" + label={i18n.str`Exchange URL`} + tooltip={i18n.str`Base URL of the exchange that made the transfer, should have been in the wire transfer subject`} + help="http://exchange.taler:8081/" + /> + <InputCurrency<Entity> + name="credit_amount" + label={i18n.str`Amount credited`} + tooltip={i18n.str`Actual amount that was wired to the merchant's bank account`} + /> + </FormProvider> + + <div class="buttons is-right mt-5"> + {onBack && ( + <button class="button" onClick={onBack}> + <i18n.Translate>Cancel</i18n.Translate> + </button> + )} + <AsyncButton + disabled={hasErrors} + data-tooltip={ + hasErrors + ? i18n.str`Need to complete marked fields` + : "confirm operation" + } + onClick={submitForm} + > + <i18n.Translate>Confirm</i18n.Translate> + </AsyncButton> + </div> </div> - + <div class="column" /> </div> - <div class="column" /> - </div> - </section> - </div> + </section> + </div> + ); } diff --git a/packages/merchant-backoffice-ui/src/paths/instance/transfers/create/index.tsx b/packages/merchant-backoffice-ui/src/paths/instance/transfers/create/index.tsx index 0d3676096..428476337 100644 --- a/packages/merchant-backoffice-ui/src/paths/instance/transfers/create/index.tsx +++ b/packages/merchant-backoffice-ui/src/paths/instance/transfers/create/index.tsx @@ -1,6 +1,6 @@ /* This file is part of GNU Taler - (C) 2021 Taler Systems S.A. + (C) 2021-2024 Taler Systems S.A. GNU Taler is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -15,46 +15,58 @@ */ /** -* -* @author Sebastian Javier Marchano (sebasjm) -*/ + * + * @author Sebastian Javier Marchano (sebasjm) + */ -import { Fragment, h, VNode } from 'preact'; -import { useState } from 'preact/hooks'; +import { TalerError, TalerMerchantApi } from "@gnu-taler/taler-util"; +import { + useTranslationContext +} from "@gnu-taler/web-util/browser"; +import { Fragment, VNode, h } from "preact"; +import { useState } from "preact/hooks"; import { NotificationCard } from "../../../../components/menu/index.js"; -import { MerchantBackend } from "../../../../declaration.js"; -import { useInstanceDetails } from "../../../../hooks/instance.js"; -import { useTransferAPI } from "../../../../hooks/transfer.js"; -import { useTranslator } from '../../../../i18n/index.js'; +import { useSessionContext } from "../../../../context/session.js"; +import { useInstanceBankAccounts } from "../../../../hooks/bank.js"; import { Notification } from "../../../../utils/types.js"; import { CreatePage } from "./CreatePage.js"; -export type Entity = MerchantBackend.Transfers.TransferInformation +export type Entity = TalerMerchantApi.TransferInformation; interface Props { onBack?: () => void; onConfirm: () => void; } -export default function CreateTransfer({onConfirm, onBack}:Props): VNode { - const { informTransfer } = useTransferAPI() - const [notif, setNotif] = useState<Notification | undefined>(undefined) - const i18n = useTranslator() - const instance = useInstanceDetails() - const accounts = !instance.ok ? [] : instance.data.accounts.map(a => a.payto_uri) - - return <> - <NotificationCard notification={notif} /> - <CreatePage - onBack={onBack} - accounts={accounts} - onCreate={(request: MerchantBackend.Transfers.TransferInformation) => { - return informTransfer(request).then(() => onConfirm()).catch((error) => { - setNotif({ - message: i18n`could not inform transfer`, - type: "ERROR", - description: error.message - }) - }) - }} /> - </> -}
\ No newline at end of file +export default function CreateTransfer({ onConfirm, onBack }: Props): VNode { + const { lib } = useSessionContext(); + const { state } = useSessionContext(); + const [notif, setNotif] = useState<Notification | undefined>(undefined); + const { i18n } = useTranslationContext(); + const instance = useInstanceBankAccounts(); + const accounts = + !instance || instance instanceof TalerError || instance.type === "fail" + ? [] + : instance.body.accounts.map((a) => a.payto_uri); + + return ( + <> + <NotificationCard notification={notif} /> + <CreatePage + onBack={onBack} + accounts={accounts} + onCreate={(request: TalerMerchantApi.TransferInformation) => { + return lib.instance + .informWireTransfer(state.token, request) + .then(() => onConfirm()) + .catch((error) => { + setNotif({ + message: i18n.str`could not inform transfer`, + type: "ERROR", + description: error.message, + }); + }); + }} + /> + </> + ); +} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/transfers/list/List.stories.tsx b/packages/merchant-backoffice-ui/src/paths/instance/transfers/list/List.stories.tsx index 94d03a492..def03fe27 100644 --- a/packages/merchant-backoffice-ui/src/paths/instance/transfers/list/List.stories.tsx +++ b/packages/merchant-backoffice-ui/src/paths/instance/transfers/list/List.stories.tsx @@ -1,6 +1,6 @@ /* This file is part of GNU Taler - (C) 2021 Taler Systems S.A. + (C) 2021-2024 Taler Systems S.A. GNU Taler is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -19,7 +19,8 @@ * @author Sebastian Javier Marchano (sebasjm) */ -import { h, VNode, FunctionalComponent } from "preact"; +import { AmountString, PaytoString } from "@gnu-taler/taler-util"; +import { FunctionalComponent, h } from "preact"; import { ListPage as TestedComponent } from "./ListPage.js"; export default { @@ -39,7 +40,7 @@ export default { function createExample<Props>( Component: FunctionalComponent<Props>, - props: Partial<Props> + props: Partial<Props>, ) { const r = (args: any) => <Component {...args} />; r.args = props; @@ -50,8 +51,8 @@ export const Example = createExample(TestedComponent, { transfers: [ { exchange_url: "http://exchange.url/", - credit_amount: "TESTKUDOS:10", - payto_uri: "payto//x-taler-bank/bank:8080/account", + credit_amount: "TESTKUDOS:10" as AmountString, + payto_uri: "payto//x-taler-bank/bank:8080/account" as PaytoString, transfer_serial_id: 123123123, wtid: "!@KJELQKWEJ!L@K#!J@", confirmed: true, @@ -62,8 +63,8 @@ export const Example = createExample(TestedComponent, { }, { exchange_url: "http://exchange.url/", - credit_amount: "TESTKUDOS:10", - payto_uri: "payto//x-taler-bank/bank:8080/account", + credit_amount: "TESTKUDOS:10" as AmountString, + payto_uri: "payto//x-taler-bank/bank:8080/account" as PaytoString, transfer_serial_id: 123123123, wtid: "!@KJELQKWEJ!L@K#!J@", confirmed: true, @@ -74,8 +75,8 @@ export const Example = createExample(TestedComponent, { }, { exchange_url: "http://exchange.url/", - credit_amount: "TESTKUDOS:10", - payto_uri: "payto//x-taler-bank/bank:8080/account", + credit_amount: "TESTKUDOS:10" as AmountString, + payto_uri: "payto//x-taler-bank/bank:8080/account" as PaytoString, transfer_serial_id: 123123123, wtid: "!@KJELQKWEJ!L@K#!J@", confirmed: true, diff --git a/packages/merchant-backoffice-ui/src/paths/instance/transfers/list/ListPage.tsx b/packages/merchant-backoffice-ui/src/paths/instance/transfers/list/ListPage.tsx index 25f9ff95c..22ad0b8d8 100644 --- a/packages/merchant-backoffice-ui/src/paths/instance/transfers/list/ListPage.tsx +++ b/packages/merchant-backoffice-ui/src/paths/instance/transfers/list/ListPage.tsx @@ -1,6 +1,6 @@ /* This file is part of GNU Taler - (C) 2021 Taler Systems S.A. + (C) 2021-2024 Taler Systems S.A. GNU Taler is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -15,19 +15,19 @@ */ /** -* -* @author Sebastian Javier Marchano (sebasjm) -*/ + * + * @author Sebastian Javier Marchano (sebasjm) + */ -import { h, VNode } from 'preact'; +import { useTranslationContext } from "@gnu-taler/web-util/browser"; +import { h, VNode } from "preact"; import { FormProvider } from "../../../../components/form/FormProvider.js"; import { InputSelector } from "../../../../components/form/InputSelector.js"; -import { MerchantBackend } from "../../../../declaration.js"; -import { Translate, useTranslator } from '../../../../i18n/index.js'; import { CardTable } from "./Table.js"; +import { TalerMerchantApi } from "@gnu-taler/taler-util"; export interface Props { - transfers: MerchantBackend.Transfers.TransferDetails[]; + transfers: TalerMerchantApi.TransferDetails[]; onLoadMoreBefore?: () => void; onLoadMoreAfter?: () => void; onShowAll: () => void; @@ -43,47 +43,95 @@ export interface Props { onDelete: () => void; } -export function ListPage({ payTo, onChangePayTo, transfers, onCreate, onDelete, accounts, onLoadMoreBefore, onLoadMoreAfter, isAllTransfers, isNonVerifiedTransfers, isVerifiedTransfers, onShowAll, onShowUnverified, onShowVerified }: Props): VNode { - const form = { payto_uri: payTo } +export function ListPage({ + payTo, + onChangePayTo, + transfers, + onCreate, + onDelete, + accounts, + onLoadMoreBefore, + onLoadMoreAfter, + isAllTransfers, + isNonVerifiedTransfers, + isVerifiedTransfers, + onShowAll, + onShowUnverified, + onShowVerified, +}: Props): VNode { + const form = { payto_uri: payTo }; - const i18n = useTranslator(); - return <section class="section is-main-section"> - <div class="columns"> - <div class="column" /> - <div class="column is-10"> - <FormProvider object={form} valueHandler={(updater) => onChangePayTo(updater(form).payto_uri)}> - <InputSelector name="payto_uri" label={i18n`Address`} - values={accounts} - placeholder={i18n`Select one account`} - tooltip={i18n`filter by account address`} /> - </FormProvider> + const { i18n } = useTranslationContext(); + return ( + <section class="section is-main-section"> + <div class="columns"> + <div class="column" /> + <div class="column is-10"> + <FormProvider + object={form} + valueHandler={(updater) => onChangePayTo(updater(form).payto_uri)} + > + <InputSelector + name="payto_uri" + label={i18n.str`Account URI`} + values={accounts} + fromStr={(d) => { + const idx = accounts.indexOf(d) + if (idx === -1) return undefined; + return d + }} + placeholder={i18n.str`Select one account`} + tooltip={i18n.str`filter by account address`} + /> + </FormProvider> + </div> + <div class="column" /> + </div> + <div class="tabs"> + <ul> + <li class={isAllTransfers ? "is-active" : ""}> + <div + class="has-tooltip-right" + data-tooltip={i18n.str`remove all filters`} + > + <a onClick={onShowAll}> + <i18n.Translate>All</i18n.Translate> + </a> + </div> + </li> + <li class={isVerifiedTransfers ? "is-active" : ""}> + <div + class="has-tooltip-right" + data-tooltip={i18n.str`only show wire transfers confirmed by the merchant`} + > + <a onClick={onShowVerified}> + <i18n.Translate>Verified</i18n.Translate> + </a> + </div> + </li> + <li class={isNonVerifiedTransfers ? "is-active" : ""}> + <div + class="has-tooltip-right" + data-tooltip={i18n.str`only show wire transfers claimed by the exchange`} + > + <a onClick={onShowUnverified}> + <i18n.Translate>Unverified</i18n.Translate> + </a> + </div> + </li> + </ul> </div> - <div class="column" /> - </div> - <div class="tabs"> - <ul> - <li class={isAllTransfers ? 'is-active' : ''}> - <div class="has-tooltip-right" data-tooltip={i18n`remove all filters`}> - <a onClick={onShowAll}><Translate>All</Translate></a> - </div> - </li> - <li class={isVerifiedTransfers ? 'is-active' : ''}> - <div class="has-tooltip-right" data-tooltip={i18n`only show wire transfers confirmed by the merchant`}> - <a onClick={onShowVerified}><Translate>Verified</Translate></a> - </div> - </li> - <li class={isNonVerifiedTransfers ? 'is-active' : ''}> - <div class="has-tooltip-right" data-tooltip={i18n`only show wire transfers claimed by the exchange`}> - <a onClick={onShowUnverified}><Translate>Unverified</Translate></a> - </div> - </li> - </ul> - </div> - <CardTable transfers={transfers.map(o => ({ ...o, id: String(o.transfer_serial_id) }))} - accounts={accounts} - onCreate={onCreate} - onDelete={onDelete} - onLoadMoreBefore={onLoadMoreBefore} hasMoreBefore={!onLoadMoreBefore} - onLoadMoreAfter={onLoadMoreAfter} hasMoreAfter={!onLoadMoreAfter} /> - </section>; + <CardTable + transfers={transfers.map((o) => ({ + ...o, + id: String(o.transfer_serial_id), + }))} + accounts={accounts} + onCreate={onCreate} + onDelete={onDelete} + onLoadMoreBefore={onLoadMoreBefore} + onLoadMoreAfter={onLoadMoreAfter} + /> + </section> + ); } diff --git a/packages/merchant-backoffice-ui/src/paths/instance/transfers/list/Table.tsx b/packages/merchant-backoffice-ui/src/paths/instance/transfers/list/Table.tsx index 26cb1ff83..b9235c669 100644 --- a/packages/merchant-backoffice-ui/src/paths/instance/transfers/list/Table.tsx +++ b/packages/merchant-backoffice-ui/src/paths/instance/transfers/list/Table.tsx @@ -1,6 +1,6 @@ /* This file is part of GNU Taler - (C) 2021 Taler Systems S.A. + (C) 2021-2024 Taler Systems S.A. GNU Taler is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -19,13 +19,14 @@ * @author Sebastian Javier Marchano (sebasjm) */ +import { TalerMerchantApi } from "@gnu-taler/taler-util"; +import { useTranslationContext } from "@gnu-taler/web-util/browser"; import { format } from "date-fns"; import { h, VNode } from "preact"; import { StateUpdater, useState } from "preact/hooks"; -import { MerchantBackend, WithId } from "../../../../declaration.js"; -import { Translate, useTranslator } from "../../../../i18n/index.js"; +import { datetimeFormatForSettings, usePreference } from "../../../../hooks/preference.js"; -type Entity = MerchantBackend.Transfers.TransferDetails & WithId; +type Entity = TalerMerchantApi.TransferDetails & WithId; interface Props { transfers: Entity[]; @@ -33,8 +34,6 @@ interface Props { onCreate: () => void; accounts: string[]; onLoadMoreBefore?: () => void; - hasMoreBefore?: boolean; - hasMoreAfter?: boolean; onLoadMoreAfter?: () => void; } @@ -44,24 +43,25 @@ export function CardTable({ onDelete, onLoadMoreAfter, onLoadMoreBefore, - hasMoreAfter, - hasMoreBefore, }: Props): VNode { const [rowSelection, rowSelectionHandler] = useState<string[]>([]); - const i18n = useTranslator(); + const { i18n } = useTranslationContext(); return ( <div class="card has-table"> <header class="card-header"> <p class="card-header-title"> <span class="icon"> - <i class="mdi mdi-bank" /> + <i class="mdi mdi-arrow-left-right" /> </span> - <Translate>Transfers</Translate> + <i18n.Translate>Transfers</i18n.Translate> </p> <div class="card-header-icon" aria-label="more options"> - <span class="has-tooltip-left" data-tooltip={i18n`add new transfer`}> + <span + class="has-tooltip-left" + data-tooltip={i18n.str`add new transfer`} + > <button class="button is-info" type="button" onClick={onCreate}> <span class="icon is-small"> <i class="mdi mdi-plus mdi-36px" /> @@ -81,8 +81,6 @@ export function CardTable({ rowSelectionHandler={rowSelectionHandler} onLoadMoreAfter={onLoadMoreAfter} onLoadMoreBefore={onLoadMoreBefore} - hasMoreAfter={hasMoreAfter} - hasMoreBefore={hasMoreBefore} /> ) : ( <EmptyTable /> @@ -99,60 +97,51 @@ interface TableProps { onDelete: (id: Entity) => void; rowSelectionHandler: StateUpdater<string[]>; onLoadMoreBefore?: () => void; - hasMoreBefore?: boolean; - hasMoreAfter?: boolean; onLoadMoreAfter?: () => void; } -function toggleSelected<T>(id: T): (prev: T[]) => T[] { - return (prev: T[]): T[] => - prev.indexOf(id) == -1 ? [...prev, id] : prev.filter((e) => e != id); -} - function Table({ instances, onLoadMoreAfter, onDelete, onLoadMoreBefore, - hasMoreAfter, - hasMoreBefore, }: TableProps): VNode { - const i18n = useTranslator(); + const { i18n } = useTranslationContext(); + const [settings] = usePreference(); return ( <div class="table-container"> {onLoadMoreBefore && ( <button class="button is-fullwidth" - data-tooltip={i18n`load more transfers before the first one`} - disabled={!hasMoreBefore} + data-tooltip={i18n.str`load more transfers before the first one`} onClick={onLoadMoreBefore} > - <Translate>load newer transfers</Translate> + <i18n.Translate>load first page</i18n.Translate> </button> )} <table class="table is-fullwidth is-striped is-hoverable is-fullwidth"> <thead> <tr> <th> - <Translate>ID</Translate> + <i18n.Translate>ID</i18n.Translate> </th> <th> - <Translate>Credit</Translate> + <i18n.Translate>Credit</i18n.Translate> </th> <th> - <Translate>Address</Translate> + <i18n.Translate>Address</i18n.Translate> </th> <th> - <Translate>Exchange URL</Translate> + <i18n.Translate>Exchange URL</i18n.Translate> </th> <th> - <Translate>Confirmed</Translate> + <i18n.Translate>Confirmed</i18n.Translate> </th> <th> - <Translate>Verified</Translate> + <i18n.Translate>Verified</i18n.Translate> </th> <th> - <Translate>Executed at</Translate> + <i18n.Translate>Executed at</i18n.Translate> </th> <th /> </tr> @@ -165,23 +154,23 @@ function Table({ <td>{i.credit_amount}</td> <td>{i.payto_uri}</td> <td>{i.exchange_url}</td> - <td>{i.confirmed ? i18n`yes` : i18n`no`}</td> - <td>{i.verified ? i18n`yes` : i18n`no`}</td> + <td>{i.confirmed ? i18n.str`yes` : i18n.str`no`}</td> + <td>{i.verified ? i18n.str`yes` : i18n.str`no`}</td> <td> {i.execution_time ? i.execution_time.t_s == "never" - ? i18n`never` + ? i18n.str`never` : format( - i.execution_time.t_s * 1000, - "yyyy/MM/dd HH:mm:ss" - ) - : i18n`unknown`} + i.execution_time.t_s * 1000, + datetimeFormatForSettings(settings), + ) + : i18n.str`unknown`} </td> <td> {i.verified === undefined ? ( <button class="button is-danger is-small has-tooltip-left" - data-tooltip={i18n`delete selected transfer from the database`} + data-tooltip={i18n.str`delete selected transfer from the database`} onClick={() => onDelete(i)} > Delete @@ -196,11 +185,10 @@ function Table({ {onLoadMoreAfter && ( <button class="button is-fullwidth" - data-tooltip={i18n`load more transfer after the last one`} - disabled={!hasMoreAfter} + data-tooltip={i18n.str`load more transfers after the last one`} onClick={onLoadMoreAfter} > - <Translate>load older transfers</Translate> + <i18n.Translate>load next page</i18n.Translate> </button> )} </div> @@ -208,17 +196,18 @@ function Table({ } function EmptyTable(): VNode { + const { i18n } = useTranslationContext(); return ( <div class="content has-text-grey has-text-centered"> <p> <span class="icon is-large"> - <i class="mdi mdi-emoticon-sad mdi-48px" /> + <i class="mdi mdi-magnify mdi-48px" /> </span> </p> <p> - <Translate> + <i18n.Translate> There is no transfer yet, add more pressing the + sign - </Translate> + </i18n.Translate> </p> </div> ); diff --git a/packages/merchant-backoffice-ui/src/paths/instance/transfers/list/index.tsx b/packages/merchant-backoffice-ui/src/paths/instance/transfers/list/index.tsx index c3079c136..8b4d1f3cb 100644 --- a/packages/merchant-backoffice-ui/src/paths/instance/transfers/list/index.tsx +++ b/packages/merchant-backoffice-ui/src/paths/instance/transfers/list/index.tsx @@ -1,6 +1,6 @@ /* This file is part of GNU Taler - (C) 2021 Taler Systems S.A. + (C) 2021-2024 Taler Systems S.A. GNU Taler is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -15,71 +15,98 @@ */ /** -* -* @author Sebastian Javier Marchano (sebasjm) -*/ + * + * @author Sebastian Javier Marchano (sebasjm) + */ -import { h, VNode } from 'preact'; -import { useState } from 'preact/hooks'; +import { HttpStatusCode, TalerError, assertUnreachable } from "@gnu-taler/taler-util"; +import { VNode, h } from "preact"; +import { useEffect, useState } from "preact/hooks"; +import { ErrorLoadingMerchant } from "../../../../components/ErrorLoadingMerchant.js"; import { Loading } from "../../../../components/exception/loading.js"; -import { MerchantBackend } from "../../../../declaration.js"; -import { HttpError } from "../../../../hooks/backend.js"; -import { useInstanceDetails } from "../../../../hooks/instance.js"; +import { useInstanceBankAccounts } from "../../../../hooks/bank.js"; import { useInstanceTransfers } from "../../../../hooks/transfer.js"; +import { LoginPage } from "../../../login/index.js"; import { ListPage } from "./ListPage.js"; +import { NotFoundPageOrAdminCreate } from "../../../notfound/index.js"; interface Props { - onUnauthorized: () => VNode; - onLoadError: (error: HttpError) => VNode; - onNotFound: () => VNode; onCreate: () => void; } interface Form { - verified?: 'yes' | 'no'; + verified?: boolean; payto_uri?: string; } -export default function ListTransfer({ onUnauthorized, onLoadError, onCreate, onNotFound }: Props): VNode { - const [form, setForm] = useState<Form>({ payto_uri: '' }) - const setFilter = (s?: 'yes' | 'no') => setForm({ ...form, verified: s }) +export default function ListTransfer({ + onCreate, +}: Props): VNode { + const setFilter = (s?: boolean) => setForm({ ...form, verified: s }); - const [position, setPosition] = useState<string | undefined>(undefined) + const [position, setPosition] = useState<string | undefined>(undefined); - const instance = useInstanceDetails() - const accounts = !instance.ok ? [] : instance.data.accounts.map(a => a.payto_uri) + const instance = useInstanceBankAccounts(); + const accounts = !instance || (instance instanceof TalerError) || instance.type === "fail" + ? [] + : instance.body.accounts.map((a) => a.payto_uri); + const [form, setForm] = useState<Form>({ payto_uri: "" }); - const isVerifiedTransfers = form.verified === 'yes' - const isNonVerifiedTransfers = form.verified === 'no' - const isAllTransfers = form.verified === undefined + const shoulUseDefaultAccount = accounts.length === 1 + useEffect(() => { + if (shoulUseDefaultAccount) { + setForm({...form, payto_uri: accounts[0]}) + } + }, [shoulUseDefaultAccount]) - const result = useInstanceTransfers({ - position, - payto_uri: form.payto_uri === '' ? undefined : form.payto_uri, - verified: form.verified, - }, (id) => setPosition(id)) + const isVerifiedTransfers = form.verified === true; + const isNonVerifiedTransfers = form.verified === false; + const isAllTransfers = form.verified === undefined; - if (result.clientError && result.isUnauthorized) return onUnauthorized() - if (result.clientError && result.isNotfound) return onNotFound() - if (result.loading) return <Loading /> - if (!result.ok) return onLoadError(result) + const result = useInstanceTransfers( + { + position, + payto_uri: form.payto_uri === "" ? undefined : form.payto_uri, + verified: form.verified, + }, + (id) => setPosition(id), + ); - return <ListPage - accounts={accounts} - transfers={result.data.transfers} - onLoadMoreBefore={result.isReachingStart ? result.loadMorePrev : undefined} - onLoadMoreAfter={result.isReachingEnd ? result.loadMore : undefined} - onCreate={onCreate} - onDelete={() => {null}} - // position={position} setPosition={setPosition} - onShowAll={() => setFilter(undefined)} - onShowUnverified={() => setFilter('no')} - onShowVerified={() => setFilter('yes')} - isAllTransfers={isAllTransfers} - isVerifiedTransfers={isVerifiedTransfers} - isNonVerifiedTransfers={isNonVerifiedTransfers} - payTo={form.payto_uri} - onChangePayTo={(p) => setForm(v => ({ ...v, payto_uri: p }))} - /> + if (!result) return <Loading />; + if (result instanceof TalerError) { + return <ErrorLoadingMerchant error={result} />; + } + if (result.type === "fail") { + switch (result.case) { + case HttpStatusCode.Unauthorized: { + return <LoginPage /> + } + case HttpStatusCode.NotFound: { + return <NotFoundPageOrAdminCreate />; + } + default: { + assertUnreachable(result); + } + } + } + return ( + <ListPage + accounts={accounts} + transfers={result.body} + onLoadMoreBefore={result.isFirstPage ? undefined: result.loadFirst } + onLoadMoreAfter={result.isLastPage ? undefined : result.loadNext} + onCreate={onCreate} + onDelete={() => { + null; + }} + onShowAll={() => setFilter(undefined)} + onShowUnverified={() => setFilter(false)} + onShowVerified={() => setFilter(true)} + isAllTransfers={isAllTransfers} + isVerifiedTransfers={isVerifiedTransfers} + isNonVerifiedTransfers={isNonVerifiedTransfers} + payTo={form.payto_uri} + onChangePayTo={(p) => setForm((v) => ({ ...v, payto_uri: p }))} + /> + ); } - diff --git a/packages/merchant-backoffice-ui/src/paths/instance/transfers/update/index.tsx b/packages/merchant-backoffice-ui/src/paths/instance/transfers/update/index.tsx index caa808693..719f99209 100644 --- a/packages/merchant-backoffice-ui/src/paths/instance/transfers/update/index.tsx +++ b/packages/merchant-backoffice-ui/src/paths/instance/transfers/update/index.tsx @@ -1,6 +1,6 @@ /* This file is part of GNU Taler - (C) 2021 Taler Systems S.A. + (C) 2021-2024 Taler Systems S.A. GNU Taler is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -15,12 +15,12 @@ */ /** -* -* @author Sebastian Javier Marchano (sebasjm) -*/ + * + * @author Sebastian Javier Marchano (sebasjm) + */ -import { h, VNode } from 'preact'; +import { h, VNode } from "preact"; -export default function UpdateTransfer():VNode { - return <div>order transfer page</div> -}
\ No newline at end of file +export default function UpdateTransfer(): VNode { + return <div>order transfer page</div>; +} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/update/Update.stories.tsx b/packages/merchant-backoffice-ui/src/paths/instance/update/Update.stories.tsx index 8c4717275..5bd12e4e9 100644 --- a/packages/merchant-backoffice-ui/src/paths/instance/update/Update.stories.tsx +++ b/packages/merchant-backoffice-ui/src/paths/instance/update/Update.stories.tsx @@ -1,6 +1,6 @@ /* This file is part of GNU Taler - (C) 2021 Taler Systems S.A. + (C) 2021-2024 Taler Systems S.A. GNU Taler is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -19,7 +19,7 @@ * @author Sebastian Javier Marchano (sebasjm) */ -import { h, VNode, FunctionalComponent } from "preact"; +import { FunctionalComponent, h } from "preact"; import { UpdatePage as TestedComponent } from "./UpdatePage.js"; export default { @@ -33,7 +33,7 @@ export default { function createExample<Props>( Component: FunctionalComponent<Props>, - props: Partial<Props> + props: Partial<Props>, ) { const r = (args: any) => <Component {...args} />; r.args = props; @@ -42,19 +42,17 @@ function createExample<Props>( export const Example = createExample(TestedComponent, { selected: { - accounts: [], name: "name", auth: { method: "external" }, address: {}, + user_type: "business", + use_stefan: true, jurisdiction: {}, - default_max_deposit_fee: "TESTKUDOS:2", - default_max_wire_fee: "TESTKUDOS:1", default_pay_delay: { - d_us: 1000000, + d_us: 1000 * 1000, //one second }, - default_wire_fee_amortization: 1, default_wire_transfer_delay: { - d_us: 100000, + d_us: 1000 * 1000, //one second }, merchant_pub: "ASDWQEKASJDKSADJ", }, diff --git a/packages/merchant-backoffice-ui/src/paths/instance/update/UpdatePage.tsx b/packages/merchant-backoffice-ui/src/paths/instance/update/UpdatePage.tsx index b5328249a..cde58967f 100644 --- a/packages/merchant-backoffice-ui/src/paths/instance/update/UpdatePage.tsx +++ b/packages/merchant-backoffice-ui/src/paths/instance/update/UpdatePage.tsx @@ -1,6 +1,6 @@ /* This file is part of GNU Taler - (C) 2021 Taler Systems S.A. + (C) 2021-2024 Taler Systems S.A. GNU Taler is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -19,137 +19,101 @@ * @author Sebastian Javier Marchano (sebasjm) */ -import { h, VNode } from "preact"; +import { Duration, TalerMerchantApi } from "@gnu-taler/taler-util"; +import { useTranslationContext } from "@gnu-taler/web-util/browser"; +import { VNode, h } from "preact"; import { useState } from "preact/hooks"; -import * as yup from "yup"; import { AsyncButton } from "../../../components/exception/AsyncButton.js"; import { - FormProvider, FormErrors, + FormProvider, } from "../../../components/form/FormProvider.js"; -import { UpdateTokenModal } from "../../../components/modal/index.js"; -import { useInstanceContext } from "../../../context/instance.js"; -import { MerchantBackend } from "../../../declaration.js"; -import { Translate, useTranslator } from "../../../i18n/index.js"; import { DefaultInstanceFormFields } from "../../../components/instance/DefaultInstanceFormFields.js"; -import { PAYTO_REGEX } from "../../../utils/constants.js"; -import { Amounts } from "@gnu-taler/taler-util"; +import { useSessionContext } from "../../../context/session.js"; import { undefinedIfEmpty } from "../../../utils/table.js"; -type Entity = MerchantBackend.Instances.InstanceReconfigurationMessage & { - auth_token?: string; +export type Entity = Omit<Omit<TalerMerchantApi.InstanceReconfigurationMessage, "default_pay_delay">, "default_wire_transfer_delay"> & { + default_pay_delay: Duration, + default_wire_transfer_delay: Duration, }; -//MerchantBackend.Instances.InstanceAuthConfigurationMessage +//TalerMerchantApi.InstanceAuthConfigurationMessage interface Props { - onUpdate: (d: Entity) => void; - onChangeAuth: ( - d: MerchantBackend.Instances.InstanceAuthConfigurationMessage - ) => Promise<void>; - selected: MerchantBackend.Instances.QueryInstancesResponse; + onUpdate: (d: TalerMerchantApi.InstanceReconfigurationMessage) => void; + selected: TalerMerchantApi.QueryInstancesResponse; isLoading: boolean; onBack: () => void; } function convert( - from: MerchantBackend.Instances.QueryInstancesResponse + from: TalerMerchantApi.QueryInstancesResponse, ): Entity { - const { accounts, ...rest } = from; - const payto_uris = accounts.filter((a) => a.active).map((a) => a.payto_uri); + const { default_pay_delay, default_wire_transfer_delay, ...rest } = from; + const defaults = { - default_wire_fee_amortization: 1, - default_pay_delay: { d_us: 2 * 1000 * 1000 * 60 * 60 }, //two hours - default_wire_transfer_delay: { d_us: 2 * 1000 * 1000 * 60 * 60 * 2 }, //two hours + use_stefan: false, + default_pay_delay: Duration.fromTalerProtocolDuration(default_pay_delay), + default_wire_transfer_delay: Duration.fromTalerProtocolDuration(default_wire_transfer_delay), }; - return { ...defaults, ...rest, payto_uris }; -} - -function getTokenValuePart(t?: string): string | undefined { - if (!t) return t; - const match = /secret-token:(.*)/.exec(t); - if (!match || !match[1]) return undefined; - return match[1]; + return { ...defaults, ...rest }; } export function UpdatePage({ onUpdate, - onChangeAuth, selected, onBack, }: Props): VNode { - const { id, token } = useInstanceContext(); - const currentTokenValue = getTokenValuePart(token); - - function updateToken(token: string | undefined | null) { - const value = - token && token.startsWith("secret-token:") - ? token.substring("secret-token:".length) - : token; - - if (!token) { - onChangeAuth({ method: "external" }); - } else { - onChangeAuth({ method: "token", token: `secret-token:${value}` }); - } - } + const { state } = useSessionContext(); const [value, valueHandler] = useState<Partial<Entity>>(convert(selected)); - const i18n = useTranslator(); + const { i18n } = useTranslationContext(); const errors: FormErrors<Entity> = { - name: !value.name ? i18n`required` : undefined, - payto_uris: - !value.payto_uris || !value.payto_uris.length - ? i18n`required` - : undefinedIfEmpty( - value.payto_uris.map((p) => { - return !PAYTO_REGEX.test(p) ? i18n`is not valid` : undefined; - }) - ), - default_max_deposit_fee: !value.default_max_deposit_fee - ? i18n`required` - : !Amounts.parse(value.default_max_deposit_fee) - ? i18n`invalid format` - : undefined, - default_max_wire_fee: !value.default_max_wire_fee - ? i18n`required` - : !Amounts.parse(value.default_max_wire_fee) - ? i18n`invalid format` - : undefined, - default_wire_fee_amortization: - value.default_wire_fee_amortization === undefined - ? i18n`required` - : isNaN(value.default_wire_fee_amortization) - ? i18n`is not a number` - : value.default_wire_fee_amortization < 1 - ? i18n`must be 1 or greater` + name: !value.name ? i18n.str`required` : undefined, + user_type: !value.user_type + ? i18n.str`required` + : value.user_type !== "business" && value.user_type !== "individual" + ? i18n.str`should be business or individual` : undefined, - default_pay_delay: !value.default_pay_delay ? i18n`required` : undefined, + default_pay_delay: !value.default_pay_delay + ? i18n.str`required` + : !!value.default_wire_transfer_delay && + value.default_wire_transfer_delay.d_ms !== "forever" && + value.default_pay_delay.d_ms !== "forever" && + value.default_pay_delay.d_ms > value.default_wire_transfer_delay.d_ms ? + i18n.str`pay delay can't be greater than wire transfer delay` : undefined, default_wire_transfer_delay: !value.default_wire_transfer_delay - ? i18n`required` + ? i18n.str`required` : undefined, address: undefinedIfEmpty({ address_lines: value.address?.address_lines && value.address?.address_lines.length > 7 - ? i18n`max 7 lines` + ? i18n.str`max 7 lines` : undefined, }), jurisdiction: undefinedIfEmpty({ address_lines: value.address?.address_lines && value.address?.address_lines.length > 7 - ? i18n`max 7 lines` + ? i18n.str`max 7 lines` : undefined, }), }; const hasErrors = Object.keys(errors).some( - (k) => (errors as any)[k] !== undefined + (k) => (errors as any)[k] !== undefined, ); + const submit = async (): Promise<void> => { - await onUpdate(value as Entity); + const { default_pay_delay, default_wire_transfer_delay, ...rest } = value as Required<Entity>; + const result: TalerMerchantApi.InstanceReconfigurationMessage = { + default_pay_delay: Duration.toTalerProtocolDuration(default_pay_delay), + default_wire_transfer_delay: Duration.toTalerProtocolDuration(default_wire_transfer_delay), + ...rest, + } + await onUpdate(result); }; - const [active, setActive] = useState(false); + // const [active, setActive] = useState(false); return ( <div> @@ -160,56 +124,14 @@ export function UpdatePage({ <div class="level-left"> <div class="level-item"> <span class="is-size-4"> - <Translate>Instance id</Translate>: <b>{id}</b> + <i18n.Translate>Instance id</i18n.Translate>: <b>{state.instance}</b> </span> </div> </div> - <div class="level-right"> - <div class="level-item"> - <h1 class="title"> - <button - class="button is-danger" - data-tooltip={i18n`Change the authorization method use for this instance.`} - onClick={(): void => { - setActive(!active); - }} - > - <div class="icon is-left"> - <i class="mdi mdi-lock-reset" /> - </div> - <span> - <Translate>Manage access token</Translate> - </span> - </button> - </h1> - </div> - </div> </div> </div> </section> - <div class="columns"> - <div class="column" /> - <div class="column is-four-fifths"> - {active && ( - <UpdateTokenModal - oldToken={currentTokenValue} - onCancel={() => { - setActive(false); - }} - onClear={() => { - updateToken(null); - setActive(false); - }} - onConfirm={(newToken) => { - updateToken(newToken); - setActive(false); - }} - /> - )} - </div> - <div class="column" /> - </div> <hr /> <div class="columns"> @@ -229,19 +151,19 @@ export function UpdatePage({ onClick={onBack} data-tooltip="cancel operation" > - <Translate>Cancel</Translate> + <i18n.Translate>Cancel</i18n.Translate> </button> <AsyncButton onClick={submit} data-tooltip={ hasErrors - ? i18n`Need to complete marked fields` + ? i18n.str`Need to complete marked fields` : "confirm operation" } disabled={hasErrors} > - <Translate>Confirm</Translate> + <i18n.Translate>Confirm</i18n.Translate> </AsyncButton> </div> </div> diff --git a/packages/merchant-backoffice-ui/src/paths/instance/update/index.tsx b/packages/merchant-backoffice-ui/src/paths/instance/update/index.tsx index c0780fadf..9da7f7efb 100644 --- a/packages/merchant-backoffice-ui/src/paths/instance/update/index.tsx +++ b/packages/merchant-backoffice-ui/src/paths/instance/update/index.tsx @@ -1,6 +1,6 @@ /* This file is part of GNU Taler - (C) 2021 Taler Systems S.A. + (C) 2021-2024 Taler Systems S.A. GNU Taler is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software @@ -13,69 +13,80 @@ You should have received a copy of the GNU General Public License along with GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> */ -import { Fragment, h, VNode } from "preact"; +import { HttpStatusCode, TalerError, TalerMerchantApi, TalerMerchantInstanceHttpClient, TalerMerchantManagementResultByMethod, assertUnreachable } from "@gnu-taler/taler-util"; +import { + useTranslationContext +} from "@gnu-taler/web-util/browser"; +import { Fragment, VNode, h } from "preact"; import { useState } from "preact/hooks"; +import { ErrorLoadingMerchant } from "../../../components/ErrorLoadingMerchant.js"; import { Loading } from "../../../components/exception/loading.js"; import { NotificationCard } from "../../../components/menu/index.js"; -import { useInstanceContext } from "../../../context/instance.js"; -import { MerchantBackend } from "../../../declaration.js"; -import { HttpError, HttpResponse } from "../../../hooks/backend.js"; +import { useSessionContext } from "../../../context/session.js"; import { - useInstanceAPI, useInstanceDetails, useManagedInstanceDetails, - useManagementAPI, } from "../../../hooks/instance.js"; -import { useTranslator } from "../../../i18n/index.js"; import { Notification } from "../../../utils/types.js"; +import { LoginPage } from "../../login/index.js"; +import { NotFoundPageOrAdminCreate } from "../../notfound/index.js"; import { UpdatePage } from "./UpdatePage.js"; export interface Props { onBack: () => void; onConfirm: () => void; - onUnauthorized: () => VNode; - onNotFound: () => VNode; - onLoadError: (e: HttpError) => VNode; - onUpdateError: (e: HttpError) => void; + // onUnauthorized: () => VNode; + // onNotFound: () => VNode; + // onLoadError: (e: HttpError<TalerErrorDetail>) => VNode; + // onUpdateError: (e: HttpError<TalerErrorDetail>) => void; } export default function Update(props: Props): VNode { - const { updateInstance, clearToken, setNewToken } = useInstanceAPI(); + const { lib } = useSessionContext(); + const updateInstance = lib.instance.updateCurrentInstance.bind(lib.instance) const result = useInstanceDetails(); - return CommonUpdate(props, result, updateInstance, clearToken, setNewToken); + return CommonUpdate(props, result, updateInstance,); } export function AdminUpdate(props: Props & { instanceId: string }): VNode { - const { updateInstance, clearToken, setNewToken } = useManagementAPI( - props.instanceId - ); + const { lib } = useSessionContext(); + const t = lib.subInstanceApi(props.instanceId).instance; + const updateInstance = t.updateCurrentInstance.bind(t) const result = useManagedInstanceDetails(props.instanceId); - return CommonUpdate(props, result, updateInstance, clearToken, setNewToken); + return CommonUpdate(props, result, updateInstance,); } + function CommonUpdate( { onBack, onConfirm, - onLoadError, - onNotFound, - onUpdateError, - onUnauthorized, }: Props, - result: HttpResponse<MerchantBackend.Instances.QueryInstancesResponse>, - updateInstance: any, - clearToken: any, - setNewToken: any + result: TalerMerchantManagementResultByMethod<"getInstanceDetails"> | TalerError | undefined, + updateInstance: typeof TalerMerchantInstanceHttpClient.prototype.updateCurrentInstance, ): VNode { - const { changeToken } = useInstanceContext(); const [notif, setNotif] = useState<Notification | undefined>(undefined); - const i18n = useTranslator(); + const { i18n } = useTranslationContext(); + const { state } = useSessionContext(); - if (result.clientError && result.isUnauthorized) return onUnauthorized(); - if (result.clientError && result.isNotfound) return onNotFound(); - if (result.loading) return <Loading />; - if (!result.ok) return onLoadError(result); + if (!result) return <Loading /> + if (result instanceof TalerError) { + return <ErrorLoadingMerchant error={result} /> + } + if (result.type === "fail") { + switch(result.case) { + case HttpStatusCode.Unauthorized: { + return <LoginPage /> + } + case HttpStatusCode.NotFound: { + return <NotFoundPageOrAdminCreate />; + } + default: { + assertUnreachable(result) + } + } + } return ( <Fragment> @@ -83,30 +94,23 @@ function CommonUpdate( <UpdatePage onBack={onBack} isLoading={false} - selected={result.data} + selected={result.body} onUpdate={( - d: MerchantBackend.Instances.InstanceReconfigurationMessage + d: TalerMerchantApi.InstanceReconfigurationMessage, ): Promise<void> => { - return updateInstance(d) + if (state.status !== "loggedIn") { + return Promise.resolve(); + } + return updateInstance(state.token, d) .then(onConfirm) .catch((error: Error) => setNotif({ - message: i18n`Failed to create instance`, + message: i18n.str`Failed to update instance`, type: "ERROR", description: error.message, - }) + }), ); }} - onChangeAuth={( - d: MerchantBackend.Instances.InstanceAuthConfigurationMessage - ): Promise<void> => { - const apiCall = - d.method === "external" ? clearToken() : setNewToken(d.token!); - return apiCall - .then(() => changeToken(d.token)) - .then(onConfirm) - .catch(onUpdateError); - }} /> </Fragment> ); diff --git a/packages/merchant-backoffice-ui/src/paths/instance/webhooks/create/Create.stories.tsx b/packages/merchant-backoffice-ui/src/paths/instance/webhooks/create/Create.stories.tsx new file mode 100644 index 000000000..2e2a58b33 --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/webhooks/create/Create.stories.tsx @@ -0,0 +1,28 @@ +/* + This file is part of GNU Taler + (C) 2021-2024 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +/** + * + * @author Sebastian Javier Marchano (sebasjm) + */ + +import { h, VNode, FunctionalComponent } from "preact"; +import { CreatePage as TestedComponent } from "./CreatePage.js"; + +export default { + title: "Pages/Webhooks/Create", + component: TestedComponent, +}; diff --git a/packages/merchant-backoffice-ui/src/paths/instance/webhooks/create/CreatePage.tsx b/packages/merchant-backoffice-ui/src/paths/instance/webhooks/create/CreatePage.tsx new file mode 100644 index 000000000..8792aabea --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/webhooks/create/CreatePage.tsx @@ -0,0 +1,179 @@ +/* + This file is part of GNU Taler + (C) 2021-2024 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +/** + * + * @author Sebastian Javier Marchano (sebasjm) + */ + +import { useTranslationContext } from "@gnu-taler/web-util/browser"; +import { Fragment, h, VNode } from "preact"; +import { useState } from "preact/hooks"; +import { AsyncButton } from "../../../../components/exception/AsyncButton.js"; +import { + FormErrors, + FormProvider, +} from "../../../../components/form/FormProvider.js"; +import { Input } from "../../../../components/form/Input.js"; +import { InputSelector } from "../../../../components/form/InputSelector.js"; +import { TalerMerchantApi } from "@gnu-taler/taler-util"; + +type Entity = TalerMerchantApi.WebhookAddDetails; + +interface Props { + onCreate: (d: Entity) => Promise<void>; + onBack?: () => void; +} + +const validMethod = ["GET", "POST", "PUT", "PATCH", "HEAD"]; + +export function CreatePage({ onCreate, onBack }: Props): VNode { + const { i18n } = useTranslationContext(); + + const [state, setState] = useState<Partial<Entity>>({}); + + const errors: FormErrors<Entity> = { + webhook_id: !state.webhook_id ? i18n.str`required` : undefined, + event_type: !state.event_type ? i18n.str`required` + : state.event_type !== "pay" && state.event_type !== "refund" ? i18n.str`it should be "pay" or "refund"` + : undefined, + http_method: !state.http_method + ? i18n.str`required` + : !validMethod.includes(state.http_method) + ? i18n.str`should be one of '${validMethod.join(", ")}'` + : undefined, + url: !state.url ? i18n.str`required` : undefined, + }; + + const hasErrors = Object.keys(errors).some( + (k) => (errors as any)[k] !== undefined, + ); + + const submitForm = () => { + if (hasErrors) return Promise.reject(); + return onCreate(state as any); + }; + + return ( + <div> + <section class="section is-main-section"> + <div class="columns"> + <div class="column" /> + <div class="column is-four-fifths"> + <FormProvider + object={state} + valueHandler={setState} + errors={errors} + > + <Input<Entity> + name="webhook_id" + label={i18n.str`ID`} + tooltip={i18n.str`Webhook ID to use`} + /> + <InputSelector + name="event_type" + label={i18n.str`Event`} + values={[ + i18n.str`Choose one...`, + i18n.str`pay`, + i18n.str`refund`, + ]} + tooltip={i18n.str`The event of the webhook: why the webhook is used`} + /> + <InputSelector + name="http_method" + label={i18n.str`Method`} + values={[ + i18n.str`Choose one...`, + i18n.str`GET`, + i18n.str`POST`, + i18n.str`PUT`, + i18n.str`PATCH`, + i18n.str`HEAD`, + ]} + tooltip={i18n.str`Method used by the webhook`} + /> + + <Input<Entity> + name="url" + label={i18n.str`URL`} + tooltip={i18n.str`URL of the webhook where the customer will be redirected`} + /> + + <p> + The text below support <a target="_blank" rel="noreferrer" href="https://mustache.github.io/mustache.5.html">mustache</a> template engine. Any string + between <pre style={{ display: "inline", padding: 0 }}>{{</pre> and <pre style={{ display: "inline", padding: 0 }}>}}</pre> will + be replaced with replaced with the value of the corresponding variable. + </p> + <p> + For example <pre style={{ display: "inline", padding: 0 }}>{{contract_terms.amount}}</pre> will be replaced + with the the order's price + </p> + <p> + The short list of variables are: + </p> + <div class="menu"> + + <ul class="menu-list" style={{ listStyleType: "disc", marginLeft: 20 }}> + <li><b>contract_terms.summary:</b> order's description </li> + <li><b>contract_terms.amount:</b> order's price </li> + <li><b>order_id:</b> order's unique identification </li> + {state.event_type === "refund" && <Fragment> + <li><b>refund_amout:</b> the amount that was being refunded</li> + <li><b>reason:</b> the reason entered by the merchant staff for granting the refund</li> + <li><b>timestamp:</b> time of the refund in nanoseconds since 1970</li> + </Fragment>} + </ul> + </div> + {/* <Input<Entity> + name="header_template" + label={i18n.str`Http header`} + inputType="multiline" + tooltip={i18n.str`Header template of the webhook`} + /> */} + <Input<Entity> + name="body_template" + inputType="multiline" + label={i18n.str`Http body`} + tooltip={i18n.str`Body template by the webhook`} + /> + </FormProvider> + + <div class="buttons is-right mt-5"> + {onBack && ( + <button class="button" onClick={onBack}> + <i18n.Translate>Cancel</i18n.Translate> + </button> + )} + <AsyncButton + disabled={hasErrors} + data-tooltip={ + hasErrors + ? i18n.str`Need to complete marked fields` + : "confirm operation" + } + onClick={submitForm} + > + <i18n.Translate>Confirm</i18n.Translate> + </AsyncButton> + </div> + </div> + <div class="column" /> + </div> + </section> + </div> + ); +} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/webhooks/create/index.tsx b/packages/merchant-backoffice-ui/src/paths/instance/webhooks/create/index.tsx new file mode 100644 index 000000000..70f246ff1 --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/webhooks/create/index.tsx @@ -0,0 +1,62 @@ +/* + This file is part of GNU Taler + (C) 2021-2024 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +/** + * + * @author Sebastian Javier Marchano (sebasjm) + */ + +import { TalerMerchantApi } from "@gnu-taler/taler-util"; +import { useTranslationContext } from "@gnu-taler/web-util/browser"; +import { Fragment, VNode, h } from "preact"; +import { useState } from "preact/hooks"; +import { NotificationCard } from "../../../../components/menu/index.js"; +import { useSessionContext } from "../../../../context/session.js"; +import { Notification } from "../../../../utils/types.js"; +import { CreatePage } from "./CreatePage.js"; + +export type Entity = TalerMerchantApi.WebhookAddDetails; +interface Props { + onBack?: () => void; + onConfirm: () => void; +} + +export default function CreateWebhook({ onConfirm, onBack }: Props): VNode { + const [notif, setNotif] = useState<Notification | undefined>(undefined); + const { i18n } = useTranslationContext(); + const { lib } = useSessionContext(); + const { state } = useSessionContext(); + + return ( + <> + <NotificationCard notification={notif} /> + <CreatePage + onBack={onBack} + onCreate={(request: TalerMerchantApi.WebhookAddDetails) => { + return lib.instance.addWebhook(state.token, request) + .then(() => onConfirm()) + .catch((error) => { + setNotif({ + message: i18n.str`could not inform template`, + type: "ERROR", + description: error.message, + }); + }); + }} + /> + </> + ); +} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/webhooks/list/List.stories.tsx b/packages/merchant-backoffice-ui/src/paths/instance/webhooks/list/List.stories.tsx new file mode 100644 index 000000000..707324d40 --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/webhooks/list/List.stories.tsx @@ -0,0 +1,28 @@ +/* + This file is part of GNU Taler + (C) 2021-2024 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +/** + * + * @author Sebastian Javier Marchano (sebasjm) + */ + +import { FunctionalComponent, h } from "preact"; +import { ListPage as TestedComponent } from "./ListPage.js"; + +export default { + title: "Pages/Templates/List", + component: TestedComponent, +}; diff --git a/packages/merchant-backoffice-ui/src/paths/instance/webhooks/list/ListPage.tsx b/packages/merchant-backoffice-ui/src/paths/instance/webhooks/list/ListPage.tsx new file mode 100644 index 000000000..3f1feb8e9 --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/webhooks/list/ListPage.tsx @@ -0,0 +1,62 @@ +/* + This file is part of GNU Taler + (C) 2021-2024 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +/** + * + * @author Sebastian Javier Marchano (sebasjm) + */ + +import { h, VNode } from "preact"; +import { useTranslationContext } from "@gnu-taler/web-util/browser"; +import { CardTable } from "./Table.js"; +import { TalerMerchantApi } from "@gnu-taler/taler-util"; + +export interface Props { + webhooks: TalerMerchantApi.WebhookEntry[]; + onLoadMoreBefore?: () => void; + onLoadMoreAfter?: () => void; + onCreate: () => void; + onDelete: (e: TalerMerchantApi.WebhookEntry) => void; + onSelect: (e: TalerMerchantApi.WebhookEntry) => void; +} + +export function ListPage({ + webhooks, + onCreate, + onDelete, + onSelect, + onLoadMoreBefore, + onLoadMoreAfter, +}: Props): VNode { + const form = { payto_uri: "" }; + + const { i18n } = useTranslationContext(); + return ( + <section class="section is-main-section"> + <CardTable + webhooks={webhooks.map((o) => ({ + ...o, + id: String(o.webhook_id), + }))} + onCreate={onCreate} + onDelete={onDelete} + onSelect={onSelect} + onLoadMoreBefore={onLoadMoreBefore} + onLoadMoreAfter={onLoadMoreAfter} + /> + </section> + ); +} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/webhooks/list/Table.tsx b/packages/merchant-backoffice-ui/src/paths/instance/webhooks/list/Table.tsx new file mode 100644 index 000000000..919285e78 --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/webhooks/list/Table.tsx @@ -0,0 +1,203 @@ +/* + This file is part of GNU Taler + (C) 2021-2024 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +/** + * + * @author Sebastian Javier Marchano (sebasjm) + */ + +import { TalerMerchantApi } from "@gnu-taler/taler-util"; +import { useTranslationContext } from "@gnu-taler/web-util/browser"; +import { h, VNode } from "preact"; +import { StateUpdater, useState } from "preact/hooks"; + +type Entity = TalerMerchantApi.WebhookEntry; + +interface Props { + webhooks: Entity[]; + onDelete: (e: Entity) => void; + onSelect: (e: Entity) => void; + onCreate: () => void; + onLoadMoreBefore?: () => void; + onLoadMoreAfter?: () => void; +} + +export function CardTable({ + webhooks, + onCreate, + onDelete, + onSelect, + onLoadMoreAfter, + onLoadMoreBefore, +}: Props): VNode { + const [rowSelection, rowSelectionHandler] = useState<string[]>([]); + + const { i18n } = useTranslationContext(); + + return ( + <div class="card has-table"> + <header class="card-header"> + <p class="card-header-title"> + <span class="icon"> + <i class="mdi mdi-newspaper" /> + </span> + <i18n.Translate>Webhooks</i18n.Translate> + </p> + <div class="card-header-icon" aria-label="more options"> + <span + class="has-tooltip-left" + data-tooltip={i18n.str`add new webhooks`} + > + <button class="button is-info" type="button" onClick={onCreate}> + <span class="icon is-small"> + <i class="mdi mdi-plus mdi-36px" /> + </span> + </button> + </span> + </div> + </header> + <div class="card-content"> + <div class="b-table has-pagination"> + <div class="table-wrapper has-mobile-cards"> + {webhooks.length > 0 ? ( + <Table + instances={webhooks} + onDelete={onDelete} + onSelect={onSelect} + rowSelection={rowSelection} + rowSelectionHandler={rowSelectionHandler} + onLoadMoreAfter={onLoadMoreAfter} + onLoadMoreBefore={onLoadMoreBefore} + /> + ) : ( + <EmptyTable /> + )} + </div> + </div> + </div> + </div> + ); +} +interface TableProps { + rowSelection: string[]; + instances: Entity[]; + onDelete: (e: Entity) => void; + onSelect: (e: Entity) => void; + rowSelectionHandler: StateUpdater<string[]>; + onLoadMoreBefore?: () => void; + onLoadMoreAfter?: () => void; +} + +function Table({ + instances, + onLoadMoreAfter, + onDelete, + onSelect, + onLoadMoreBefore, +}: TableProps): VNode { + const { i18n } = useTranslationContext(); + return ( + <div class="table-container"> + {onLoadMoreBefore && ( + <button + class="button is-fullwidth" + data-tooltip={i18n.str`load more webhooks before the first one`} + onClick={onLoadMoreBefore} + > + <i18n.Translate>load first page</i18n.Translate> + </button> + )} + <table class="table is-fullwidth is-striped is-hoverable is-fullwidth"> + <thead> + <tr> + <th> + <i18n.Translate>ID</i18n.Translate> + </th> + <th> + <i18n.Translate>Event type</i18n.Translate> + </th> + <th /> + </tr> + </thead> + <tbody> + {instances.map((i) => { + return ( + <tr key={i.webhook_id}> + <td + onClick={(): void => onSelect(i)} + style={{ cursor: "pointer" }} + > + {i.webhook_id} + </td> + <td + onClick={(): void => onSelect(i)} + style={{ cursor: "pointer" }} + > + {i.event_type} + </td> + <td class="is-actions-cell right-sticky"> + <div class="buttons is-right"> + <button + class="button is-danger is-small has-tooltip-left" + data-tooltip={i18n.str`delete selected webhook from the database`} + onClick={() => onDelete(i)} + > + Delete + </button> + {/* <button + class="button is-info is-small has-tooltip-left" + data-tooltip={i18n.str`test webhook`} + onClick={() => onNewOrder(i)} + > + Test + </button> */} + </div> + </td> + </tr> + ); + })} + </tbody> + </table> + {onLoadMoreAfter && ( + <button + class="button is-fullwidth" + data-tooltip={i18n.str`load more webhooks after the last one`} + onClick={onLoadMoreAfter} + > + <i18n.Translate>load next page</i18n.Translate> + </button> + )} + </div> + ); +} + +function EmptyTable(): VNode { + const { i18n } = useTranslationContext(); + return ( + <div class="content has-text-grey has-text-centered"> + <p> + <span class="icon is-large"> + <i class="mdi mdi-magnify mdi-48px" /> + </span> + </p> + <p> + <i18n.Translate> + There is no webhooks yet, add more pressing the + sign + </i18n.Translate> + </p> + </div> + ); +} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/webhooks/list/index.tsx b/packages/merchant-backoffice-ui/src/paths/instance/webhooks/list/index.tsx new file mode 100644 index 000000000..789b8d73b --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/webhooks/list/index.tsx @@ -0,0 +1,105 @@ +/* + This file is part of GNU Taler + (C) 2021-2024 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +/** + * + * @author Sebastian Javier Marchano (sebasjm) + */ + +import { + HttpStatusCode, + TalerError, + TalerMerchantApi, + assertUnreachable, +} from "@gnu-taler/taler-util"; +import { + useTranslationContext +} from "@gnu-taler/web-util/browser"; +import { Fragment, VNode, h } from "preact"; +import { useState } from "preact/hooks"; +import { ErrorLoadingMerchant } from "../../../../components/ErrorLoadingMerchant.js"; +import { Loading } from "../../../../components/exception/loading.js"; +import { NotificationCard } from "../../../../components/menu/index.js"; +import { useSessionContext } from "../../../../context/session.js"; +import { useInstanceWebhooks } from "../../../../hooks/webhooks.js"; +import { Notification } from "../../../../utils/types.js"; +import { LoginPage } from "../../../login/index.js"; +import { NotFoundPageOrAdminCreate } from "../../../notfound/index.js"; +import { ListPage } from "./ListPage.js"; + +interface Props { + onCreate: () => void; + onSelect: (id: string) => void; +} + +export default function ListWebhooks({ onCreate, onSelect }: Props): VNode { + const { i18n } = useTranslationContext(); + const [notif, setNotif] = useState<Notification | undefined>(undefined); + const { lib } = useSessionContext(); + const { state } = useSessionContext(); + const result = useInstanceWebhooks(); + + if (!result) return <Loading />; + if (result instanceof TalerError) { + return <ErrorLoadingMerchant error={result} />; + } + if (result.type === "fail") { + switch (result.case) { + case HttpStatusCode.NotFound: { + return <NotFoundPageOrAdminCreate />; + } + case HttpStatusCode.Unauthorized: { + return <LoginPage /> + } + default: { + assertUnreachable(result); + } + } + } + + return ( + <Fragment> + <NotificationCard notification={notif} /> + + <ListPage + webhooks={result.body.webhooks} + onLoadMoreBefore={undefined} //result.isFirstPage ? undefined : result.loadFirst} + onLoadMoreAfter={undefined} //result.isLastPage ? undefined : result.loadNext} + onCreate={onCreate} + onSelect={(e) => { + onSelect(e.webhook_id); + }} + onDelete={(e: TalerMerchantApi.WebhookEntry) => { + return lib.instance + .deleteWebhook(state.token, e.webhook_id) + .then(() => + setNotif({ + message: i18n.str`webhook delete successfully`, + type: "SUCCESS", + }), + ) + .catch((error) => + setNotif({ + message: i18n.str`could not delete the webhook`, + type: "ERROR", + description: error.message, + }), + ); + }} + /> + </Fragment> + ); +} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/webhooks/update/Update.stories.tsx b/packages/merchant-backoffice-ui/src/paths/instance/webhooks/update/Update.stories.tsx new file mode 100644 index 000000000..303d17b72 --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/webhooks/update/Update.stories.tsx @@ -0,0 +1,32 @@ +/* + This file is part of GNU Taler + (C) 2021-2024 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +/** + * + * @author Sebastian Javier Marchano (sebasjm) + */ + +import { h, VNode, FunctionalComponent } from "preact"; +import { UpdatePage as TestedComponent } from "./UpdatePage.js"; + +export default { + title: "Pages/Templates/Update", + component: TestedComponent, + argTypes: { + onUpdate: { action: "onUpdate" }, + onBack: { action: "onBack" }, + }, +}; diff --git a/packages/merchant-backoffice-ui/src/paths/instance/webhooks/update/UpdatePage.tsx b/packages/merchant-backoffice-ui/src/paths/instance/webhooks/update/UpdatePage.tsx new file mode 100644 index 000000000..6aca62582 --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/webhooks/update/UpdatePage.tsx @@ -0,0 +1,145 @@ +/* + This file is part of GNU Taler + (C) 2021-2024 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +/** + * + * @author Sebastian Javier Marchano (sebasjm) + */ + +import { useTranslationContext } from "@gnu-taler/web-util/browser"; +import { h, VNode } from "preact"; +import { useState } from "preact/hooks"; +import { AsyncButton } from "../../../../components/exception/AsyncButton.js"; +import { + FormErrors, + FormProvider, +} from "../../../../components/form/FormProvider.js"; +import { Input } from "../../../../components/form/Input.js"; +import { TalerMerchantApi } from "@gnu-taler/taler-util"; + +type Entity = TalerMerchantApi.WebhookPatchDetails & WithId; + +interface Props { + onUpdate: (d: Entity) => Promise<void>; + onBack?: () => void; + webhook: Entity; +} +const validMethod = ["GET", "POST", "PUT", "PATCH", "HEAD"]; + +export function UpdatePage({ webhook, onUpdate, onBack }: Props): VNode { + const { i18n } = useTranslationContext(); + + const [state, setState] = useState<Partial<Entity>>(webhook); + + const errors: FormErrors<Entity> = { + event_type: !state.event_type ? i18n.str`required` : undefined, + http_method: !state.http_method + ? i18n.str`required` + : !validMethod.includes(state.http_method) + ? i18n.str`should be one of '${validMethod.join(", ")}'` + : undefined, + url: !state.url ? i18n.str`required` : undefined, + }; + + const hasErrors = Object.keys(errors).some( + (k) => (errors as any)[k] !== undefined, + ); + + const submitForm = () => { + if (hasErrors) return Promise.reject(); + return onUpdate(state as any); + }; + + return ( + <div> + <section class="section"> + <section class="hero is-hero-bar"> + <div class="hero-body"> + <div class="level"> + <div class="level-left"> + <div class="level-item"> + <span class="is-size-4"> + Webhook: <b>{webhook.id}</b> + </span> + </div> + </div> + </div> + </div> + </section> + <hr /> + + <section class="section is-main-section"> + <div class="columns"> + <div class="column is-four-fifths"> + <FormProvider + object={state} + valueHandler={setState} + errors={errors} + > + <Input<Entity> + name="event_type" + label={i18n.str`Event`} + tooltip={i18n.str`The event of the webhook: why the webhook is used`} + /> + <Input<Entity> + name="http_method" + label={i18n.str`Method`} + tooltip={i18n.str`Method used by the webhook`} + /> + <Input<Entity> + name="url" + label={i18n.str`URL`} + tooltip={i18n.str`URL of the webhook where the customer will be redirected`} + /> + <Input<Entity> + name="header_template" + label={i18n.str`Header`} + inputType="multiline" + tooltip={i18n.str`Header template of the webhook`} + /> + <Input<Entity> + name="body_template" + inputType="multiline" + label={i18n.str`Body`} + tooltip={i18n.str`Body template by the webhook`} + /> + </FormProvider> + + <div class="buttons is-right mt-5"> + {onBack && ( + <button class="button" onClick={onBack}> + <i18n.Translate>Cancel</i18n.Translate> + </button> + )} + <AsyncButton + disabled={hasErrors} + data-tooltip={ + hasErrors + ? i18n.str`Need to complete marked fields` + : "confirm operation" + } + onClick={submitForm} + > + <i18n.Translate>Confirm</i18n.Translate> + </AsyncButton> + </div> + </div> + </div> + </section> + </section> + </div> + ); +} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/webhooks/update/index.tsx b/packages/merchant-backoffice-ui/src/paths/instance/webhooks/update/index.tsx new file mode 100644 index 000000000..5b2ba7bb9 --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/webhooks/update/index.tsx @@ -0,0 +1,97 @@ +/* + This file is part of GNU Taler + (C) 2021-2024 Taler Systems S.A. + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> + */ + +/** + * + * @author Sebastian Javier Marchano (sebasjm) + */ + +import { HttpStatusCode, TalerError, TalerMerchantApi, assertUnreachable } from "@gnu-taler/taler-util"; +import { + useTranslationContext +} from "@gnu-taler/web-util/browser"; +import { Fragment, VNode, h } from "preact"; +import { useState } from "preact/hooks"; +import { ErrorLoadingMerchant } from "../../../../components/ErrorLoadingMerchant.js"; +import { Loading } from "../../../../components/exception/loading.js"; +import { NotificationCard } from "../../../../components/menu/index.js"; +import { useSessionContext } from "../../../../context/session.js"; +import { + useWebhookDetails, +} from "../../../../hooks/webhooks.js"; +import { Notification } from "../../../../utils/types.js"; +import { LoginPage } from "../../../login/index.js"; +import { NotFoundPageOrAdminCreate } from "../../../notfound/index.js"; +import { UpdatePage } from "./UpdatePage.js"; + +export type Entity = TalerMerchantApi.WebhookPatchDetails & WithId; + +interface Props { + onBack?: () => void; + onConfirm: () => void; + tid: string; +} +export default function UpdateWebhook({ + tid, + onConfirm, + onBack, +}: Props): VNode { + const { lib } = useSessionContext(); + const { state } = useSessionContext(); + const result = useWebhookDetails(tid); + const [notif, setNotif] = useState<Notification | undefined>(undefined); + + const { i18n } = useTranslationContext(); + + if (!result) return <Loading />; + if (result instanceof TalerError) { + return <ErrorLoadingMerchant error={result} />; + } + if (result.type === "fail") { + switch (result.case) { + case HttpStatusCode.NotFound: { + return <NotFoundPageOrAdminCreate />; + } + case HttpStatusCode.Unauthorized: { + return <LoginPage /> + } + default: { + assertUnreachable(result); + } + } + } + + return ( + <Fragment> + <NotificationCard notification={notif} /> + <UpdatePage + webhook={{ ...result.body, id: tid }} + onBack={onBack} + onUpdate={(data) => { + return lib.instance.updateWebhook(state.token, tid, data) + .then(onConfirm) + .catch((error) => { + setNotif({ + message: i18n.str`could not update template`, + type: "ERROR", + description: error.message, + }); + }); + }} + /> + </Fragment> + ); +} |