'use client'; import { useMemo, useState } from 'react'; import { useMutation } from '@tanstack/react-query'; import { toast } from 'sonner'; import { Icons } from '@/components/icons'; import { Button } from '@/components/ui/button'; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'; import { Textarea } from '@/components/ui/textarea'; import { shareCustomerContactMutation, unshareCustomerContactMutation } from '../api/mutations'; import type { CustomerContactRecord, CustomerReferenceData } from '../api/types'; import { formatDateTime } from '@/lib/format'; export function ContactShareSheet({ customerId, contact, referenceData, open, onOpenChange, canManage }: { customerId: string; contact: CustomerContactRecord | null; referenceData: CustomerReferenceData; open: boolean; onOpenChange: (open: boolean) => void; canManage: boolean; }) { const [sharedToUserId, setSharedToUserId] = useState(''); const [remark, setRemark] = useState(''); const existingSharedIds = useMemo( () => new Set(contact?.shares.map((item) => item.sharedToUserId) ?? []), [contact] ); const candidates = useMemo( () => referenceData.crmUsers.filter((user) => !existingSharedIds.has(user.id)), [existingSharedIds, referenceData.crmUsers] ); const shareMutation = useMutation({ ...shareCustomerContactMutation, onSuccess: () => { toast.success('แชร์ contact เรียบร้อย'); setSharedToUserId(''); setRemark(''); }, onError: (error) => toast.error(error instanceof Error ? error.message : 'ไม่สามารถแชร์ contact ได้') }); const unshareMutation = useMutation({ ...unshareCustomerContactMutation, onSuccess: () => { toast.success('ยกเลิกการแชร์เรียบร้อย'); }, onError: (error) => toast.error(error instanceof Error ? error.message : 'ไม่สามารถยกเลิกการแชร์ได้') }); return ( Shared With จัดการผู้ใช้ที่เข้าถึง contact นี้ได้
{!contact?.shares.length ? (
ยังไม่มีการแชร์ contact นี้
) : (
{contact.shares.map((share) => (
{share.sharedToName ?? share.sharedToUserId}
{formatDateTime(share.sharedAt)} โดย {share.sharedByName ?? share.sharedByUserId}
{share.remark ?
{share.remark}
: null}
{canManage ? ( ) : null}
))}
)} {canManage ? (