gitscope
https://dev.kronoz.win/r/marzneshin.git
dashboard/src/features/users/dialogs/mutation/sections/use-expiration-method-tabs.ts · v0.3.0
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 88321ab Mardin 2y ago else if (entity.expire !== undefined && entity.expire !== null)
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 88321ab Mardin 2y ago const defaultExpirationMethodTab =
21 88321ab Mardin 2y ago (entity !== null) ? getUserExpirationMethod(entity) : 'determined'
22 5875753 Mrdn 2y ago const [
23 5875753 Mrdn 2y ago selectedExpirationMethodTab,
24 5875753 Mrdn 2y ago setSelectedExpirationMethodTab
25 5875753 Mrdn 2y ago ] = useState<ExpirationMethodStrategy | string>(defaultExpirationMethodTab);
26 5875753 Mrdn 2y ago
27 5875753 Mrdn 2y ago useEffect(() => {
28 5875753 Mrdn 2y ago form.setValue("status", "active")
29 5875753 Mrdn 2y ago if (selectedExpirationMethodTab === 'onhold') {
30 5875753 Mrdn 2y ago form.setValue("status", "on_hold")
31 5875753 Mrdn 2y ago form.setValue("expire", undefined);
32 5875753 Mrdn 2y ago form.clearErrors("expire");
33 5875753 Mrdn 2y ago } else if (selectedExpirationMethodTab === "unlimited") {
34 88321ab Mardin 2y ago form.setValue("expire", 0);
35 5875753 Mrdn 2y ago form.setValue("on_hold_expire_duration", undefined);
36 5875753 Mrdn 2y ago form.setValue("on_hold_timeout", undefined);
37 5875753 Mrdn 2y ago form.clearErrors("expire");
38 5875753 Mrdn 2y ago form.clearErrors("on_hold_expire_duration");
39 5875753 Mrdn 2y ago form.clearErrors("on_hold_timeout");
40 5875753 Mrdn 2y ago } else {
41 5875753 Mrdn 2y ago form.setValue("on_hold_expire_duration", 0);
42 5875753 Mrdn 2y ago form.setValue("on_hold_timeout", null);
43 5875753 Mrdn 2y ago form.clearErrors("on_hold_expire_duration");
44 5875753 Mrdn 2y ago form.clearErrors("on_hold_timeout");
45 5875753 Mrdn 2y ago }
46 5875753 Mrdn 2y ago // eslint-disable-next-line
47 5875753 Mrdn 2y ago }, [selectedExpirationMethodTab]);
48 5875753 Mrdn 2y ago
49 5875753 Mrdn 2y ago return { selectedExpirationMethodTab, defaultExpirationMethodTab, setSelectedExpirationMethodTab }
50 5875753 Mrdn 2y ago }