All files / pages AccountsPage.tsx

66.66% Statements 40/60
83.33% Branches 20/24
43.75% Functions 7/16
66.66% Lines 40/60

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266                                                        43x 43x 43x     43x 43x 43x 43x 43x 43x     43x 43x 43x 43x 43x   43x 18x 18x   18x 18x             14x   3x   17x       43x 17x     43x                 43x 1x 1x 1x     43x         43x         43x         43x         43x         43x 1x 1x     43x               2x                                               4x                                                                                                                                                                                                                                          
/**
 * Accounts management page
 * Full implementation with CRUD operations, search, and pagination
 */
 
import { useEffect, useState, useCallback } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Users, Plus, Search, RefreshCw } from 'lucide-react';
import AccountsTable from '@/components/accounts/AccountsTable';
import CreateAccountDialog from '@/components/accounts/CreateAccountDialog';
import ViewAccountDialog from '@/components/accounts/ViewAccountDialog';
import EditAccountDialog from '@/components/accounts/EditAccountDialog';
import DeleteAccountDialog from '@/components/accounts/DeleteAccountDialog';
import {
    getAccounts,
    createAccount,
    updateAccount,
    deleteAccount,
    type AccountListItem,
    type AccountListResponse,
    type CreateAccountData,
    type UpdateAccountData,
} from '@/services/accounts.service';
import { handleApiError } from '@/lib/api';
 
