File size: 1,662 Bytes
d96d2a2
 
 
 
 
2b6d06f
d96d2a2
2b6d06f
d96d2a2
 
 
 
2b6d06f
 
 
d96d2a2
2b6d06f
 
d96d2a2
 
2b6d06f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d96d2a2
 
 
 
2b6d06f
d96d2a2
2b6d06f
d96d2a2
 
2b6d06f
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
import { useEffect } from 'react';
import { supabase } from '../lib/supabaseClient';
import useAuthStore from '../store/authStore';
import useTicketStore from '../store/ticketStore';

const useTicketsRealtime = () => {
    const { user, profile } = useAuthStore();
    const { addTicket, updateTicket, removeTicket } = useTicketStore();

    useEffect(() => {
        if (!user || !profile) return;

        // Only admins see the live ticket queue
        const isAdmin = profile.role === 'admin' || profile.role === 'master_admin';
        if (!isAdmin) return;

        const channel = supabase
            .channel('tickets-realtime-dashboard')
            .on(
                'postgres_changes',
                {
                    event: '*',
                    schema: 'public',
                    table: 'tickets',
                    filter: `company_id=eq.${profile.company_id}`,
                },
                (payload) => {
                    const { eventType, new: newRecord, old: oldRecord } = payload;

                    if (eventType === 'INSERT') {
                        addTicket(newRecord);
                    }

                    if (eventType === 'UPDATE') {
                        updateTicket(newRecord.ticket_id, newRecord);
                    }

                    if (eventType === 'DELETE') {
                        removeTicket(oldRecord.ticket_id);
                    }
                }
            )
            .subscribe();

        return () => {
            supabase.removeChannel(channel);
        };
    }, [user, profile, addTicket, updateTicket, removeTicket]);
};

export default useTicketsRealtime;