hooks#useSettings JavaScript Examples

The following examples show how to use hooks#useSettings. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.jsx    From apps with GNU Affero General Public License v3.0 5 votes vote down vote up
Dashboard = ({
    route: {
        handler: {
            props: { tab, action, secondaryAction, id },
        },
    },
}) => {
    const settings = useSettings();
    const mediator = useMediator();

    let content, modal;

    if (mediator.keyPairs === null) {
        modal = <UploadKeyPairsModal />;
    }

    if (mediator.keyPairs !== null) {
        switch (tab) {
            case 'settings':
                content = (
                    <Settings
                        action={action}
                        secondaryAction={secondaryAction}
                        id={id}
                    />
                );
                break;
            case 'providers':
                content = <Providers action={action} id={secondaryAction} />;
                break;
            case 'stats':
                content = (
                    <Stats
                        action={action}
                        secondaryAction={secondaryAction}
                        id={id}
                    />
                );
                break;
        }
    }

    let invalidKeyMessage;

    // to do: implement validation flow
    /*
    if (mediator.validKeyPairs !== undefined && validKeyPairs.valid === false) {
        invalidKeyMessage = (
            <Message type="danger">
                <T t={t} k="invalidKey" />
            </Message>
        );
    }
    */

    return (
        <CenteredCard size="fullwidth" tight>
            <CardHeader>
                <Tabs>
                    <Tab
                        active={tab === 'providers'}
                        href="/mediator/providers"
                    >
                        <T t={t} k="providers.title" />
                    </Tab>
                    <Tab active={tab === 'stats'} href="/mediator/stats">
                        <T t={t} k="stats.title" />
                    </Tab>
                    <Tab active={tab === 'settings'} href="/mediator/settings">
                        <T t={t} k="settings.title" />
                    </Tab>
                </Tabs>
            </CardHeader>
            {modal}
            {content}
        </CenteredCard>
    );
}
Example #2
Source File: appointments.jsx    From apps with GNU Affero General Public License v3.0 5 votes vote down vote up
OfferDetails = ({ offer }) => {
    const settings = useSettings();
    const lang = settings.get('lang');
    const notices = [];
    const properties = settings.get('appointmentProperties');
    for (const [category, values] of Object.entries(properties)) {
        for (const [k, v] of Object.entries(values.values)) {
            if (
                (offer[k] === true ||
                    (offer.properties !== undefined &&
                        offer.properties[category] === k)) &&
                v.notice !== undefined &&
                v.infosUrl !== undefined &&
                v.anamnesisUrl !== undefined
            )
                notices.push(
                    <F key="k">
                        <p>{v.notice[lang]}</p>
                        <p>
                            <T
                                t={t}
                                k="offer-notice-text"
                                vaccine={
                                    <strong key="vaccine">{v[lang]}</strong>
                                }
                                info={
                                    <a
                                        key="infos"
                                        target="_blank"
                                        href={v.infosUrl[lang]}
                                    >
                                        <T t={t} k="info" />
                                    </a>
                                }
                                anamnesis={
                                    <a
                                        key="anamnesis"
                                        target="_blank"
                                        href={v.anamnesisUrl[lang]}
                                    >
                                        <T t={t} k="anamnesis" />
                                    </a>
                                }
                            />
                        </p>
                    </F>
                );
        }
    }
    return <div className="kip-offer-details">{notices}</div>;
}
Example #3
Source File: new-appointment.jsx    From apps with GNU Affero General Public License v3.0 4 votes vote down vote up
NewAppointment = withForm(
    ({ route, action, id, form: { valid, error, data, set, reset } }) => {
        let actionUrl = '';
        const settings = useSettings();
        const router = useRouter();
        if (action !== undefined) actionUrl = `/${action}`;
        if (id !== undefined) actionUrl += `/view/${id}`;
        const [saving, setSaving] = useState(false);
        const cancel = () =>
            router.navigateToUrl(`/provider/schedule${actionUrl}`);

        let appointment;

        if (id !== undefined)
            appointment = appointments.find((app) => hexId(app.id) === id);

        const save = () => {
            let action;
            setSaving(true);
            // we remove unnecessary fields like 'time' and 'date'
            delete data.time;
            delete data.date;
            if (appointment !== undefined) action = updateAppointmentAction;
            else action = createAppointmentAction;
            const promise = action(data, appointment);
            promise.finally(() => setSaving(false));
            promise.then(() => {
                // we reload the appointments
                openAppointmentsAction();
                // and we go back to the schedule view
                router.navigateToUrl(`/provider/schedule${actionUrl}`);
            });
        };

        useEffectOnce(() => {
            if (appointment !== undefined) {
                const appointmentData = {
                    time: formatTime(appointment.timestamp),
                    date: formatDate(appointment.timestamp),
                    slots: appointment.slots,
                    duration: appointment.duration,
                };
                for (const [_, v] of Object.entries(properties)) {
                    for (const [kk, _] of Object.entries(v.values)) {
                        if (appointment[kk] !== undefined)
                            appointmentData[kk] = true;
                        else delete appointmentData[kk];
                    }
                }
                reset(appointmentData);
            } else {
                const newData = {
                    duration: data.duration || 30,
                    slots: data.slots || 1,
                };

                let firstProperty;
                let found = false;
                addProps: for (const [_, v] of Object.entries(properties)) {
                    for (const [kk, _] of Object.entries(v.values)) {
                        if (firstProperty === undefined) firstProperty = kk;
                        if (data[kk] !== undefined) {
                            found = true;
                            newData[kk] = true;
                            break addProps;
                        }
                    }
                }
                if (!found) newData[firstProperty] = true;

                if (route.hashParams !== undefined) {
                    if (route.hashParams.timestamp !== undefined) {
                        const date = new Date(route.hashParams.timestamp);
                        newData.time = formatTime(date);
                        newData.date = formatDate(date);
                    }
                }
                reset(newData);
            }
        });

        const properties = settings.get('appointmentProperties');

        const apptProperties = Object.entries(properties).map(([k, v]) => {
            const options = Object.entries(v.values).map(([kv, vv]) => ({
                value: kv,
                key: vv,
                title: <T t={properties} k={`${k}.values.${kv}`} />,
            }));

            let currentOption;

            for (const [k, v] of Object.entries(data)) {
                for (const option of options) {
                    if (k === option.value && v === true) currentOption = k;
                }
            }

            const changeTo = (option) => {
                const newData = { ...data };
                for (const option of options) newData[option.value] = undefined;
                newData[option.value] = true;
                reset(newData);
            };

            return (
                <React.Fragment key={k}>
                    <h2>
                        <T t={properties} k={`${k}.title`} />
                    </h2>
                    <RichSelect
                        options={options}
                        value={currentOption}
                        onChange={(option) => changeTo(option)}
                    />
                </React.Fragment>
            );
        });

        const durations = [
            5, 10, 15, 20, 30, 45, 60, 90, 120, 150, 180, 210, 240,
        ].map((v) => ({
            value: v,
            title: (
                <T
                    t={t}
                    k={`schedule.appointment.duration.title`}
                    duration={v}
                />
            ),
        }));

        return (
            <Modal
                saveDisabled={!valid || saving}
                cancelDisabled={saving}
                closeDisabled={saving}
                className="kip-new-appointment"
                onSave={save}
                waiting={saving}
                onCancel={cancel}
                onClose={cancel}
                title={
                    <T
                        t={t}
                        k={
                            appointment !== undefined
                                ? 'edit-appointment.title'
                                : 'new-appointment.title'
                        }
                    />
                }
            >
                <FormComponent>
                    <FieldSet>
                        <div className="kip-field">
                            <Label htmlFor="date">
                                <T t={t} k="new-appointment.date" />
                            </Label>
                            <ErrorFor error={error} field="date" />
                            <input
                                value={data.date || ''}
                                type="date"
                                className="bulma-input"
                                onChange={(e) => set('date', e.target.value)}
                            />
                        </div>
                        <div className="kip-field">
                            <Label htmlFor="time">
                                <T t={t} k="new-appointment.time" />
                            </Label>
                            <ErrorFor error={error} field="time" />
                            <input
                                type="time"
                                className="bulma-input"
                                value={data.time || ''}
                                onChange={(e) => set('time', e.target.value)}
                                step={60}
                            />
                        </div>
                        <div className="kip-field kip-is-fullwidth kip-slider">
                            <Label htmlFor="slots">
                                <T t={t} k="new-appointment.slots" />
                            </Label>
                            <ErrorFor error={error} field="slots" />
                            <input
                                type="number"
                                className="bulma-input"
                                value={data.slots || 1}
                                onChange={(e) =>
                                    set('slots', parseInt(e.target.value))
                                }
                                step={1}
                                min={1}
                                max={50}
                            />
                        </div>
                        <div className="kip-field kip-is-fullwidth">
                            <RichSelect
                                id="duration"
                                value={data.duration || 30}
                                onChange={(value) =>
                                    set('duration', value.value)
                                }
                                options={durations}
                            />
                        </div>

                        <div className="kip-field kip-is-fullwidth">
                            {apptProperties}
                        </div>
                    </FieldSet>
                </FormComponent>
            </Modal>
        );
    },
    AppointmentForm,
    'form'
)
Example #4
Source File: verify.jsx    From apps with GNU Affero General Public License v3.0 4 votes vote down vote up
Verify = () => {
    const router = useRouter();
    const settings = useSettings();
    const provider = useProvider();

    const [submitting, setSubmitting] = useState(false);
    const [response, setResponse] = useState(null);

    const submit = async () => {
        if (submitting) return;

        setSubmitting(true);
        const response = await provider.storeData();
        setSubmitting(false);

        setResponse(response);

        if (response.status === Status.Succeeded)
            router.navigateToUrl('/provider/setup/store-secrets');
    };

    let failedMessage;
    let failed;

    if (response && response.status === Status.Failed) {
        console.log(response);
        failed = true;
        if (
            response.error.error !== undefined &&
            response.error.error.code === 401
        ) {
            failedMessage = (
                <Message type="danger">
                    <T t={t} k="wizard.failed.invalid-code" />
                </Message>
            );
        }
    }

    if (failed && !failedMessage)
        failedMessage = (
            <Message type="danger">
                <T t={t} k="wizard.failed.notice" />
            </Message>
        );

    return (
        <>
            <CardContent>
                {failedMessage}
                <p className="kip-verify-notice">
                    <T
                        t={t}
                        k="verify.text"
                        link={
                            <A
                                key="letUsKnow"
                                external
                                href={settings.get('supportEmail')}
                            >
                                <T t={t} k="wizard.letUsKnow" key="letUsKnow" />
                            </A>
                        }
                    />
                </p>
                <ProviderData />
            </CardContent>
            <CardFooter>
                <Button
                    type={failed ? 'danger' : 'success'}
                    disabled={submitting}
                    onClick={submit}
                >
                    <T
                        t={t}
                        k={
                            failed
                                ? 'wizard.failed.title'
                                : submitting
                                ? 'wizard.please-wait'
                                : 'wizard.continue'
                        }
                    />
                </Button>
            </CardFooter>
        </>
    );
}
Example #5
Source File: appointments.jsx    From apps with GNU Affero General Public License v3.0 4 votes vote down vote up
InvitationDetails = ({}) => {
    const settings = useSettings();

    const [confirming, setConfirming] = useState(false);
    const [initialized, setInitialized] = useState(false);

    useEffect(() => {
        if (initialized) return;
        setInitialized(true);
        toggleOffersAction(null);
    });

    const toggle = (offer) => {
        toggleOffersAction(offer, data.offers);
    };

    const doConfirmOffers = () => {
        const selectedOffers = [];
        // we add the selected offers in the order the user chose
        for (const offerID of toggleOffers.data) {
            const offer = data.offers.find((offer) => offer.id === offerID);
            selectedOffers.push(offer);
        }
        setConfirming(true);
        const p = confirmOffersAction(selectedOffers, data, tokenData.data);
        p.then(() => {
            acceptedInvitationAction();
        });
        p.finally(() => {
            setConfirming(false);
            toggleOffersAction(null);
        });
    };

    let content;

    const properties = settings.get('appointmentProperties');
    // to do: use something better than the index i for the key?
    const offers = data.offers
        .filter((offer) => offer.slotData.some((sl) => sl.open))
        .filter((a) => new Date(a.timestamp) > new Date())
        .sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp))
        .map((offer, i) => {
            const d = new Date(offer.timestamp);
            const selected = toggleOffers.data.includes(offer.id);
            let pref;
            if (selected) pref = toggleOffers.data.indexOf(offer.id) + 1;
            return (
                <tr
                    key={offer.id}
                    className={classNames(`kip-pref-${pref}`, {
                        'kip-selected': selected,
                        'kip-failed': false,
                    })}
                    onClick={() => toggle(offer)}
                >
                    <td>{selected ? pref : '-'}</td>
                    <td>
                        {d.toLocaleString('de-DE', {
                            month: '2-digit',
                            day: '2-digit',
                            year: '2-digit',
                            hour: '2-digit',
                            minute: '2-digit',
                        })}
                    </td>
                    <td>{formatDuration(offer.duration, settings, t)}</td>
                    <td>
                        <PropertyTags appointment={offer} />
                    </td>
                </tr>
            );
        });

    let offerDetails;

    if (offers.length === 0)
        offerDetails = (
            <Message type="warning">
                <T t={t} k="no-offers-anymore" />
            </Message>
        );
    else
        offerDetails = (
            <table className="bulma-table bulma-is-striped bulma-is-fullwidth">
                <thead>
                    <tr>
                        <th>
                            <T t={t} k="appointment-preference" />
                        </th>
                        <th>
                            <T t={t} k="appointment-date" />
                        </th>
                        <th>
                            <T t={t} k="appointment-duration" />
                        </th>
                        <th>
                            <T t={t} k="appointment-vaccine" />
                        </th>
                    </tr>
                </thead>
                <tbody>{offers}</tbody>
            </table>
        );

    return (
        <F>
            <CardContent>
                <div className="kip-invitation-details">
                    <ProviderDetails data={data.provider} />
                    <p>
                        <T t={t} k="appointments-notice" />
                    </p>
                    {offerDetails}
                </div>
            </CardContent>
            <CardFooter>
                <Button
                    waiting={confirming}
                    onClick={doConfirmOffers}
                    disabled={
                        confirming ||
                        Object.keys(
                            toggleOffers.data.filter((id) =>
                                data.offers.find((of) => of.id === id)
                            )
                        ).length === 0
                    }
                    type="success"
                >
                    <T t={t} k="confirm-appointment" />
                </Button>
            </CardFooter>
        </F>
    );
}
Example #6
Source File: store-secrets.jsx    From apps with GNU Affero General Public License v3.0 4 votes vote down vote up
StoreOnline = ({ secret, embedded, hideNotice }) => {
    const [bookmarkModal, setBookmarkModal] = useState(false);
    const [copyModal, setCopyModal] = useState(false);
    const settings = useSettings();
    const user = useUser();

    let modal;

    const showBookmarkModal = () => {
        history.pushState(
            {},
            settings.t(t, 'store-secrets.restore.title'),
            `/user/restore#${user.secret}`
        );
        setBookmarkModal(true);
    };

    const hideBookmarkModal = () => {
        history.back();
        setBookmarkModal(false);
    };

    if (bookmarkModal)
        modal = (
            <Modal
                title={<T t={t} k="store-secrets.bookmark-modal.title" />}
                onClose={hideBookmarkModal}
            >
                <T t={t} k="store-secrets.bookmark-modal.text" />
            </Modal>
        );

    const chunks = user.secret.match(/.{1,4}/g);

    const fragments = [];
    for (let i = 0; i < chunks.length; i++) {
        fragments.push(<F key={`${i}-main`}>{chunks[i]}</F>);
        if (i < chunks.length - 1)
            fragments.push(
                <strong key={`${i}-dot`} style={{ userSelect: 'none' }}>
                    ยท
                </strong>
            );
    }

    return (
        <F>
            {modal}
            {!embedded && (
                <p className="kip-secrets-notice">
                    <T t={t} k="store-secrets.online.text" safe />
                </p>
            )}
            <div
                className={
                    'kip-secrets-box' + (embedded ? ' kip-is-embedded' : '')
                }
            >
                {
                    <F>
                        <div className="kip-uid">
                            {!hideNotice && (
                                <span>
                                    <T t={t} k="store-secrets.secret" />
                                </span>
                            )}
                            <code>{fragments}</code>
                        </div>
                    </F>
                }
            </div>
            {!embedded && (
                <div className="kip-secrets-links">
                    <A
                        className="bulma-button bulma-is-small"
                        onClick={showBookmarkModal}
                    >
                        <T t={t} k="store-secrets.bookmark" />
                    </A>
                </div>
            )}
        </F>
    );
}