File size: 1,950 Bytes
1e5ae4b
 
 
 
 
 
 
 
0c0f5cc
1e5ae4b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0c0f5cc
1e5ae4b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import type { AdminRole, AdminUser, UserFilterForm, UserForm } from '@/types/admin';

export const emptyUserForm: UserForm = {
    email: '',
    identity_number: '',
    is_active: true,
    is_superuser: false,
    name: '',
    password: '',
    phone: '',
    role: 'student',
    user_token: '',
};

export function stringValue(value: unknown): string {
    if (value === null || value === undefined) {
        return '';
    }

    return String(value);
}

export function roleLabel(role?: AdminRole | null): string {
    return (
        {
            admin: 'Admin',
            lecturer: 'Dosen',
            student: 'Mahasiswa',
        }[role ?? 'student'] ?? 'Mahasiswa'
    );
}

export function isUserActive(user: AdminUser): boolean {
    if (typeof user.is_active === 'boolean') {
        return user.is_active;
    }

    return user.status === 'active';
}

export function formatDate(value?: string | null): string {
    if (!value) {
        return '-';
    }

    return value.split('T')[0] || value;
}

export function readError(errors: object, key: string): string | undefined {
    return (errors as Record<string, string | undefined>)[key];
}

export function userToForm(user: AdminUser): UserForm {
    return {
        email: stringValue(user.email),
        identity_number: stringValue(user.identity_number),
        is_active: isUserActive(user),
        is_superuser: Boolean(user.is_superuser),
        name: stringValue(user.name),
        password: '',
        phone: stringValue(user.phone),
        role: user.role ?? 'student',
        user_token: stringValue(user.user_token),
    };
}

export function buildFilterQuery(filters: UserFilterForm): Record<string, string> {
    return Object.fromEntries(
        Object.entries({
            email: filters.email,
            name: filters.name,
            role: filters.role === 'all' ? '' : filters.role,
        }).filter(([, value]) => value !== ''),
    );
}