mirror of
https://github.com/R0m1k3/Regisflow.git
synced 2026-10-24 07:38:18 +02:00
Enable store selection for admins and associate sales with specific stores
Implements store selection and association functionality using useStoreContext hook and updates sale creation and retrieval APIs. Replit-Commit-Author: Agent Replit-Commit-Session-Id: 91318273-c764-4fd4-be04-bdc12c38af32 Replit-Commit-Screenshot-Url: https://storage.googleapis.com/screenshot-production-us-central1/0715008c-7244-40f4-befc-26c014852236/d304bad8-e4eb-4558-b9d6-38704ba052e8.jpg
This commit is contained in:
1 parent
a5336a5919
commit
4384818f63
5 files changed
+216
-7
No files matched your search
@@ -8,6 +8,8 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@
|
|||||||
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form';
|
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form';
|
||||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||||
import { useToast } from '@/hooks/use-toast';
|
import { useToast } from '@/hooks/use-toast';
|
||||||
|
import { useAuth } from '@/hooks/useAuth';
|
||||||
|
import { useStoreContext } from '@/hooks/useStoreContext';
|
||||||
import { apiRequest } from '@/lib/queryClient';
|
import { apiRequest } from '@/lib/queryClient';
|
||||||
import { validateRequiredFields, validateEAN13, ARTICLE_CATEGORY_MAPPING, IDENTITY_TYPES } from '@/lib/validation';
|
import { validateRequiredFields, validateEAN13, ARTICLE_CATEGORY_MAPPING, IDENTITY_TYPES } from '@/lib/validation';
|
||||||
import { Package, User, Users, Save, X } from 'lucide-react';
|
import { Package, User, Users, Save, X } from 'lucide-react';
|
||||||
@@ -32,6 +34,8 @@ interface FormData {
|
|||||||
export default function NewSaleForm() {
|
export default function NewSaleForm() {
|
||||||
const { toast } = useToast();
|
const { toast } = useToast();
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
|
const { user } = useAuth();
|
||||||
|
const { selectedStoreId } = useStoreContext();
|
||||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||||
|
|
||||||
const form = useForm<FormData>({
|
const form = useForm<FormData>({
|
||||||
@@ -58,9 +62,15 @@ export default function NewSaleForm() {
|
|||||||
|
|
||||||
const createSaleMutation = useMutation({
|
const createSaleMutation = useMutation({
|
||||||
mutationFn: async (saleData: any) => {
|
mutationFn: async (saleData: any) => {
|
||||||
|
const dataToSend = {
|
||||||
|
...saleData,
|
||||||
|
// Include storeId for admin users
|
||||||
|
...(user?.role === 'admin' && selectedStoreId && { storeId: selectedStoreId })
|
||||||
|
};
|
||||||
|
|
||||||
const response = await apiRequest('/api/sales', {
|
const response = await apiRequest('/api/sales', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
body: JSON.stringify(saleData),
|
body: JSON.stringify(dataToSend),
|
||||||
});
|
});
|
||||||
return response.json();
|
return response.json();
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -6,6 +6,8 @@ import { Input } from '@/components/ui/input';
|
|||||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
|
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
|
||||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
|
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
|
||||||
import { useToast } from '@/hooks/use-toast';
|
import { useToast } from '@/hooks/use-toast';
|
||||||
|
import { useStoreContext } from '@/hooks/useStoreContext';
|
||||||
|
import { useAuth } from '@/hooks/useAuth';
|
||||||
import { apiRequest } from '@/lib/queryClient';
|
import { apiRequest } from '@/lib/queryClient';
|
||||||
import type { Sale } from '@shared/schema';
|
import type { Sale } from '@shared/schema';
|
||||||
import { History, Download, Trash2, Eye, Filter } from 'lucide-react';
|
import { History, Download, Trash2, Eye, Filter } from 'lucide-react';
|
||||||
@@ -17,21 +19,30 @@ interface SalesHistoryProps {
|
|||||||
export default function SalesHistory({ canDelete = false }: SalesHistoryProps) {
|
export default function SalesHistory({ canDelete = false }: SalesHistoryProps) {
|
||||||
const { toast } = useToast();
|
const { toast } = useToast();
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
|
const { user } = useAuth();
|
||||||
|
const { selectedStoreId } = useStoreContext();
|
||||||
const [selectedSale, setSelectedSale] = useState<Sale | null>(null);
|
const [selectedSale, setSelectedSale] = useState<Sale | null>(null);
|
||||||
const [startDate, setStartDate] = useState('');
|
const [startDate, setStartDate] = useState('');
|
||||||
const [endDate, setEndDate] = useState('');
|
const [endDate, setEndDate] = useState('');
|
||||||
|
|
||||||
// Query for sales
|
// Query for sales
|
||||||
const { data: salesData, isLoading } = useQuery<Sale[]>({
|
const { data: salesData, isLoading } = useQuery<Sale[]>({
|
||||||
queryKey: ['/api/sales', startDate, endDate],
|
queryKey: ['/api/sales', startDate, endDate, selectedStoreId],
|
||||||
queryFn: async () => {
|
queryFn: async () => {
|
||||||
const params = new URLSearchParams();
|
const params = new URLSearchParams();
|
||||||
if (startDate) params.append('startDate', startDate);
|
if (startDate) params.append('startDate', startDate);
|
||||||
if (endDate) params.append('endDate', endDate);
|
if (endDate) params.append('endDate', endDate);
|
||||||
|
|
||||||
|
// Add storeId for admin users
|
||||||
|
if (user?.role === 'admin' && selectedStoreId) {
|
||||||
|
params.append('storeId', selectedStoreId.toString());
|
||||||
|
}
|
||||||
|
|
||||||
const queryString = params.toString();
|
const queryString = params.toString();
|
||||||
const response = await apiRequest(`/api/sales${queryString ? `?${queryString}` : ''}`);
|
const response = await apiRequest(`/api/sales${queryString ? `?${queryString}` : ''}`);
|
||||||
return response.json();
|
return response.json();
|
||||||
},
|
},
|
||||||
|
enabled: !!selectedStoreId, // Only run query when store is selected
|
||||||
});
|
});
|
||||||
|
|
||||||
const sales = Array.isArray(salesData) ? salesData : [];
|
const sales = Array.isArray(salesData) ? salesData : [];
|
||||||
|
|||||||
@@ -0,0 +1,70 @@
|
|||||||
|
import { createContext, useContext, useState, useEffect, ReactNode } from 'react';
|
||||||
|
import { useQuery } from '@tanstack/react-query';
|
||||||
|
import { apiRequest } from '@/lib/queryClient';
|
||||||
|
import type { Store } from '@shared/schema';
|
||||||
|
|
||||||
|
interface StoreContextType {
|
||||||
|
selectedStoreId: number | null;
|
||||||
|
setSelectedStoreId: (storeId: number | null) => void;
|
||||||
|
stores: Store[];
|
||||||
|
selectedStore: Store | null;
|
||||||
|
isLoadingStores: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
const StoreContext = createContext<StoreContextType | undefined>(undefined);
|
||||||
|
|
||||||
|
interface StoreProviderProps {
|
||||||
|
children: ReactNode;
|
||||||
|
userStoreId?: number | null;
|
||||||
|
isAdmin?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function StoreProvider({ children, userStoreId, isAdmin }: StoreProviderProps) {
|
||||||
|
const [selectedStoreId, setSelectedStoreId] = useState<number | null>(null);
|
||||||
|
|
||||||
|
// Query all stores for admin, or just get user's store for non-admin
|
||||||
|
const { data: stores = [], isLoading: isLoadingStores } = useQuery<Store[]>({
|
||||||
|
queryKey: isAdmin ? ['/api/admin/stores'] : ['/api/stores'],
|
||||||
|
queryFn: async () => {
|
||||||
|
const endpoint = isAdmin ? '/api/admin/stores' : '/api/stores';
|
||||||
|
const response = await apiRequest(endpoint);
|
||||||
|
return response.json();
|
||||||
|
},
|
||||||
|
enabled: !!isAdmin || !!userStoreId,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Set initial selected store
|
||||||
|
useEffect(() => {
|
||||||
|
if (stores.length > 0 && selectedStoreId === null) {
|
||||||
|
if (isAdmin) {
|
||||||
|
// Admin: select first store by default
|
||||||
|
setSelectedStoreId(stores[0].id);
|
||||||
|
} else if (userStoreId) {
|
||||||
|
// Non-admin: select user's store
|
||||||
|
setSelectedStoreId(userStoreId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, [stores, selectedStoreId, isAdmin, userStoreId]);
|
||||||
|
|
||||||
|
const selectedStore = stores.find(store => store.id === selectedStoreId) || null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<StoreContext.Provider value={{
|
||||||
|
selectedStoreId,
|
||||||
|
setSelectedStoreId,
|
||||||
|
stores,
|
||||||
|
selectedStore,
|
||||||
|
isLoadingStores,
|
||||||
|
}}>
|
||||||
|
{children}
|
||||||
|
</StoreContext.Provider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useStoreContext() {
|
||||||
|
const context = useContext(StoreContext);
|
||||||
|
if (context === undefined) {
|
||||||
|
throw new Error('useStoreContext must be used within a StoreProvider');
|
||||||
|
}
|
||||||
|
return context;
|
||||||
|
}
|
||||||
@@ -1,18 +1,21 @@
|
|||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||||
import { useAuth } from "@/hooks/useAuth";
|
import { useAuth } from "@/hooks/useAuth";
|
||||||
|
import { StoreProvider, useStoreContext } from "@/hooks/useStoreContext";
|
||||||
import NewSaleForm from "@/components/NewSaleForm";
|
import NewSaleForm from "@/components/NewSaleForm";
|
||||||
import SalesHistory from "@/components/SalesHistory";
|
import SalesHistory from "@/components/SalesHistory";
|
||||||
import Administration from "@/components/Administration";
|
import Administration from "@/components/Administration";
|
||||||
import { Package, History, Settings, LogOut, User } from "lucide-react";
|
import { Package, History, Settings, LogOut, User, Building2 } from "lucide-react";
|
||||||
import { useToast } from "@/hooks/use-toast";
|
import { useToast } from "@/hooks/use-toast";
|
||||||
|
|
||||||
export default function Dashboard() {
|
function DashboardContent() {
|
||||||
const { user, logout } = useAuth();
|
const { user, logout } = useAuth();
|
||||||
const { toast } = useToast();
|
const { toast } = useToast();
|
||||||
const [activeTab, setActiveTab] = useState("new-sale");
|
const [activeTab, setActiveTab] = useState("new-sale");
|
||||||
|
const { selectedStoreId, setSelectedStoreId, stores, selectedStore, isLoadingStores } = useStoreContext();
|
||||||
|
|
||||||
const handleLogout = async () => {
|
const handleLogout = async () => {
|
||||||
try {
|
try {
|
||||||
@@ -32,6 +35,7 @@ export default function Dashboard() {
|
|||||||
|
|
||||||
const canAccessAdmin = user?.role === "admin";
|
const canAccessAdmin = user?.role === "admin";
|
||||||
const canDeleteSales = user?.role === "admin" || user?.role === "manager";
|
const canDeleteSales = user?.role === "admin" || user?.role === "manager";
|
||||||
|
const isAdmin = user?.role === "admin";
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-gray-50">
|
<div className="min-h-screen bg-gray-50">
|
||||||
@@ -50,6 +54,36 @@ export default function Dashboard() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex items-center gap-4">
|
<div className="flex items-center gap-4">
|
||||||
|
{/* Store Selector for Admin */}
|
||||||
|
{isAdmin && !isLoadingStores && (
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Building2 className="h-4 w-4 text-gray-500" />
|
||||||
|
<Select
|
||||||
|
value={selectedStoreId?.toString() || ""}
|
||||||
|
onValueChange={(value) => setSelectedStoreId(parseInt(value))}
|
||||||
|
>
|
||||||
|
<SelectTrigger className="w-48">
|
||||||
|
<SelectValue placeholder="Sélectionner un magasin" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
{stores.map((store) => (
|
||||||
|
<SelectItem key={store.id} value={store.id.toString()}>
|
||||||
|
{store.name}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Current Store Display for Non-Admin */}
|
||||||
|
{!isAdmin && selectedStore && (
|
||||||
|
<div className="flex items-center gap-2 text-sm text-gray-600">
|
||||||
|
<Building2 className="h-4 w-4" />
|
||||||
|
<span>{selectedStore.name}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
<div className="text-right">
|
<div className="text-right">
|
||||||
<p className="text-sm font-medium text-gray-900">
|
<p className="text-sm font-medium text-gray-900">
|
||||||
{user?.firstName} {user?.lastName}
|
{user?.firstName} {user?.lastName}
|
||||||
@@ -67,6 +101,30 @@ export default function Dashboard() {
|
|||||||
|
|
||||||
{/* Main Content */}
|
{/* Main Content */}
|
||||||
<main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
|
<main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
|
||||||
|
{selectedStore && (
|
||||||
|
<div className="mb-6">
|
||||||
|
<Card>
|
||||||
|
<CardContent className="pt-6">
|
||||||
|
<div className="flex items-center gap-4">
|
||||||
|
<div className="p-3 bg-blue-100 rounded-lg">
|
||||||
|
<Building2 className="h-6 w-6 text-blue-600" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h2 className="text-lg font-semibold text-gray-900">{selectedStore.name}</h2>
|
||||||
|
<div className="text-sm text-gray-600">
|
||||||
|
{selectedStore.address && <p>{selectedStore.address}</p>}
|
||||||
|
<div className="flex gap-4">
|
||||||
|
{selectedStore.phone && <span>📞 {selectedStore.phone}</span>}
|
||||||
|
{selectedStore.email && <span>✉️ {selectedStore.email}</span>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
<Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-6">
|
<Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-6">
|
||||||
<TabsList className="grid w-full grid-cols-3 lg:w-auto lg:grid-cols-auto">
|
<TabsList className="grid w-full grid-cols-3 lg:w-auto lg:grid-cols-auto">
|
||||||
<TabsTrigger value="new-sale" className="flex items-center gap-2">
|
<TabsTrigger value="new-sale" className="flex items-center gap-2">
|
||||||
@@ -102,4 +160,17 @@ export default function Dashboard() {
|
|||||||
</main>
|
</main>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function Dashboard() {
|
||||||
|
const { user } = useAuth();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<StoreProvider
|
||||||
|
userStoreId={user?.storeId}
|
||||||
|
isAdmin={user?.role === "admin"}
|
||||||
|
>
|
||||||
|
<DashboardContent />
|
||||||
|
</StoreProvider>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
+50
-3
@@ -117,6 +117,26 @@ export async function registerRoutes(app: Express): Promise<Server> {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Store routes for users
|
||||||
|
app.get('/api/stores', requireAuth, async (req, res) => {
|
||||||
|
try {
|
||||||
|
const user = await storage.getUser(req.session.userId!);
|
||||||
|
if (!user || !user.storeId) {
|
||||||
|
return res.status(404).json({ error: "User store not found" });
|
||||||
|
}
|
||||||
|
|
||||||
|
const store = await storage.getStore(user.storeId);
|
||||||
|
if (!store) {
|
||||||
|
return res.status(404).json({ error: "Store not found" });
|
||||||
|
}
|
||||||
|
|
||||||
|
res.json([store]); // Return as array to match admin endpoint format
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Get user stores error:', error);
|
||||||
|
res.status(500).json({ error: "Failed to get stores" });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
// Sales routes
|
// Sales routes
|
||||||
app.get('/api/sales', requireAuth, async (req, res) => {
|
app.get('/api/sales', requireAuth, async (req, res) => {
|
||||||
try {
|
try {
|
||||||
@@ -125,9 +145,23 @@ export async function registerRoutes(app: Express): Promise<Server> {
|
|||||||
return res.status(404).json({ error: "User not found" });
|
return res.status(404).json({ error: "User not found" });
|
||||||
}
|
}
|
||||||
|
|
||||||
const { startDate, endDate } = req.query;
|
const { startDate, endDate, storeId } = req.query;
|
||||||
|
|
||||||
|
// Determine which store to query
|
||||||
|
let targetStoreId: number;
|
||||||
|
if (user.role === 'admin' && storeId) {
|
||||||
|
// Admin can query any store
|
||||||
|
targetStoreId = parseInt(storeId as string);
|
||||||
|
} else {
|
||||||
|
// Non-admin users can only query their own store
|
||||||
|
if (!user.storeId) {
|
||||||
|
return res.status(400).json({ error: "User has no assigned store" });
|
||||||
|
}
|
||||||
|
targetStoreId = user.storeId;
|
||||||
|
}
|
||||||
|
|
||||||
const sales = await storage.getSalesByStore(
|
const sales = await storage.getSalesByStore(
|
||||||
user.storeId!,
|
targetStoreId,
|
||||||
startDate as string,
|
startDate as string,
|
||||||
endDate as string
|
endDate as string
|
||||||
);
|
);
|
||||||
@@ -145,9 +179,22 @@ export async function registerRoutes(app: Express): Promise<Server> {
|
|||||||
return res.status(404).json({ error: "User not found" });
|
return res.status(404).json({ error: "User not found" });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Determine which store to use for the sale
|
||||||
|
let targetStoreId: number;
|
||||||
|
if (user.role === 'admin' && req.body.storeId) {
|
||||||
|
// Admin can create sales for any store
|
||||||
|
targetStoreId = req.body.storeId;
|
||||||
|
} else {
|
||||||
|
// Non-admin users can only create sales for their assigned store
|
||||||
|
if (!user.storeId) {
|
||||||
|
return res.status(400).json({ error: "User has no assigned store" });
|
||||||
|
}
|
||||||
|
targetStoreId = user.storeId;
|
||||||
|
}
|
||||||
|
|
||||||
const saleData = insertSaleSchema.parse({
|
const saleData = insertSaleSchema.parse({
|
||||||
...req.body,
|
...req.body,
|
||||||
storeId: user.storeId,
|
storeId: targetStoreId,
|
||||||
userId: user.id
|
userId: user.id
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user