gitscope
https://dev.kronoz.win/r/marzneshin.git
dashboard/src/features/users/dialogs/mutation/sections/use-expiration-method-tabs.ts · v0.3.0-alpha11
Source
1 5875753 Mrdn 2y ago import { UserMutationType } from "@marzneshin/features/users";
2 5875753 Mrdn 2y ago import { useEffect, useState } from "react";
3 5875753 Mrdn 2y ago import { useFormContext } from "react-hook-form";
4 5875753 Mrdn 2y ago
5 5875753 Mrdn 2y ago type ExpirationMethodStrategy = "onhold" | "determined" | "unlimited";
6 5875753 Mrdn 2y ago
7 5875753 Mrdn 2y ago const getUserExpirationMethod = (entity: UserMutationType): ExpirationMethodStrategy => {
8 5875753 Mrdn 2y ago if (entity.status === "on_hold")
9 5875753 Mrdn 2y ago return 'onhold'
10 5875753 Mrdn 2y ago else if (entity.expire !== undefined)
11 5875753 Mrdn 2y ago return 'determined'
12 5875753 Mrdn 2y ago else
13 5875753 Mrdn 2y ago return 'unlimited'
14 5875753 Mrdn 2y ago }
15 5875753 Mrdn 2y ago
16 5875753 Mrdn 2y ago
17 5875753 Mrdn 2y ago export const useExpirationMethodTabs = ({ entity }: { entity: UserMutationType | null }) => {
18 5875753 Mrdn 2y ago const form = useFormContext()
19 5875753 Mrdn 2y ago
20 5875753 Mrdn 2y ago const defaultExpirationMethodTab = entity?.username ? getUserExpirationMethod(entity) : 'determined'
21 5875753 Mrdn 2y ago const [
22 5875753 Mrdn 2y ago selectedExpirationMethodTab,
23 5875753 Mrdn 2y ago setSelectedExpirationMethodTab
24 5875753 Mrdn 2y ago ] = useState<ExpirationMethodStrategy | string>(defaultExpirationMethodTab);
25 5875753 Mrdn 2y ago
26 5875753 Mrdn 2y ago useEffect(() => {
27 5875753 Mrdn 2y ago form.setValue("status", "active")
28 5875753 Mrdn 2y ago if (selectedExpirationMethodTab === 'onhold') {
29 5875753 Mrdn 2y ago form.setValue("status", "on_hold")
30 5875753 Mrdn 2y ago form.setValue("expire", undefined);
31 5875753 Mrdn 2y ago form.clearErrors("expire");
32 5875753 Mrdn 2y ago } else if (selectedExpirationMethodTab === "unlimited") {
33 5875753 Mrdn 2y ago form.setValue("expire", undefined);
34 5875753 Mrdn 2y ago form.setValue("on_hold_expire_duration", undefined);
35 5875753 Mrdn 2y ago form.setValue("on_hold_timeout", undefined);
36 5875753 Mrdn 2y ago form.clearErrors("expire");
37 5875753 Mrdn 2y ago form.clearErrors("on_hold_expire_duration");
38 5875753 Mrdn 2y ago form.clearErrors("on_hold_timeout");
39 5875753 Mrdn 2y ago } else {
40 5875753 Mrdn 2y ago form.setValue("on_hold_expire_duration", 0);
41 5875753 Mrdn 2y ago form.setValue("on_hold_timeout", null);
42 5875753 Mrdn 2y ago form.clearErrors("on_hold_expire_duration");
43 5875753 Mrdn 2y ago form.clearErrors("on_hold_timeout");
44 5875753 Mrdn 2y ago }
45 5875753 Mrdn 2y ago // eslint-disable-next-line
46 5875753 Mrdn 2y ago }, [selectedExpirationMethodTab]);
47 5875753 Mrdn 2y ago
48 5875753 Mrdn 2y ago return { selectedExpirationMethodTab, defaultExpirationMethodTab, setSelectedExpirationMethodTab }
49 5875753 Mrdn 2y ago }