export default function AccountsPage() {
    const [data, setData] = useState<AccountListResponse | null>(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);
 
    // Pagination and filtering state
    const [page, setPage] = useState(1);
    const [pageSize, setPageSize] = useState(10);
    const [sortBy, setSortBy] = useState('created_at');
    const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('desc');
    const [search, setSearch] = useState('');
    const [searchInput, setSearchInput] = useState('');
 
    // Dialog state
    const [createDialogOpen, setCreateDialogOpen] = useState(false);
    const [viewDialogOpen, setViewDialogOpen] = useState(false);
    const [editDialogOpen, setEditDialogOpen] = useState(false);
    const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
    const [selectedAccount, setSelectedAccount] = useState<AccountListItem | null>(null);
 
    const fetchAccounts = useCallback(async () => {
        setLoading(true);
        setError(null);
 
        try {
            const response = await getAccounts({
                page,
                page_size: pageSize,
                sort_by: sortBy,
                sort_order: sortOrder,
                search: search || undefined,
            });
            setData(response);
        } catch (err) {
            setError(handleApiError(err));
        } finally {
            setLoading(false);
        }
    }, [page, pageSize, sortBy, sortOrder, search]);
 
    useEffect(() => {
        fetchAccounts();
    }, [fetchAccounts]);
 
    const handleSort = (column: string) => {
        if (sortBy === column) {
            setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc');
        } else {
            setSortBy(column);
            setSortOrder('desc');
        }
    };
 
    const handleSearch = (e: React.FormEvent) => {
        e.preventDefault();
        setSearch(searchInput);
        setPage(1);
    };
 
    const handleCreateAccount = async (data: CreateAccountData) => {
        await createAccount(data);
        await fetchAccounts();
    };
 
    const handleUpdateAccount = async (accountId: string, data: UpdateAccountData) => {
        await updateAccount(accountId, data);
        await fetchAccounts();
    };
 
    const handleDeleteAccount = async (accountId: string) => {
        await deleteAccount(accountId);
        await fetchAccounts();
    };
 
    const handleView = (account: AccountListItem) => {
        setSelectedAccount(account);
        setViewDialogOpen(true);
    };
 
    const handleEdit = (account: AccountListItem) => {
        setSelectedAccount(account);
        setEditDialogOpen(true);
    };
 
    const handleDelete = (account: AccountListItem) => {
        setSelectedAccount(account);
        setDeleteDialogOpen(true);
    };
 
    return (
        <div className="space-y-6">
            {/* Header */}
            <div className="flex items-center justify-between">
                <div>
                    <h1 className="text-3xl font-bold">Accounts</h1>
                    <p className="text-muted-foreground mt-2">Manage tenant accounts</p>
                </div>
                <Button onClick={() => setCreateDialogOpen(true)} className="gap-2">
                    <Plus className="h-4 w-4" />
                    Create Account
                </Button>
            </div>
 
            {/* Search and Actions */}
            <Card>
                <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                        <Users className="h-5 w-5 text-primary" />
                        Account Management
                    </CardTitle>
                    <CardDescription>
                        View, create, edit, and delete tenant accounts
                    </CardDescription>
                </CardHeader>
                <CardContent className="space-y-4">
                    {/* Search Bar */}
                    <form onSubmit={handleSearch} className="flex gap-2">
                        <div className="relative flex-1">
                            <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                            <Input
                                value={searchInput}
                                onChange={(e) => setSearchInput(e.target.value)}
                                placeholder="Search by name, slug, or code..."
                                className="pl-9"
                            />
                        </div>
                        <Button type="submit" variant="secondary">
                            Search
                        </Button>
                        {search && (
                            <Button
                                type="button"
                                variant="outline"
                                onClick={() => {
                                    setSearch('');
                                    setSearchInput('');
                                    setPage(1);
                                }}
                            >
                                Clear
                            </Button>
                        )}
                        <Button
                            type="button"
                            variant="outline"
                            size="icon"
                            onClick={fetchAccounts}
                            disabled={loading}
                        >
                            <RefreshCw className={`h-4 w-4 ${loading ? 'animate-spin' : ''}`} />
                        </Button>
                    </form>
 
                    {/* Error State */}
                    {error && (
                        <div className="bg-destructive/10 border border-destructive/20 rounded-lg p-4">
                            <p className="text-destructive font-medium">Failed to load accounts</p>
                            <p className="text-sm text-muted-foreground mt-1">{error}</p>
                            <Button onClick={fetchAccounts} className="mt-4" size="sm">
                                Try Again
                            </Button>
                        </div>
                    )}
 
                    {/* Loading State */}
                    {loading && !data && (
                        <div className="flex items-center justify-center py-12">
                            <RefreshCw className="h-8 w-8 animate-spin text-muted-foreground" />
                        </div>
                    )}
 
                    {/* Table */}
                    {!loading && data && data.items.length > 0 && (
                        <AccountsTable
                            accounts={data.items}
                            sortBy={sortBy}
                            sortOrder={sortOrder}
                            onSort={handleSort}
                            onView={handleView}
                            onEdit={handleEdit}
                            onDelete={handleDelete}
                            totalItems={data.total}
                            page={page}
                            pageSize={pageSize}
                            onPageChange={setPage}
                            onPageSizeChange={(size) => {
                                setPageSize(size);
                                setPage(1);
                            }}
                        />
                    )}
 
                    {/* Empty State */}
                    {!loading && data && data.items.length === 0 && !search && (
                        <div className="text-center py-12">
                            <Users className="h-12 w-12 mx-auto mb-4 text-muted-foreground opacity-50" />
                            <h3 className="text-lg font-medium mb-2">No accounts yet</h3>
                            <p className="text-muted-foreground mb-4">
                                Get started by creating your first account
                            </p>
                            <Button onClick={() => setCreateDialogOpen(true)}>
                                <Plus className="h-4 w-4 mr-2" />
                                Create Account
                            </Button>
                        </div>
                    )}
                </CardContent>
            </Card>
 
            {/* Dialogs */}
            <CreateAccountDialog
                open={createDialogOpen}
                onOpenChange={setCreateDialogOpen}
                onSubmit={handleCreateAccount}
            />
 
            <ViewAccountDialog
                open={viewDialogOpen}
                onOpenChange={setViewDialogOpen}
                account={selectedAccount}
            />
 
            <EditAccountDialog
                open={editDialogOpen}
                onOpenChange={setEditDialogOpen}
                account={selectedAccount}
                onSubmit={handleUpdateAccount}
            />
 
            <DeleteAccountDialog
                open={deleteDialogOpen}
                onOpenChange={setDeleteDialogOpen}
                account={selectedAccount}
                onConfirm={handleDeleteAccount}
            />
        </div>
    );
}