From b9ff31b8df2574663f073782f5be588dc8283174 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Christian=20Bl=C3=A4ttler?= Date: Tue, 28 Nov 2023 08:36:43 +0100 Subject: start with token families ui --- .../merchant-backoffice-ui/src/InstanceRoutes.tsx | 48 ++++ .../src/components/menu/SideBar.tsx | 10 + .../src/components/tokenfamily/TokenFamilyForm.tsx | 150 +++++++++++++ .../merchant-backoffice-ui/src/declaration.d.ts | 117 ++++++++++ .../src/hooks/tokenfamily.ts | 126 +++++++++++ .../tokenfamilies/create/Create.stories.tsx | 43 ++++ .../instance/tokenfamilies/create/CreatePage.tsx | 81 +++++++ .../paths/instance/tokenfamilies/create/index.tsx | 60 +++++ .../paths/instance/tokenfamilies/list/Table.tsx | 244 +++++++++++++++++++++ .../paths/instance/tokenfamilies/list/index.tsx | 118 ++++++++++ .../merchant-backoffice-ui/src/schemas/index.ts | 53 +++++ 11 files changed, 1050 insertions(+) create mode 100644 packages/merchant-backoffice-ui/src/components/tokenfamily/TokenFamilyForm.tsx create mode 100644 packages/merchant-backoffice-ui/src/hooks/tokenfamily.ts create mode 100644 packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/create/Create.stories.tsx create mode 100644 packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/create/CreatePage.tsx create mode 100644 packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/create/index.tsx create mode 100644 packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/list/Table.tsx create mode 100644 packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/list/index.tsx (limited to 'packages') diff --git a/packages/merchant-backoffice-ui/src/InstanceRoutes.tsx b/packages/merchant-backoffice-ui/src/InstanceRoutes.tsx index c3c20bcc4..5ee17220d 100644 --- a/packages/merchant-backoffice-ui/src/InstanceRoutes.tsx +++ b/packages/merchant-backoffice-ui/src/InstanceRoutes.tsx @@ -65,6 +65,11 @@ import WebhookUpdatePage from "./paths/instance/webhooks/update/index.js"; import ValidatorCreatePage from "./paths/instance/otp_devices/create/index.js"; import ValidatorListPage from "./paths/instance/otp_devices/list/index.js"; import ValidatorUpdatePage from "./paths/instance/otp_devices/update/index.js"; + +import TokenFamilyCreatePage from "./paths/instance/tokenfamilies/create/index.js"; +import TokenFamilyListPage from "./paths/instance/tokenfamilies/list/index.js"; +// import TokenFamilyUpdatePage from "./paths/instance/tokenfamilies/update/index.js"; + import TransferCreatePage from "./paths/instance/transfers/create/index.js"; import TransferListPage from "./paths/instance/transfers/list/index.js"; import InstanceUpdatePage, { @@ -118,6 +123,10 @@ export enum InstancePaths { otp_devices_update = "/otp-devices/:vid/update", otp_devices_new = "/otp-devices/new", + token_family_list = "/tokenfamilies", + token_family_update = "/tokenfamilies/:slug/update", + token_family_new = "/tokenfamilies/new", + interface = "/interface", } @@ -486,6 +495,45 @@ export function InstanceRoutes({ route(InstancePaths.transfers_list); }} /> + {/* * + * Token family pages + */} + { + route(InstancePaths.token_family_new); + }} + onSelect={(slug: string) => { + route(InstancePaths.token_family_update.replace(":slug", slug)); + }} + onNotFound={IfAdminCreateDefaultOr(NotFoundPage)} + /> + {/* { + route(InstancePaths.token_family_list); + }} + onBack={() => { + route(InstancePaths.token_family_list); + }} + onNotFound={IfAdminCreateDefaultOr(NotFoundPage)} + /> */} + { + route(InstancePaths.token_family_list); + }} + onBack={() => { + route(InstancePaths.token_family_list); + }} + /> {/** * Webhooks pages */} diff --git a/packages/merchant-backoffice-ui/src/components/menu/SideBar.tsx b/packages/merchant-backoffice-ui/src/components/menu/SideBar.tsx index 8aac5f543..447020acf 100644 --- a/packages/merchant-backoffice-ui/src/components/menu/SideBar.tsx +++ b/packages/merchant-backoffice-ui/src/components/menu/SideBar.tsx @@ -123,6 +123,16 @@ export function Sidebar({ +
  • + + + + + + Token Families + + +
  • {needKYC && (
  • diff --git a/packages/merchant-backoffice-ui/src/components/tokenfamily/TokenFamilyForm.tsx b/packages/merchant-backoffice-ui/src/components/tokenfamily/TokenFamilyForm.tsx new file mode 100644 index 000000000..3cb739aea --- /dev/null +++ b/packages/merchant-backoffice-ui/src/components/tokenfamily/TokenFamilyForm.tsx @@ -0,0 +1,150 @@ +/* + This file is part of GNU Taler + (C) 2021-2023 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 + */ + +/** + * + * @author Christian Blättler + */ + +import { useTranslationContext } from "@gnu-taler/web-util/browser"; +import { h } from "preact"; +import { useCallback, useEffect, useState } from "preact/hooks"; +import * as yup from "yup"; +import { useBackendContext } from "../../context/backend.js"; +import { MerchantBackend } from "../../declaration.js"; +import { + TokenFamilyCreateSchema as createSchema, + TokenFamilyUpdateSchema as updateSchema, +} from "../../schemas/index.js"; +import { FormErrors, FormProvider } from "../form/FormProvider.js"; +import { Input } from "../form/Input.js"; +import { InputWithAddon } from "../form/InputWithAddon.js"; +import { InputDate } from "../form/InputDate.js"; +import { InputDuration } from "../form/InputDuration.js"; +import { InputSelector } from "../form/InputSelector.js"; + +type Entity = MerchantBackend.TokenFamilies.TokenFamilyAddDetail; + +interface Props { + onSubscribe: (c?: () => Entity | undefined) => void; + initial?: Partial; + alreadyExist?: boolean; +} + +export function TokenFamilyForm({ onSubscribe, initial, alreadyExist }: Props) { + const [value, valueHandler] = useState>({ + slug: "", + name: "", + description: "", + description_i18n: {}, + kind: MerchantBackend.TokenFamilies.TokenFamilyKind.Discount, + duration: { d_us: "forever" }, + valid_after: { t_s: "never" }, + valid_before: { t_s: "never" }, + }); + let errors: FormErrors = {}; + + try { + // (alreadyExist ? updateSchema : createSchema).validateSync(value, { + // abortEarly: false, + // }); + createSchema.validateSync(value, { + abortEarly: false, + }); + } catch (err) { + if (err instanceof yup.ValidationError) { + const yupErrors = err.inner as yup.ValidationError[]; + 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 submit = useCallback((): Entity | undefined => { + // HACK: Think about how this can be done better + return value as Entity; + }, [value]); + + useEffect(() => { + onSubscribe(hasErrors ? undefined : submit); + }, [submit, hasErrors]); + + const backend = useBackendContext(); + const { i18n } = useTranslationContext(); + + return ( +
    + + name="token_family" + errors={errors} + object={value} + valueHandler={valueHandler} + > + {/* {alreadyExist ? undefined : ( */} + + name="slug" + addonBefore={`${backend.url}/tokenfamily/`} + label={i18n.str`Slug`} + tooltip={i18n.str`token family slug to use in URLs (for internal use only)`} + /> + {/* )} + {alreadyExist ? undefined : ( */} + + name="kind" + label={i18n.str`Kind`} + tooltip={i18n.str`token family kind`} + values={["discount", "subscription"]} + /> + {/* )} */} + + name="name" + inputType="text" + label={i18n.str`Name`} + tooltip={i18n.str`user-readable token family name`} + /> + + name="description" + inputType="multiline" + label={i18n.str`Description`} + tooltip={i18n.str`token family description for customers`} + /> + + name="valid_after" + label={i18n.str`Valid After`} + tooltip={i18n.str`token family can issue tokens after this date`} + withTimestampSupport + /> + + name="valid_before" + label={i18n.str`Valid Before`} + tooltip={i18n.str`token family can issue tokens until this date`} + withTimestampSupport + /> + + name="duration" + label={i18n.str`Duration`} + tooltip={i18n.str`validity duration of a issued token`} + withForever + /> + +
    + ); +} diff --git a/packages/merchant-backoffice-ui/src/declaration.d.ts b/packages/merchant-backoffice-ui/src/declaration.d.ts index dc53e3e83..9808f8b66 100644 --- a/packages/merchant-backoffice-ui/src/declaration.d.ts +++ b/packages/merchant-backoffice-ui/src/declaration.d.ts @@ -1526,6 +1526,123 @@ export namespace MerchantBackend { } } + namespace TokenFamilies { + // Kind of the token family. + enum TokenFamilyKind { + Discount = "discount", + Subscription = "subscription", + } + + // POST /private/tokenfamilies + interface TokenFamilyAddDetail { + // Identifier for the token family consisting of unreserved characters + // according to RFC 3986. + slug: string; + + // Human-readable name for the token family. + name: string; + + // Human-readable description for the token family. + description: string; + + // Optional map from IETF BCP 47 language tags to localized descriptions. + description_i18n?: { [lang_tag: string]: string }; + + // Start time of the token family's validity period. + // If not specified, merchant backend will use the current time. + valid_after?: Timestamp; + + // End time of the token family's validity period. + valid_before: Timestamp; + + // Validity duration of an issued token. + duration: RelativeTime; + + // Kind of the token family. + kind: TokenFamilyKind; + } + + // PATCH /private/tokenfamilies/$SLUG + interface TokenFamilyPatchDetail { + // Human-readable name for the token family. + name: string; + + // Human-readable description for the token family. + description: string; + + // Optional map from IETF BCP 47 language tags to localized descriptions. + description_i18n: { [lang_tag: string]: string }; + + // Start time of the token family's validity period. + valid_after: Timestamp; + + // End time of the token family's validity period. + valid_before: Timestamp; + + // Validity duration of an issued token. + duration: RelativeTime; + } + + // GET /private/tokenfamilies + interface TokenFamilySummaryResponse { + // All configured token families of this instance. + token_families: TokenFamilyEntry[]; + } + + interface TokenFamilyEntry { + // Identifier for the token family consisting of unreserved characters + // according to RFC 3986. + slug: string; + + // Human-readable name for the token family. + name: string; + + // Start time of the token family's validity period. + valid_after: Timestamp; + + // End time of the token family's validity period. + valid_before: Timestamp; + + // Kind of the token family. + kind: TokenFamilyKind; + } + + // GET /private/tokenfamilies/$SLUG + interface TokenFamilyDetail { + // Identifier for the token family consisting of unreserved characters + // according to RFC 3986. + slug: string; + + // Human-readable name for the token family. + name: string; + + // Human-readable description for the token family. + description: string; + + // Optional map from IETF BCP 47 language tags to localized descriptions. + description_i18n?: { [lang_tag: string]: string }; + + // Start time of the token family's validity period. + valid_after: Timestamp; + + // End time of the token family's validity period. + valid_before: Timestamp; + + // Validity duration of an issued token. + duration: RelativeTime; + + // Kind of the token family. + kind: TokenFamilyKind; + + // How many tokens have been issued for this family. + issued: Integer; + + // How many tokens have been redeemed for this family. + redeemed: Integer; + } + + } + interface ContractTerms { // Human-readable description of the whole purchase summary: string; diff --git a/packages/merchant-backoffice-ui/src/hooks/tokenfamily.ts b/packages/merchant-backoffice-ui/src/hooks/tokenfamily.ts new file mode 100644 index 000000000..0266fe536 --- /dev/null +++ b/packages/merchant-backoffice-ui/src/hooks/tokenfamily.ts @@ -0,0 +1,126 @@ +/* + This file is part of GNU Taler + (C) 2021-2023 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 + */ + import { + HttpResponse, + HttpResponseOk, + RequestError, +} from "@gnu-taler/web-util/browser"; +import { MerchantBackend } from "../declaration.js"; +import { useBackendInstanceRequest, useMatchMutate } from "./backend.js"; + +// FIX default import https://github.com/microsoft/TypeScript/issues/49189 +import _useSWR, { SWRHook, useSWRConfig } from "swr"; +const useSWR = _useSWR as unknown as SWRHook; + +export interface TokenFamilyAPI { + createTokenFamily: ( + data: MerchantBackend.TokenFamilies.TokenFamilyAddDetail, + ) => Promise; + updateTokenFamily: ( + slug: string, + data: MerchantBackend.TokenFamilies.TokenFamilyPatchDetail, + ) => Promise; + deleteTokenFamily: (slug: string) => Promise; +} + +export function useTokenFamilyAPI(): TokenFamilyAPI { + const mutateAll = useMatchMutate(); + const { mutate } = useSWRConfig(); + + const { request } = useBackendInstanceRequest(); + + const createTokenFamily = async ( + data: MerchantBackend.TokenFamilies.TokenFamilyAddDetail, + ): Promise => { + const res = await request(`/private/tokenfamilies`, { + method: "POST", + data, + }); + + return await mutateAll(/.*"\/private\/tokenfamilies.*/); + }; + + const updateTokenFamily = async ( + tokenFamilySlug: string, + data: MerchantBackend.TokenFamilies.TokenFamilyPatchDetail, + ): Promise => { + const r = await request(`/private/tokenfamilies/${tokenFamilySlug}`, { + method: "PATCH", + data, + }); + + return await mutateAll(/.*"\/private\/tokenfamilies.*/); + }; + + const deleteTokenFamily = async (tokenFamilySlug: string): Promise => { + await request(`/private/tokenfamilies/${tokenFamilySlug}`, { + method: "DELETE", + }); + await mutate([`/private/tokenfamilies`]); + }; + + return { createTokenFamily, updateTokenFamily, deleteTokenFamily }; +} + +export function useInstanceTokenFamilies(): HttpResponse< + (MerchantBackend.TokenFamilies.TokenFamilyEntry)[], + MerchantBackend.ErrorDetail +> { + const { fetcher, multiFetcher } = useBackendInstanceRequest(); + + const { data: list, error: listError } = useSWR< + HttpResponseOk, + RequestError + >([`/private/tokenfamilies`], fetcher, { + refreshInterval: 0, + refreshWhenHidden: false, + revalidateOnFocus: false, + revalidateOnReconnect: false, + refreshWhenOffline: false, + }); + + if (listError) return listError.cause; + + if (list) { + return { ok: true, data: list.data.token_families }; + } + return { loading: true }; +} + +export function useTokenFamilyDetails( + tokenFamilySlug: string, +): HttpResponse< + MerchantBackend.TokenFamilies.TokenFamilyDetail, + MerchantBackend.ErrorDetail +> { + const { fetcher } = useBackendInstanceRequest(); + + const { data, error, isValidating } = useSWR< + HttpResponseOk, + RequestError + >([`/private/tokenfamilies/${tokenFamilySlug}`], fetcher, { + refreshInterval: 0, + refreshWhenHidden: false, + revalidateOnFocus: false, + revalidateOnReconnect: false, + refreshWhenOffline: false, + }); + + if (isValidating) return { loading: true, data: data?.data }; + if (data) return data; + if (error) return error.cause; + return { loading: true }; +} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/create/Create.stories.tsx b/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/create/Create.stories.tsx new file mode 100644 index 000000000..d9ac4202c --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/create/Create.stories.tsx @@ -0,0 +1,43 @@ +/* + This file is part of GNU Taler + (C) 2021-2023 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 + */ + +/** + * + * @author Christian Blättler + */ + +import { h, VNode, FunctionalComponent } from "preact"; +import { CreatePage as TestedComponent } from "./CreatePage.js"; + +export default { + title: "Pages/TokenFamily/Create", + component: TestedComponent, + argTypes: { + onCreate: { action: "onCreate" }, + onBack: { action: "onBack" }, + }, +}; + +function createExample( + Component: FunctionalComponent, + props: Partial, +) { + const r = (args: any) => ; + r.args = props; + return r; +} + +export const Example = createExample(TestedComponent, {}); diff --git a/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/create/CreatePage.tsx b/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/create/CreatePage.tsx new file mode 100644 index 000000000..bf5b94e95 --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/create/CreatePage.tsx @@ -0,0 +1,81 @@ +/* + This file is part of GNU Taler + (C) 2021-2023 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 + */ + +/** + * + * @author Christian Blättler + */ + +import { useTranslationContext } from "@gnu-taler/web-util/browser"; +import { h, VNode } from "preact"; +import { AsyncButton } from "../../../../components/exception/AsyncButton.js"; +import { MerchantBackend } from "../../../../declaration.js"; +import { useListener } from "../../../../hooks/listener.js"; +import { TokenFamilyCreateForm } from "../../../../components/token/TokenFamilyCreateForm.js"; +import { Test } from "../../../../components/token/Test.js"; + +type Entity = MerchantBackend.TokenFamilies.TokenFamilyAddDetail; + +interface Props { + onCreate: (d: Entity) => Promise; + onBack?: () => void; +} + +export function CreatePage({ onCreate, onBack }: Props): VNode { + const [submitForm, addFormSubmitter] = useListener( + (result) => { + if (result) return onCreate(result); + return Promise.reject(); + }, + ); + + const { i18n } = useTranslationContext(); + + return ( +
    +
    +
    +
    +
    + {/* */} + + + +
    + {onBack && ( + + )} + + Confirm + +
    +
    +
    +
    +
    +
    + ); +} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/create/index.tsx b/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/create/index.tsx new file mode 100644 index 000000000..5abab05b0 --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/create/index.tsx @@ -0,0 +1,60 @@ +/* + This file is part of GNU Taler + (C) 2021-2023 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 + */ + +/** + * + * @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 { NotificationCard } from "../../../../components/menu/index.js"; +import { MerchantBackend } from "../../../../declaration.js"; +import { Notification } from "../../../../utils/types.js"; +import { CreatePage } from "./CreatePage.js"; +import { useTokenFamilyAPI } from "../../../../hooks/tokenfamily.js"; + +export type Entity = MerchantBackend.TokenFamilies.TokenFamilyAddDetail; +interface Props { + onBack?: () => void; + onConfirm: () => void; +} +export default function CreateTokenFamily({ onConfirm, onBack }: Props): VNode { + const { createTokenFamily } = useTokenFamilyAPI(); + const [notif, setNotif] = useState(undefined); + const { i18n } = useTranslationContext(); + + return ( + + + { + return createTokenFamily(request) + .then(() => onConfirm()) + .catch((error) => { + setNotif({ + message: i18n.str`could not create token family`, + type: "ERROR", + description: error.message, + }); + }); + }} + /> + + ); +} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/list/Table.tsx b/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/list/Table.tsx new file mode 100644 index 000000000..3d9bf9018 --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/list/Table.tsx @@ -0,0 +1,244 @@ +/* + This file is part of GNU Taler + (C) 2021-2023 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 + */ + +/** + * + * @author Christian Blättler + */ + +import { useTranslationContext } from "@gnu-taler/web-util/browser"; +import { Fragment, h, VNode } from "preact"; +import { StateUpdater, useState } from "preact/hooks"; +import { format } from "date-fns"; +import { MerchantBackend } from "../../../../declaration.js"; + +type Entity = MerchantBackend.TokenFamilies.TokenFamilyEntry; + +interface Props { + instances: Entity[]; + onDelete: (tokenFamily: Entity) => void; + onSelect: (tokenFamily: Entity) => void; + onUpdate: ( + slug: string, + data: MerchantBackend.TokenFamilies.TokenFamilyPatchDetail, + ) => Promise; + onCreate: () => void; + selected?: boolean; +} + +export function CardTable({ + instances, + onCreate, + onSelect, + onUpdate, + onDelete, +}: Props): VNode { + const [rowSelection, rowSelectionHandler] = useState( + undefined, + ); + const { i18n } = useTranslationContext(); + return ( +
    +
    +

    + + + + Token Families +

    +
    + + + +
    +
    +
    +
    +
    + {instances.length > 0 ? ( + + ) : ( + + )} + + + + + ); +} +interface TableProps { + rowSelection: string | undefined; + instances: Entity[]; + onSelect: (tokenFamily: Entity) => void; + onUpdate: ( + slug: string, + data: MerchantBackend.TokenFamilies.TokenFamilyPatchDetail, + ) => Promise; + onDelete: (tokenFamily: Entity) => void; + rowSelectionHandler: StateUpdater; +} + +function Table({ + rowSelection, + rowSelectionHandler, + instances, + onSelect, + onUpdate, + onDelete, +}: TableProps): VNode { + const { i18n } = useTranslationContext(); + return ( +
    +
    + + + + + + + + + + + {instances.map((i) => { + return ( + + + + + + + + + + + ); + })} + +
    + Slug + + Name + + Valid After + + Valid Before + + Kind + +
    + rowSelection !== i.slug && rowSelectionHandler(i.slug) + } + style={{ cursor: "pointer" }} + > + {i.slug} + + rowSelection !== i.slug && rowSelectionHandler(i.slug) + } + style={{ cursor: "pointer" }} + > + {i.name} + + rowSelection !== i.slug && rowSelectionHandler(i.slug) + } + style={{ cursor: "pointer" }} + > + {i.valid_after.t_s === "never" + ? "never" + : format(new Date(i.valid_after.t_s * 1000), "yyyy/MM/dd hh:mm:ss")} + + rowSelection !== i.slug && rowSelectionHandler(i.slug) + } + style={{ cursor: "pointer" }} + > + {i.valid_before.t_s === "never" + ? "never" + : format(new Date(i.valid_before.t_s * 1000), "yyyy/MM/dd hh:mm:ss")} + + rowSelection !== i.slug && rowSelectionHandler(i.slug) + } + style={{ cursor: "pointer" }} + > + {i.kind} + +
    + + + + + + +
    +
    +
    + ); +} + + +function EmptyTable(): VNode { + const { i18n } = useTranslationContext(); + return ( +
    +

    + + + +

    +

    + + There are no token families yet, add the first one by pressing the + sign. + +

    +
    + ); +} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/list/index.tsx b/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/list/index.tsx new file mode 100644 index 000000000..a5d7413c0 --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/list/index.tsx @@ -0,0 +1,118 @@ +/* + This file is part of GNU Taler + (C) 2021-2023 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 + */ + +/** + * + * @author Christian Blättler + */ + +import { + ErrorType, + HttpError, + useTranslationContext, +} from "@gnu-taler/web-util/browser"; +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 { + useInstanceTokenFamilies, + useTokenFamilyAPI, +} from "../../../../hooks/tokenfamily.js"; +import { Notification } from "../../../../utils/types.js"; +import { CardTable } from "./Table.js"; +import { HttpStatusCode } from "@gnu-taler/taler-util"; + +interface Props { + onUnauthorized: () => VNode; + onNotFound: () => VNode; + onCreate: () => void; + onSelect: (slug: string) => void; + onLoadError: (e: HttpError) => VNode; +} +export default function TokenFamilyList({ + onUnauthorized, + onLoadError, + onCreate, + onSelect, + onNotFound, +}: Props): VNode { + const result = useInstanceTokenFamilies(); + const { deleteTokenFamily, updateTokenFamily } = useTokenFamilyAPI(); + const [notif, setNotif] = useState(undefined); + + const { i18n } = useTranslationContext(); + + if (result.loading) return ; + if (!result.ok) { + if ( + result.type === ErrorType.CLIENT && + result.status === HttpStatusCode.Unauthorized + ) + return onUnauthorized(); + if ( + result.type === ErrorType.CLIENT && + result.status === HttpStatusCode.NotFound + ) + return onNotFound(); + return onLoadError(result); + } + + return ( +
    + + + + updateTokenFamily(slug, fam) + .then(() => + setNotif({ + message: i18n.str`token family updated successfully`, + type: "SUCCESS", + }), + ) + .catch((error) => + setNotif({ + message: i18n.str`could not update the token family`, + type: "ERROR", + description: error.message, + }), + ) + } + onSelect={(tokenFamily) => onSelect(tokenFamily.slug)} + onDelete={(fam) => + deleteTokenFamily(fam.slug) + .then(() => + setNotif({ + message: i18n.str`token family delete successfully`, + type: "SUCCESS", + }), + ) + .catch((error) => + setNotif({ + message: i18n.str`could not delete the token family`, + type: "ERROR", + description: error.message, + }), + ) + } + /> +
    + ); +} diff --git a/packages/merchant-backoffice-ui/src/schemas/index.ts b/packages/merchant-backoffice-ui/src/schemas/index.ts index c97d41204..1704b0555 100644 --- a/packages/merchant-backoffice-ui/src/schemas/index.ts +++ b/packages/merchant-backoffice-ui/src/schemas/index.ts @@ -23,6 +23,7 @@ import { isAfter, isFuture } from "date-fns"; import * as yup from "yup"; import { AMOUNT_REGEX, PAYTO_REGEX } from "../utils/constants.js"; import { Amounts } from "@gnu-taler/taler-util"; +import { MerchantBackend } from "../declaration.js"; yup.setLocale({ mixed: { @@ -243,3 +244,55 @@ export const NonInventoryProductSchema = yup.object().shape({ .required() .test("amount", "the amount is not valid", currencyWithAmountIsValid), }); + +const timestampSchema = yup.object().shape({ + t_s: yup.mixed().test( + 'is-timestamp', + 'Invalid timestamp', + value => typeof value === 'number' || value === 'never' + ) +}).required(); + +const durationSchema = yup.object().shape({ + d_us: yup.mixed().test( + 'is-duration', + 'Invalid duration', + value => typeof value === 'number' || value === 'forever' + ) +}).required(); + +const tokenFamilyKindSchema = yup.mixed().oneOf(Object.values(MerchantBackend.TokenFamilies.TokenFamilyKind)).required(); + +export const TokenFamilyCreateSchema = yup.object().shape({ + slug: yup.string().ensure().required(), + name: yup.string().required(), + description: yup.string().required(), + // description_i18n: yup.lazy((obj) => + // yup.object().shape( + // Object.keys(obj || {}).reduce((acc, key) => { + // acc[key] = yup.string().required(); + // return acc; + // }, {}) + // ) + // ).optional(), + valid_after: timestampSchema.optional(), + valid_before: timestampSchema, + duration: durationSchema, + kind: tokenFamilyKindSchema, +}); + +export const TokenFamilyUpdateSchema = yup.object().shape({ + name: yup.string().required(), + description: yup.string().required(), + // description_i18n: yup.lazy((obj) => + // yup.object().shape( + // Object.keys(obj).reduce((acc, key) => { + // acc[key] = yup.string().required(); + // return acc; + // }, {}) + // ) + // ), + valid_after: timestampSchema, + valid_before: timestampSchema, + duration: durationSchema, +}); -- cgit v1.2.3 From 628a2ff35590fb37c69ad5ac075db1ba4049df1e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Christian=20Bl=C3=A4ttler?= Date: Tue, 28 Nov 2023 08:37:41 +0100 Subject: fix imports --- .../src/paths/instance/tokenfamilies/create/CreatePage.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'packages') diff --git a/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/create/CreatePage.tsx b/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/create/CreatePage.tsx index bf5b94e95..777066d20 100644 --- a/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/create/CreatePage.tsx +++ b/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/create/CreatePage.tsx @@ -24,8 +24,8 @@ import { h, VNode } from "preact"; import { AsyncButton } from "../../../../components/exception/AsyncButton.js"; import { MerchantBackend } from "../../../../declaration.js"; import { useListener } from "../../../../hooks/listener.js"; -import { TokenFamilyCreateForm } from "../../../../components/token/TokenFamilyCreateForm.js"; -import { Test } from "../../../../components/token/Test.js"; +import { TokenFamilyForm } from "../../../../components/tokenfamily/TokenFamilyForm.js"; +import { Test } from "../../../../components/tokenfamily/Test.js"; type Entity = MerchantBackend.TokenFamilies.TokenFamilyAddDetail; -- cgit v1.2.3 From f49d24ae6e99b0a879d99855aa1b4eb183157610 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Christian=20Bl=C3=A4ttler?= Date: Tue, 28 Nov 2023 09:44:06 +0100 Subject: use composite type instead of enum --- .../src/components/tokenfamily/TokenFamilyForm.tsx | 2 +- packages/merchant-backoffice-ui/src/declaration.d.ts | 5 +---- .../src/paths/instance/tokenfamilies/create/CreatePage.tsx | 6 +++--- packages/merchant-backoffice-ui/src/schemas/index.ts | 5 +++-- 4 files changed, 8 insertions(+), 10 deletions(-) (limited to 'packages') diff --git a/packages/merchant-backoffice-ui/src/components/tokenfamily/TokenFamilyForm.tsx b/packages/merchant-backoffice-ui/src/components/tokenfamily/TokenFamilyForm.tsx index 3cb739aea..420466eaa 100644 --- a/packages/merchant-backoffice-ui/src/components/tokenfamily/TokenFamilyForm.tsx +++ b/packages/merchant-backoffice-ui/src/components/tokenfamily/TokenFamilyForm.tsx @@ -50,7 +50,7 @@ export function TokenFamilyForm({ onSubscribe, initial, alreadyExist }: Props) { name: "", description: "", description_i18n: {}, - kind: MerchantBackend.TokenFamilies.TokenFamilyKind.Discount, + kind: "discount", duration: { d_us: "forever" }, valid_after: { t_s: "never" }, valid_before: { t_s: "never" }, diff --git a/packages/merchant-backoffice-ui/src/declaration.d.ts b/packages/merchant-backoffice-ui/src/declaration.d.ts index 9808f8b66..15bde2305 100644 --- a/packages/merchant-backoffice-ui/src/declaration.d.ts +++ b/packages/merchant-backoffice-ui/src/declaration.d.ts @@ -1528,10 +1528,7 @@ export namespace MerchantBackend { namespace TokenFamilies { // Kind of the token family. - enum TokenFamilyKind { - Discount = "discount", - Subscription = "subscription", - } + type TokenFamilyKind = "discount" | "subscription"; // POST /private/tokenfamilies interface TokenFamilyAddDetail { diff --git a/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/create/CreatePage.tsx b/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/create/CreatePage.tsx index 777066d20..7ae9bebe6 100644 --- a/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/create/CreatePage.tsx +++ b/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/create/CreatePage.tsx @@ -25,7 +25,7 @@ import { AsyncButton } from "../../../../components/exception/AsyncButton.js"; import { MerchantBackend } from "../../../../declaration.js"; import { useListener } from "../../../../hooks/listener.js"; import { TokenFamilyForm } from "../../../../components/tokenfamily/TokenFamilyForm.js"; -import { Test } from "../../../../components/tokenfamily/Test.js"; +// import { Test } from "../../../../components/tokenfamily/Test.js"; type Entity = MerchantBackend.TokenFamilies.TokenFamilyAddDetail; @@ -50,9 +50,9 @@ export function CreatePage({ onCreate, onBack }: Props): VNode {
    - {/* */} + - + {/* */}
    {onBack && ( diff --git a/packages/merchant-backoffice-ui/src/schemas/index.ts b/packages/merchant-backoffice-ui/src/schemas/index.ts index 1704b0555..5bcb68021 100644 --- a/packages/merchant-backoffice-ui/src/schemas/index.ts +++ b/packages/merchant-backoffice-ui/src/schemas/index.ts @@ -21,9 +21,10 @@ import { isAfter, isFuture } from "date-fns"; import * as yup from "yup"; -import { AMOUNT_REGEX, PAYTO_REGEX } from "../utils/constants.js"; +import { PAYTO_REGEX } from "../utils/constants.js"; import { Amounts } from "@gnu-taler/taler-util"; import { MerchantBackend } from "../declaration.js"; +// import { MerchantBackend } from "../declaration.js"; yup.setLocale({ mixed: { @@ -261,7 +262,7 @@ const durationSchema = yup.object().shape({ ) }).required(); -const tokenFamilyKindSchema = yup.mixed().oneOf(Object.values(MerchantBackend.TokenFamilies.TokenFamilyKind)).required(); +const tokenFamilyKindSchema = yup.mixed().oneOf(["discount", "subscription"]).required(); export const TokenFamilyCreateSchema = yup.object().shape({ slug: yup.string().ensure().required(), -- cgit v1.2.3 From ca12c07abd1ca9083373e9f2a3f872573759b0ac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Christian=20Bl=C3=A4ttler?= Date: Thu, 18 Jan 2024 11:46:53 +0100 Subject: add token family update page --- .../merchant-backoffice-ui/src/InstanceRoutes.tsx | 9 +- .../src/components/tokenfamily/TokenFamilyForm.tsx | 40 ++---- .../paths/instance/tokenfamilies/create/index.tsx | 2 +- .../instance/tokenfamilies/update/UpdatePage.tsx | 159 +++++++++++++++++++++ .../paths/instance/tokenfamilies/update/index.tsx | 106 ++++++++++++++ 5 files changed, 285 insertions(+), 31 deletions(-) create mode 100644 packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/update/UpdatePage.tsx create mode 100644 packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/update/index.tsx (limited to 'packages') diff --git a/packages/merchant-backoffice-ui/src/InstanceRoutes.tsx b/packages/merchant-backoffice-ui/src/InstanceRoutes.tsx index 5ee17220d..a82e96c14 100644 --- a/packages/merchant-backoffice-ui/src/InstanceRoutes.tsx +++ b/packages/merchant-backoffice-ui/src/InstanceRoutes.tsx @@ -27,10 +27,9 @@ import { import { format } from "date-fns"; import { Fragment, FunctionComponent, h, VNode } from "preact"; import { Route, route, Router } from "preact-router"; -import { useCallback, useEffect, useMemo, useState } from "preact/hooks"; +import { useEffect, useMemo, useState } from "preact/hooks"; import { Loading } from "./components/exception/loading.js"; import { Menu, NotificationCard } from "./components/menu/index.js"; -import { useBackendContext } from "./context/backend.js"; import { InstanceContextProvider } from "./context/instance.js"; import { useBackendDefaultToken, @@ -68,7 +67,7 @@ import ValidatorUpdatePage from "./paths/instance/otp_devices/update/index.js"; import TokenFamilyCreatePage from "./paths/instance/tokenfamilies/create/index.js"; import TokenFamilyListPage from "./paths/instance/tokenfamilies/list/index.js"; -// import TokenFamilyUpdatePage from "./paths/instance/tokenfamilies/update/index.js"; +import TokenFamilyUpdatePage from "./paths/instance/tokenfamilies/update/index.js"; import TransferCreatePage from "./paths/instance/transfers/create/index.js"; import TransferListPage from "./paths/instance/transfers/list/index.js"; @@ -511,7 +510,7 @@ export function InstanceRoutes({ }} onNotFound={IfAdminCreateDefaultOr(NotFoundPage)} /> - {/* */} + /> >({ slug: "", name: "", @@ -58,10 +55,7 @@ export function TokenFamilyForm({ onSubscribe, initial, alreadyExist }: Props) { let errors: FormErrors = {}; try { - // (alreadyExist ? updateSchema : createSchema).validateSync(value, { - // abortEarly: false, - // }); - createSchema.validateSync(value, { + TokenFamilyCreateSchema.validateSync(value, { abortEarly: false, }); } catch (err) { @@ -98,22 +92,18 @@ export function TokenFamilyForm({ onSubscribe, initial, alreadyExist }: Props) { object={value} valueHandler={valueHandler} > - {/* {alreadyExist ? undefined : ( */} - - name="slug" - addonBefore={`${backend.url}/tokenfamily/`} - label={i18n.str`Slug`} - tooltip={i18n.str`token family slug to use in URLs (for internal use only)`} - /> - {/* )} - {alreadyExist ? undefined : ( */} - - name="kind" - label={i18n.str`Kind`} - tooltip={i18n.str`token family kind`} - values={["discount", "subscription"]} - /> - {/* )} */} + + name="slug" + addonBefore={`${backend.url}/tokenfamily/`} + label={i18n.str`Slug`} + tooltip={i18n.str`token family slug to use in URLs (for internal use only)`} + /> + + name="kind" + label={i18n.str`Kind`} + tooltip={i18n.str`token family kind`} + values={["discount", "subscription"]} + /> name="name" inputType="text" diff --git a/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/create/index.tsx b/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/create/index.tsx index 5abab05b0..0beef4c45 100644 --- a/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/create/index.tsx +++ b/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/create/index.tsx @@ -16,7 +16,7 @@ /** * - * @author Sebastian Javier Marchano (sebasjm) + * @author Christian Blättler */ import { useTranslationContext } from "@gnu-taler/web-util/browser"; diff --git a/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/update/UpdatePage.tsx b/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/update/UpdatePage.tsx new file mode 100644 index 000000000..3735645bd --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/update/UpdatePage.tsx @@ -0,0 +1,159 @@ +/* + This file is part of GNU Taler + (C) 2021-2023 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 + */ + +/** + * + * @author Christian Blättler + */ + +import { useTranslationContext } from "@gnu-taler/web-util/browser"; +import { h } from "preact"; +import { useState } from "preact/hooks"; +import * as yup from "yup"; +import { MerchantBackend, WithId } from "../../../../declaration.js"; +import { TokenFamilyUpdateSchema } from "../../../../schemas/index.js"; +import { useBackendContext } from "../../../../context/backend.js"; +import { FormErrors, FormProvider } from "../../../../components/form/FormProvider.js"; +import { Input } from "../../../../components/form/Input.js"; +import { InputDate } from "../../../../components/form/InputDate.js"; +import { InputDuration } from "../../../../components/form/InputDuration.js"; +import { AsyncButton } from "../../../../components/exception/AsyncButton.js"; + +type Entity = MerchantBackend.TokenFamilies.TokenFamilyPatchDetail & WithId; + +interface Props { + onUpdate: (d: Entity) => Promise; + onBack?: () => void; + tokenFamily: Entity; +} + +export function UpdatePage({ onUpdate, onBack, tokenFamily }: Props) { + const [value, valueHandler] = useState>({ + ...tokenFamily, + }); + let errors: FormErrors = {}; + + try { + TokenFamilyUpdateSchema.validateSync(value, { + abortEarly: false, + }); + } catch (err) { + if (err instanceof yup.ValidationError) { + const yupErrors = err.inner as yup.ValidationError[]; + 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 submitForm = () => { + if (hasErrors) return Promise.reject(); + + return onUpdate(value as Entity); + } + + const { i18n } = useTranslationContext(); + const { url: backendURL } = useBackendContext() + + return ( +
    +
    +
    +
    +
    +
    +
    + + {backendURL}/tokenfamilies/{tokenFamily.id} + +
    +
    +
    +
    +
    +
    + +
    +
    +
    + + name="token_family" + errors={errors} + object={value} + valueHandler={valueHandler} + > + + name="name" + inputType="text" + label={i18n.str`Name`} + tooltip={i18n.str`user-readable token family name`} + /> + + name="description" + inputType="multiline" + label={i18n.str`Description`} + tooltip={i18n.str`token family description for customers`} + /> + + name="valid_after" + label={i18n.str`Valid After`} + tooltip={i18n.str`token family can issue tokens after this date`} + withTimestampSupport + /> + + name="valid_before" + label={i18n.str`Valid Before`} + tooltip={i18n.str`token family can issue tokens until this date`} + withTimestampSupport + /> + + name="duration" + label={i18n.str`Duration`} + tooltip={i18n.str`validity duration of a issued token`} + withForever + /> + + +
    + {onBack && ( + + )} + + Confirm + +
    +
    +
    +
    +
    +
    + ); +} diff --git a/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/update/index.tsx b/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/update/index.tsx new file mode 100644 index 000000000..4f582d7f3 --- /dev/null +++ b/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/update/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 + */ + +/** + * + * @author Christian Blättler + */ + +import { + ErrorType, + HttpError, + useTranslationContext, +} from "@gnu-taler/web-util/browser"; +import { Fragment, 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, WithId } from "../../../../declaration.js"; +import { Notification } from "../../../../utils/types.js"; +import { UpdatePage } from "./UpdatePage.js"; +import { HttpStatusCode } from "@gnu-taler/taler-util"; +import { useTokenFamilyAPI, useTokenFamilyDetails } from "../../../../hooks/tokenfamily.js"; + +export type Entity = MerchantBackend.TokenFamilies.TokenFamilyPatchDetail & WithId; + +interface Props { + onBack?: () => void; + onConfirm: () => void; + onUnauthorized: () => VNode; + onNotFound: () => VNode; + onLoadError: (e: HttpError) => VNode; + slug: string; +} +export default function UpdateTokenFamily({ + slug, + onConfirm, + onBack, + onUnauthorized, + onNotFound, + onLoadError, +}: Props): VNode { + const { updateTokenFamily } = useTokenFamilyAPI(); + const result = useTokenFamilyDetails(slug); + const [notif, setNotif] = useState(undefined); + + const { i18n } = useTranslationContext(); + + if (result.loading) return ; + if (!result.ok) { + if ( + result.type === ErrorType.CLIENT && + result.status === HttpStatusCode.Unauthorized + ) + return onUnauthorized(); + if ( + result.type === ErrorType.CLIENT && + result.status === HttpStatusCode.NotFound + ) + return onNotFound(); + return onLoadError(result); + } + + const family: Entity = { + id: slug, + name: result.data.name, + description: result.data.description, + description_i18n: result.data.description_i18n || {}, + duration: result.data.duration, + valid_after: result.data.valid_after, + valid_before: result.data.valid_before, + }; + + return ( + + + { + return updateTokenFamily(slug, data) + .then(onConfirm) + .catch((error) => { + setNotif({ + message: i18n.str`could not update token family`, + type: "ERROR", + description: error.message, + }); + }); + }} + /> + + ); +} -- cgit v1.2.3 From 09046010252b134348de8b18c0c99ffea4e3c95d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Christian=20Bl=C3=A4ttler?= Date: Thu, 18 Jan 2024 15:12:57 +0100 Subject: add titles for token family pages --- packages/merchant-backoffice-ui/src/components/menu/index.tsx | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'packages') diff --git a/packages/merchant-backoffice-ui/src/components/menu/index.tsx b/packages/merchant-backoffice-ui/src/components/menu/index.tsx index 7bb7c0c00..a918cb818 100644 --- a/packages/merchant-backoffice-ui/src/components/menu/index.tsx +++ b/packages/merchant-backoffice-ui/src/components/menu/index.tsx @@ -66,6 +66,12 @@ function getInstanceTitle(path: string, id: string): string { return `${id}: Use template`; case InstancePaths.interface: return `${id}: Interface`; + case InstancePaths.token_family_list: + return `${id}: Token families`; + case InstancePaths.token_family_new: + return `${id}: New token family`; + case InstancePaths.token_family_update: + return `${id}: Update token family`; default: return ""; } -- cgit v1.2.3 From 7b3157df9746d12f712e6a4604eccc8ed6b7d0c3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Christian=20Bl=C3=A4ttler?= Date: Tue, 7 May 2024 18:11:47 +0200 Subject: remove routes that accidentally landed in the auditor backoffice ui --- .../auditor-backoffice-ui/src/InstanceRoutes.tsx | 47 ---------------------- 1 file changed, 47 deletions(-) (limited to 'packages') diff --git a/packages/auditor-backoffice-ui/src/InstanceRoutes.tsx b/packages/auditor-backoffice-ui/src/InstanceRoutes.tsx index 16b891ef5..c661fb900 100644 --- a/packages/auditor-backoffice-ui/src/InstanceRoutes.tsx +++ b/packages/auditor-backoffice-ui/src/InstanceRoutes.tsx @@ -69,10 +69,6 @@ import ValidatorCreatePage from "./paths/instance/otp_devices/create/index.js"; import ValidatorListPage from "./paths/instance/otp_devices/list/index.js"; import ValidatorUpdatePage from "./paths/instance/otp_devices/update/index.js"; -import TokenFamilyCreatePage from "./paths/instance/tokenfamilies/create/index.js"; -import TokenFamilyListPage from "./paths/instance/tokenfamilies/list/index.js"; -import TokenFamilyUpdatePage from "./paths/instance/tokenfamilies/update/index.js"; - import TransferCreatePage from "./paths/instance/transfers/create/index.js"; import TransferListPage from "./paths/instance/transfers/list/index.js"; import InstanceUpdatePage, { @@ -99,10 +95,6 @@ export enum InstancePaths { deposit_confirmation_update = "/deposit-confirmation/:pid/update", deposit_confirmation_new = "/deposit-confirmation/new", - token_family_list = "/tokenfamilies", - token_family_update = "/tokenfamilies/:slug/update", - token_family_new = "/tokenfamilies/new", - interface = "/interface", } @@ -438,45 +430,6 @@ export function InstanceRoutes({ route(InstancePaths.transfers_list); }} /> - {/* * - * Token family pages - */} - { - route(InstancePaths.token_family_new); - }} - onSelect={(slug: string) => { - route(InstancePaths.token_family_update.replace(":slug", slug)); - }} - onNotFound={IfAdminCreateDefaultOr(NotFoundPage)} - /> - { - route(InstancePaths.token_family_list); - }} - onBack={() => { - route(InstancePaths.token_family_list); - }} - onNotFound={IfAdminCreateDefaultOr(NotFoundPage)} - /> - { - route(InstancePaths.token_family_list); - }} - onBack={() => { - route(InstancePaths.token_family_list); - }} - /> {/** * Webhooks pages */} -- cgit v1.2.3 From 04447178039569db4da0fd60c819e9fe1bc1df20 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Christian=20Bl=C3=A4ttler?= Date: Tue, 7 May 2024 18:12:20 +0200 Subject: update token families code to allign with new standards --- packages/merchant-backoffice-ui/src/Routing.tsx | 46 +++++++ .../src/components/tokenfamily/TokenFamilyForm.tsx | 12 +- .../src/hooks/tokenfamily.ts | 140 +++++++-------------- .../instance/tokenfamilies/create/CreatePage.tsx | 5 +- .../paths/instance/tokenfamilies/create/index.tsx | 7 +- .../paths/instance/tokenfamilies/list/Table.tsx | 3 +- .../paths/instance/tokenfamilies/list/index.tsx | 120 +++++++++++------- .../instance/tokenfamilies/update/UpdatePage.tsx | 7 +- .../paths/instance/tokenfamilies/update/index.tsx | 63 +++++----- 9 files changed, 214 insertions(+), 189 deletions(-) (limited to 'packages') diff --git a/packages/merchant-backoffice-ui/src/Routing.tsx b/packages/merchant-backoffice-ui/src/Routing.tsx index 665137415..8ccd559b9 100644 --- a/packages/merchant-backoffice-ui/src/Routing.tsx +++ b/packages/merchant-backoffice-ui/src/Routing.tsx @@ -60,6 +60,9 @@ import TemplateQrPage from "./paths/instance/templates/qr/index.js"; import TemplateUpdatePage from "./paths/instance/templates/update/index.js"; import TemplateUsePage from "./paths/instance/templates/use/index.js"; import TokenPage from "./paths/instance/token/index.js"; +import TokenFamilyCreatePage from "./paths/instance/tokenfamilies/create/index.js"; +import TokenFamilyListPage from "./paths/instance/tokenfamilies/list/index.js"; +import TokenFamilyUpdatePage from "./paths/instance/tokenfamilies/update/index.js"; import TransferCreatePage from "./paths/instance/transfers/create/index.js"; import TransferListPage from "./paths/instance/transfers/list/index.js"; import InstanceUpdatePage, { @@ -106,6 +109,10 @@ export enum InstancePaths { templates_use = "/templates/:tid/use", templates_qr = "/templates/:tid/qr", + token_family_list = "/tokenfamilies", + token_family_update = "/tokenfamilies/:slug/update", + token_family_new = "/tokenfamilies/new", + webhooks_list = "/webhooks", webhooks_update = "/webhooks/:tid/update", webhooks_new = "/webhooks/new", @@ -472,6 +479,45 @@ export function Routing(_p: Props): VNode { route(InstancePaths.transfers_list); }} /> + {/* * + * Token family pages + */} + { + route(InstancePaths.token_family_new); + }} + onSelect={(slug: string) => { + route(InstancePaths.token_family_update.replace(":slug", slug)); + }} + // onNotFound={IfAdminCreateDefaultOr(NotFoundPage)} + /> + { + route(InstancePaths.token_family_list); + }} + onBack={() => { + route(InstancePaths.token_family_list); + }} + // onNotFound={IfAdminCreateDefaultOr(NotFoundPage)} + /> + { + route(InstancePaths.token_family_list); + }} + onBack={() => { + route(InstancePaths.token_family_list); + }} + /> {/** * Webhooks pages */} diff --git a/packages/merchant-backoffice-ui/src/components/tokenfamily/TokenFamilyForm.tsx b/packages/merchant-backoffice-ui/src/components/tokenfamily/TokenFamilyForm.tsx index 95441b9fa..1492beb48 100644 --- a/packages/merchant-backoffice-ui/src/components/tokenfamily/TokenFamilyForm.tsx +++ b/packages/merchant-backoffice-ui/src/components/tokenfamily/TokenFamilyForm.tsx @@ -23,8 +23,6 @@ import { useTranslationContext } from "@gnu-taler/web-util/browser"; import { h } from "preact"; import { useCallback, useEffect, useState } from "preact/hooks"; import * as yup from "yup"; -import { useBackendContext } from "../../context/backend.js"; -import { MerchantBackend } from "../../declaration.js"; import { TokenFamilyCreateSchema } from "../../schemas/index.js"; import { FormErrors, FormProvider } from "../form/FormProvider.js"; import { Input } from "../form/Input.js"; @@ -32,8 +30,10 @@ import { InputWithAddon } from "../form/InputWithAddon.js"; import { InputDate } from "../form/InputDate.js"; import { InputDuration } from "../form/InputDuration.js"; import { InputSelector } from "../form/InputSelector.js"; +import { useSessionContext } from "../../context/session.js"; +import { TalerMerchantApi } from "@gnu-taler/taler-util"; -type Entity = MerchantBackend.TokenFamilies.TokenFamilyAddDetail; +type Entity = TalerMerchantApi.TokenFamilyCreateRequest; interface Props { onSubscribe: (c?: () => Entity | undefined) => void; @@ -47,7 +47,7 @@ export function TokenFamilyForm({ onSubscribe }: Props) { name: "", description: "", description_i18n: {}, - kind: "discount", + kind: TalerMerchantApi.TokenFamilyKind.Discount, duration: { d_us: "forever" }, valid_after: { t_s: "never" }, valid_before: { t_s: "never" }, @@ -81,7 +81,7 @@ export function TokenFamilyForm({ onSubscribe }: Props) { onSubscribe(hasErrors ? undefined : submit); }, [submit, hasErrors]); - const backend = useBackendContext(); + const { state } = useSessionContext(); const { i18n } = useTranslationContext(); return ( @@ -94,7 +94,7 @@ export function TokenFamilyForm({ onSubscribe }: Props) { > name="slug" - addonBefore={`${backend.url}/tokenfamily/`} + addonBefore={new URL("tokenfamily/", state.backendUrl.href).href} label={i18n.str`Slug`} tooltip={i18n.str`token family slug to use in URLs (for internal use only)`} /> diff --git a/packages/merchant-backoffice-ui/src/hooks/tokenfamily.ts b/packages/merchant-backoffice-ui/src/hooks/tokenfamily.ts index 0266fe536..62f364972 100644 --- a/packages/merchant-backoffice-ui/src/hooks/tokenfamily.ts +++ b/packages/merchant-backoffice-ui/src/hooks/tokenfamily.ts @@ -13,114 +13,66 @@ You should have received a copy of the GNU General Public License along with GNU Taler; see the file COPYING. If not, see */ - import { - HttpResponse, - HttpResponseOk, - RequestError, -} from "@gnu-taler/web-util/browser"; import { MerchantBackend } from "../declaration.js"; -import { useBackendInstanceRequest, useMatchMutate } from "./backend.js"; +import { useSessionContext } from "../context/session.js"; // FIX default import https://github.com/microsoft/TypeScript/issues/49189 -import _useSWR, { SWRHook, useSWRConfig } from "swr"; +import _useSWR, { SWRHook } from "swr"; +import { AccessToken, TalerHttpError, TalerMerchantManagementResultByMethod } from "@gnu-taler/taler-util"; const useSWR = _useSWR as unknown as SWRHook; -export interface TokenFamilyAPI { - createTokenFamily: ( - data: MerchantBackend.TokenFamilies.TokenFamilyAddDetail, - ) => Promise; - updateTokenFamily: ( - slug: string, - data: MerchantBackend.TokenFamilies.TokenFamilyPatchDetail, - ) => Promise; - deleteTokenFamily: (slug: string) => Promise; -} - -export function useTokenFamilyAPI(): TokenFamilyAPI { - const mutateAll = useMatchMutate(); - const { mutate } = useSWRConfig(); - - const { request } = useBackendInstanceRequest(); +export function useInstanceTokenFamilies() { + const { state: session, lib: { instance } } = useSessionContext(); - const createTokenFamily = async ( - data: MerchantBackend.TokenFamilies.TokenFamilyAddDetail, - ): Promise => { - const res = await request(`/private/tokenfamilies`, { - method: "POST", - data, - }); + // const [offset, setOffset] = useState(); - return await mutateAll(/.*"\/private\/tokenfamilies.*/); - }; - - const updateTokenFamily = async ( - tokenFamilySlug: string, - data: MerchantBackend.TokenFamilies.TokenFamilyPatchDetail, - ): Promise => { - const r = await request(`/private/tokenfamilies/${tokenFamilySlug}`, { - method: "PATCH", - data, + async function fetcher([token, bid]: [AccessToken, number]) { + return await instance.listTokenFamilies(token, { + // limit: PAGINATED_LIST_REQUEST, + // offset: bid === undefined ? undefined: String(bid), + // order: "dec", }); + } - return await mutateAll(/.*"\/private\/tokenfamilies.*/); - }; + const { data, error } = useSWR< + TalerMerchantManagementResultByMethod<"listTokenFamilies">, + TalerHttpError + >([session.token, "offset", "listTokenFamilies"], fetcher); - const deleteTokenFamily = async (tokenFamilySlug: string): Promise => { - await request(`/private/tokenfamilies/${tokenFamilySlug}`, { - method: "DELETE", - }); - await mutate([`/private/tokenfamilies`]); - }; + if (error) return error; + if (data === undefined) return undefined; + if (data.type !== "ok") return data; - return { createTokenFamily, updateTokenFamily, deleteTokenFamily }; + return data; } -export function useInstanceTokenFamilies(): HttpResponse< - (MerchantBackend.TokenFamilies.TokenFamilyEntry)[], - MerchantBackend.ErrorDetail -> { - const { fetcher, multiFetcher } = useBackendInstanceRequest(); - - const { data: list, error: listError } = useSWR< - HttpResponseOk, - RequestError - >([`/private/tokenfamilies`], fetcher, { - refreshInterval: 0, - refreshWhenHidden: false, - revalidateOnFocus: false, - revalidateOnReconnect: false, - refreshWhenOffline: false, - }); - - if (listError) return listError.cause; - - if (list) { - return { ok: true, data: list.data.token_families }; +export function useTokenFamilyDetails(tokenFamilySlug: string) { + const { state: session } = useSessionContext(); + const { lib: { instance } } = useSessionContext(); + + async function fetcher([slug, token]: [string, AccessToken]) { + return await instance.getTokenFamilyDetails(token, slug); } - return { loading: true }; + + const { data, error } = useSWR< + TalerMerchantManagementResultByMethod<"getTokenFamilyDetails">, + TalerHttpError + >([tokenFamilySlug, session.token, "getTokenFamilyDetails"], fetcher); + + if (error) return error; + if (data === undefined) return undefined; + if (data.type !== "ok") return data; + + return data; } -export function useTokenFamilyDetails( - tokenFamilySlug: string, -): HttpResponse< - MerchantBackend.TokenFamilies.TokenFamilyDetail, - MerchantBackend.ErrorDetail -> { - const { fetcher } = useBackendInstanceRequest(); - - const { data, error, isValidating } = useSWR< - HttpResponseOk, - RequestError - >([`/private/tokenfamilies/${tokenFamilySlug}`], fetcher, { - refreshInterval: 0, - refreshWhenHidden: false, - revalidateOnFocus: false, - revalidateOnReconnect: false, - refreshWhenOffline: false, - }); - - if (isValidating) return { loading: true, data: data?.data }; - if (data) return data; - if (error) return error.cause; - return { loading: true }; +export interface TokenFamilyAPI { + createTokenFamily: ( + data: MerchantBackend.TokenFamilies.TokenFamilyAddDetail, + ) => Promise; + updateTokenFamily: ( + slug: string, + data: MerchantBackend.TokenFamilies.TokenFamilyPatchDetail, + ) => Promise; + deleteTokenFamily: (slug: string) => Promise; } diff --git a/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/create/CreatePage.tsx b/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/create/CreatePage.tsx index 7ae9bebe6..cec1f3426 100644 --- a/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/create/CreatePage.tsx +++ b/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/create/CreatePage.tsx @@ -22,12 +22,11 @@ import { useTranslationContext } from "@gnu-taler/web-util/browser"; import { h, VNode } from "preact"; import { AsyncButton } from "../../../../components/exception/AsyncButton.js"; -import { MerchantBackend } from "../../../../declaration.js"; import { useListener } from "../../../../hooks/listener.js"; import { TokenFamilyForm } from "../../../../components/tokenfamily/TokenFamilyForm.js"; -// import { Test } from "../../../../components/tokenfamily/Test.js"; +import { TalerMerchantApi } from "@gnu-taler/taler-util"; -type Entity = MerchantBackend.TokenFamilies.TokenFamilyAddDetail; +type Entity = TalerMerchantApi.TokenFamilyCreateRequest; interface Props { onCreate: (d: Entity) => Promise; diff --git a/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/create/index.tsx b/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/create/index.tsx index 0beef4c45..deee7d0d5 100644 --- a/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/create/index.tsx +++ b/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/create/index.tsx @@ -25,8 +25,8 @@ import { useState } from "preact/hooks"; import { NotificationCard } from "../../../../components/menu/index.js"; import { MerchantBackend } from "../../../../declaration.js"; import { Notification } from "../../../../utils/types.js"; +import { useSessionContext } from "../../../../context/session.js"; import { CreatePage } from "./CreatePage.js"; -import { useTokenFamilyAPI } from "../../../../hooks/tokenfamily.js"; export type Entity = MerchantBackend.TokenFamilies.TokenFamilyAddDetail; interface Props { @@ -34,9 +34,10 @@ interface Props { onConfirm: () => void; } export default function CreateTokenFamily({ onConfirm, onBack }: Props): VNode { - const { createTokenFamily } = useTokenFamilyAPI(); const [notif, setNotif] = useState(undefined); const { i18n } = useTranslationContext(); + const { lib } = useSessionContext(); + const { state } = useSessionContext(); return ( @@ -44,7 +45,7 @@ export default function CreateTokenFamily({ onConfirm, onBack }: Props): VNode { { - return createTokenFamily(request) + return lib.instance.createTokenFamily(state.token, request) .then(() => onConfirm()) .catch((error) => { setNotif({ diff --git a/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/list/Table.tsx b/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/list/Table.tsx index 3d9bf9018..b5ca03cfd 100644 --- a/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/list/Table.tsx +++ b/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/list/Table.tsx @@ -24,8 +24,9 @@ import { Fragment, h, VNode } from "preact"; import { StateUpdater, useState } from "preact/hooks"; import { format } from "date-fns"; import { MerchantBackend } from "../../../../declaration.js"; +import { TalerMerchantApi } from "@gnu-taler/taler-util"; -type Entity = MerchantBackend.TokenFamilies.TokenFamilyEntry; +type Entity = TalerMerchantApi.TokenFamilySummary; interface Props { instances: Entity[]; diff --git a/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/list/index.tsx b/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/list/index.tsx index a5d7413c0..5531174e0 100644 --- a/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/list/index.tsx +++ b/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/list/index.tsx @@ -31,11 +31,15 @@ import { NotificationCard } from "../../../../components/menu/index.js"; import { MerchantBackend } from "../../../../declaration.js"; import { useInstanceTokenFamilies, - useTokenFamilyAPI, } from "../../../../hooks/tokenfamily.js"; import { Notification } from "../../../../utils/types.js"; import { CardTable } from "./Table.js"; -import { HttpStatusCode } from "@gnu-taler/taler-util"; +import { HttpStatusCode, TalerError, TalerMerchantApi, assertUnreachable } from "@gnu-taler/taler-util"; +import { useSessionContext } from "../../../../context/session.js"; +import { ErrorLoadingMerchant } from "../../../../components/ErrorLoadingMerchant.js"; +import { ConfirmModal } from "../../../../components/modal/index.js"; +import { LoginPage } from "../../../login/index.js"; +import { NotFoundPageOrAdminCreate } from "../../../notfound/index.js"; interface Props { onUnauthorized: () => VNode; @@ -52,24 +56,29 @@ export default function TokenFamilyList({ onNotFound, }: Props): VNode { const result = useInstanceTokenFamilies(); - const { deleteTokenFamily, updateTokenFamily } = useTokenFamilyAPI(); const [notif, setNotif] = useState(undefined); + const { lib, state } = useSessionContext(); + const [deleting, setDeleting] = + useState(null); const { i18n } = useTranslationContext(); - if (result.loading) return ; - if (!result.ok) { - if ( - result.type === ErrorType.CLIENT && - result.status === HttpStatusCode.Unauthorized - ) - return onUnauthorized(); - if ( - result.type === ErrorType.CLIENT && - result.status === HttpStatusCode.NotFound - ) - return onNotFound(); - return onLoadError(result); + if (!result) return ; + if (result instanceof TalerError) { + return ; + } + if (result.type === "fail") { + switch (result.case) { + case HttpStatusCode.NotFound: { + return ; + } + case HttpStatusCode.Unauthorized: { + return + } + default: { + assertUnreachable(result); + } + } } return ( @@ -77,42 +86,61 @@ export default function TokenFamilyList({ - updateTokenFamily(slug, fam) - .then(() => - setNotif({ - message: i18n.str`token family updated successfully`, - type: "SUCCESS", - }), - ) - .catch((error) => - setNotif({ - message: i18n.str`could not update the token family`, - type: "ERROR", - description: error.message, - }), - ) - } + onUpdate={async (slug, fam) => { + try { + await lib.instance.updateTokenFamily(state.token, slug, fam); + setNotif({ + message: i18n.str`token family updated successfully`, + type: "SUCCESS", + }); + } catch (error) { + setNotif({ + message: i18n.str`could not update the token family`, + type: "ERROR", + description: error instanceof Error ? error.message : undefined, + }); + } + return; + }} onSelect={(tokenFamily) => onSelect(tokenFamily.slug)} - onDelete={(fam) => - deleteTokenFamily(fam.slug) - .then(() => + onDelete={(fam) => setDeleting(fam)} + /> + + {deleting && ( + setDeleting(null)} + onConfirm={async (): Promise => { + try { + await lib.instance.deleteTokenFamily(state.token, deleting.slug); setNotif({ - message: i18n.str`token family delete successfully`, + message: i18n.str`Token family "${deleting.name}" (SLUG: ${deleting.slug}) has been deleted`, type: "SUCCESS", - }), - ) - .catch((error) => + }); + } catch (error) { setNotif({ - message: i18n.str`could not delete the token family`, + message: i18n.str`Failed to delete token family`, type: "ERROR", - description: error.message, - }), - ) - } - /> + description: error instanceof Error ? error.message : undefined, + }); + } + setDeleting(null); + }} + > +

    + If you delete the "{deleting.name}" token family (Slug:{" "} + {deleting.slug}), all issued tokens will become invalid. +

    +

    + Deleting a token family cannot be undone. +

    +
    + )} ); } diff --git a/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/update/UpdatePage.tsx b/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/update/UpdatePage.tsx index 3735645bd..7ad18c01b 100644 --- a/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/update/UpdatePage.tsx +++ b/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/update/UpdatePage.tsx @@ -25,14 +25,14 @@ import { useState } from "preact/hooks"; import * as yup from "yup"; import { MerchantBackend, WithId } from "../../../../declaration.js"; import { TokenFamilyUpdateSchema } from "../../../../schemas/index.js"; -import { useBackendContext } from "../../../../context/backend.js"; import { FormErrors, FormProvider } from "../../../../components/form/FormProvider.js"; import { Input } from "../../../../components/form/Input.js"; import { InputDate } from "../../../../components/form/InputDate.js"; import { InputDuration } from "../../../../components/form/InputDuration.js"; import { AsyncButton } from "../../../../components/exception/AsyncButton.js"; +import { TalerMerchantApi } from "@gnu-taler/taler-util"; -type Entity = MerchantBackend.TokenFamilies.TokenFamilyPatchDetail & WithId; +type Entity = TalerMerchantApi.TokenFamilyUpdateRequest; interface Props { onUpdate: (d: Entity) => Promise; @@ -71,7 +71,6 @@ export function UpdatePage({ onUpdate, onBack, tokenFamily }: Props) { } const { i18n } = useTranslationContext(); - const { url: backendURL } = useBackendContext() return (
    @@ -82,7 +81,7 @@ export function UpdatePage({ onUpdate, onBack, tokenFamily }: Props) {
    - {backendURL}/tokenfamilies/{tokenFamily.id} + Token Family: {tokenFamily.name}
    diff --git a/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/update/index.tsx b/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/update/index.tsx index 4f582d7f3..068235e14 100644 --- a/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/update/index.tsx +++ b/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/update/index.tsx @@ -28,59 +28,58 @@ import { Fragment, 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, WithId } from "../../../../declaration.js"; import { Notification } from "../../../../utils/types.js"; import { UpdatePage } from "./UpdatePage.js"; -import { HttpStatusCode } from "@gnu-taler/taler-util"; -import { useTokenFamilyAPI, useTokenFamilyDetails } from "../../../../hooks/tokenfamily.js"; +import { HttpStatusCode, TalerError, TalerMerchantApi, assertUnreachable } from "@gnu-taler/taler-util"; +import { useTokenFamilyDetails } from "../../../../hooks/tokenfamily.js"; +import { useSessionContext } from "../../../../context/session.js"; +import { ErrorLoadingMerchant } from "../../../../components/ErrorLoadingMerchant.js"; +import { LoginPage } from "../../../login/index.js"; +import { NotFoundPageOrAdminCreate } from "../../../notfound/index.js"; -export type Entity = MerchantBackend.TokenFamilies.TokenFamilyPatchDetail & WithId; +type Entity = TalerMerchantApi.TokenFamilyUpdateRequest; interface Props { onBack?: () => void; onConfirm: () => void; - onUnauthorized: () => VNode; - onNotFound: () => VNode; - onLoadError: (e: HttpError) => VNode; slug: string; } export default function UpdateTokenFamily({ slug, onConfirm, onBack, - onUnauthorized, - onNotFound, - onLoadError, }: Props): VNode { - const { updateTokenFamily } = useTokenFamilyAPI(); const result = useTokenFamilyDetails(slug); const [notif, setNotif] = useState(undefined); + const { lib, state } = useSessionContext(); const { i18n } = useTranslationContext(); - if (result.loading) return ; - if (!result.ok) { - if ( - result.type === ErrorType.CLIENT && - result.status === HttpStatusCode.Unauthorized - ) - return onUnauthorized(); - if ( - result.type === ErrorType.CLIENT && - result.status === HttpStatusCode.NotFound - ) - return onNotFound(); - return onLoadError(result); + if (!result) return ; + if (result instanceof TalerError) { + return ; + } + if (result.type === "fail") { + switch (result.case) { + case HttpStatusCode.NotFound: { + return ; + } + case HttpStatusCode.Unauthorized: { + return + } + default: { + assertUnreachable(result); + } + } } const family: Entity = { - id: slug, - name: result.data.name, - description: result.data.description, - description_i18n: result.data.description_i18n || {}, - duration: result.data.duration, - valid_after: result.data.valid_after, - valid_before: result.data.valid_before, + name: result.body.name, + description: result.body.description, + description_i18n: result.body.description_i18n || {}, + duration: result.body.duration, + valid_after: result.body.valid_after, + valid_before: result.body.valid_before, }; return ( @@ -90,7 +89,7 @@ export default function UpdateTokenFamily({ tokenFamily={family} onBack={onBack} onUpdate={(data) => { - return updateTokenFamily(slug, data) + return lib.instance.updateTokenFamily(state.token, slug, data) .then(onConfirm) .catch((error) => { setNotif({ -- cgit v1.2.3 From a9daad793cf66061e14fa4a847e1b595e26493e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Christian=20Bl=C3=A4ttler?= Date: Wed, 22 May 2024 20:31:49 +0200 Subject: crudly fix build errors --- packages/taler-util/src/http-impl.node.ts | 2 +- packages/taler-util/src/url.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'packages') diff --git a/packages/taler-util/src/http-impl.node.ts b/packages/taler-util/src/http-impl.node.ts index 45a12c258..77bdf575a 100644 --- a/packages/taler-util/src/http-impl.node.ts +++ b/packages/taler-util/src/http-impl.node.ts @@ -188,7 +188,7 @@ export class HttpLibImpl implements HttpRequestLibrary { ); } - let timeoutHandle: NodeJS.Timer | undefined = undefined; + let timeoutHandle: NodeJS.Timeout | undefined = undefined; let cancelCancelledHandler: (() => void) | undefined = undefined; const doCleanup = () => { diff --git a/packages/taler-util/src/url.ts b/packages/taler-util/src/url.ts index 149997f3f..1b5626626 100644 --- a/packages/taler-util/src/url.ts +++ b/packages/taler-util/src/url.ts @@ -94,7 +94,7 @@ if (useOwnUrlImp || !_URL) { _URL = URLImpl; } -export const URL: URLCtor = _URL; +export const URL = _URL; // @ts-ignore let _URLSearchParams = globalThis.URLSearchParams; -- cgit v1.2.3 From 635d710203bd88843ba16bbee7ab43ad02d295ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Christian=20Bl=C3=A4ttler?= Date: Wed, 22 May 2024 21:12:37 +0200 Subject: convert token family duration --- .../instance/tokenfamilies/update/UpdatePage.tsx | 31 ++++++++++++++++------ 1 file changed, 23 insertions(+), 8 deletions(-) (limited to 'packages') diff --git a/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/update/UpdatePage.tsx b/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/update/UpdatePage.tsx index 7ad18c01b..184e37b9c 100644 --- a/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/update/UpdatePage.tsx +++ b/packages/merchant-backoffice-ui/src/paths/instance/tokenfamilies/update/UpdatePage.tsx @@ -30,20 +30,29 @@ import { Input } from "../../../../components/form/Input.js"; import { InputDate } from "../../../../components/form/InputDate.js"; import { InputDuration } from "../../../../components/form/InputDuration.js"; import { AsyncButton } from "../../../../components/exception/AsyncButton.js"; -import { TalerMerchantApi } from "@gnu-taler/taler-util"; +import { Duration, TalerMerchantApi } from "@gnu-taler/taler-util"; -type Entity = TalerMerchantApi.TokenFamilyUpdateRequest; +type Entity = Omit & { + duration: Duration, +}; interface Props { - onUpdate: (d: Entity) => Promise; + onUpdate: (d: TalerMerchantApi.TokenFamilyUpdateRequest) => Promise; onBack?: () => void; - tokenFamily: Entity; + tokenFamily: TalerMerchantApi.TokenFamilyUpdateRequest; +} + +function convert(from: TalerMerchantApi.TokenFamilyUpdateRequest) { + const { duration, ...rest } = from; + + const converted = { + duration: Duration.fromTalerProtocolDuration(duration), + }; + return { ...converted, ...rest }; } export function UpdatePage({ onUpdate, onBack, tokenFamily }: Props) { - const [value, valueHandler] = useState>({ - ...tokenFamily, - }); + const [value, valueHandler] = useState>(convert(tokenFamily)); let errors: FormErrors = {}; try { @@ -67,7 +76,13 @@ export function UpdatePage({ onUpdate, onBack, tokenFamily }: Props) { const submitForm = () => { if (hasErrors) return Promise.reject(); - return onUpdate(value as Entity); + const { duration, ...rest } = value as Required; + const result: TalerMerchantApi.TokenFamilyUpdateRequest = { + ...rest, + duration: Duration.toTalerProtocolDuration(duration), + }; + + return onUpdate(result); } const { i18n } = useTranslationContext(); -- cgit v1.2.3 From 9d0fc80a905e02a0a0b63dd547daac6e7b17fb52 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Christian=20Bl=C3=A4ttler?= Date: Wed, 22 May 2024 21:13:03 +0200 Subject: remove unused --- packages/merchant-backoffice-ui/src/Routing.tsx | 6 ------ .../src/paths/instance/tokenfamilies/list/index.tsx | 3 --- 2 files changed, 9 deletions(-) (limited to 'packages') diff --git a/packages/merchant-backoffice-ui/src/Routing.tsx b/packages/merchant-backoffice-ui/src/Routing.tsx index 8ccd559b9..4ffad2d6d 100644 --- a/packages/merchant-backoffice-ui/src/Routing.tsx +++ b/packages/merchant-backoffice-ui/src/Routing.tsx @@ -485,28 +485,22 @@ export function Routing(_p: Props): VNode { { route(InstancePaths.token_family_new); }} onSelect={(slug: string) => { route(InstancePaths.token_family_update.replace(":slug", slug)); }} - // onNotFound={IfAdminCreateDefaultOr(NotFoundPage)} /> { route(InstancePaths.token_family_list); }} onBack={() => { route(InstancePaths.token_family_list); }} - // onNotFound={IfAdminCreateDefaultOr(NotFoundPage)} /> ) => VNode; } export default function TokenFamilyList({ - onUnauthorized, - onLoadError, onCreate, onSelect, - onNotFound, }: Props): VNode { const result = useInstanceTokenFamilies(); const [notif, setNotif] = useState(undefined); -- cgit v1.2.3