# All files / js/composables useCustomerLookup.ts

63.49% Statements 40/63
68% Branches 17/25
50% Functions 5/10
63.49% Lines 40/63

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

    3x
    3x
    3x
    3x

    3x
    3x

    3x

    3x
    2x
    2x

    3x
    1x
    1x
    1x
    1x

    3x

    3x

    3x

    3x
    1x

    1x
    1x

    1x

    1x

    3x
    2x

    2x
    2x

    2x

    2x
    1x
    1x

    1x

    1x
    1x
    1x
    1x
    1x
    1x

    3x

     import type { CustomerLookupCustomer, QuickCreateCustomerPayload, QuickCreateCustomerResponse } from '@/types/customers';
    import { getCsrfToken } from '@/lib/csrf';
    import { useForm } from '@inertiajs/vue3';
    import { ref, watch } from 'vue';
    import { toast } from 'vue-sonner';

    interface UseCustomerLookupOptions {
        customers: CustomerLookupCustomer[];
        initialCustomerId?: number | string | null;
        onCustomerSelected: (customer: CustomerLookupCustomer) => void;
        onCustomerCleared?: () => void;
        searchUrl?: string;
        quickCreateUrl?: string;
        searchErrorMessage?: string;
        createErrorMessage?: string;
    }

    export function useCustomerLookup({
        customers,
        initialCustomerId = null,
        onCustomerSelected,
        onCustomerCleared,
        searchUrl = '/customers/search',
        quickCreateUrl = '/customers/quick-create',
        searchErrorMessage = 'Unable to load matching customers right now.',
        createErrorMessage = 'Unable to create a customer right now.',
    }: UseCustomerLookupOptions) {
        const customerSearchQuery = ref('');
        const customerSearchFocused = ref(false);
        const filteredCustomers = ref<CustomerLookupCustomer[]>([]);
        const selectedCustomer = ref<CustomerLookupCustomer | null>(
            customers.find((customer) => customer.id === Number(initialCustomerId)) ?? null,
        );
        const showQuickCreateModal = ref(false);
        const quickCreateForm = useForm<QuickCreateCustomerPayload>({
            name: '',
            email: '',
            phone: '',
            terms: '',
        });

        Iif (selectedCustomer.value) {
            customerSearchQuery.value = selectedCustomer.value.name;
        }

        watch(customerSearchQuery, (newQuery) => {
            Eif (!showQuickCreateModal.value) {
                quickCreateForm.name = newQuery;
            }
        });

        const selectCustomer = (customer: CustomerLookupCustomer) => {
            selectedCustomer.value = customer;
            customerSearchQuery.value = customer.name;
            customerSearchFocused.value = false;
            onCustomerSelected(customer);
        };

        const clearCustomer = () => {
            selectedCustomer.value = null;
            customerSearchQuery.value = '';
            customerSearchFocused.value = false;
            filteredCustomers.value = [];
            onCustomerCleared?.();
        };

        const setSelectedCustomer = (customer: CustomerLookupCustomer | null) => {
            if (!customer) {
                clearCustomer();

                return;
            }

            selectedCustomer.value = customer;
            customerSearchQuery.value = customer.name;
        };

        const handleCustomerBlur = () => {
            setTimeout(() => {
                customerSearchFocused.value = false;
            }, 200);
        };

        const handleCustomerSearch = async () => {
            Iif (!customerSearchQuery.value.trim()) {
                filteredCustomers.value = [];

                return;
            }

            try {
                const response = await fetch(`${searchUrl}?q=${encodeURIComponent(customerSearchQuery.value)}`, {
                    headers: {
                        Accept: 'application/json',
                        'X-Requested-With': 'XMLHttpRequest',
                    },
                });

                Iif (!response.ok) {
                    filteredCustomers.value = [];
                    toast.error(searchErrorMessage);

                    return;
                }

                filteredCustomers.value = (await response.json()) as CustomerLookupCustomer[];
            } catch {
                filteredCustomers.value = [];
                toast.error(searchErrorMessage);
            }
        };

        const quickCreateCustomer = async () => {
            quickCreateForm.clearErrors();

            try {
                const response = await fetch(quickCreateUrl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        Accept: 'application/json',
                        'X-Requested-With': 'XMLHttpRequest',
                        'X-CSRF-TOKEN': getCsrfToken(),
                    },
                    body: JSON.stringify(quickCreateForm.data()),
                });

                const payload = (await response.json()) as QuickCreateCustomerResponse;

                if (!response.ok) {
                    if (payload.errors) {
                        quickCreateForm.setError(payload.errors);
                    } else E{
                        toast.error(createErrorMessage);
                    }

                    return;
                }

                Eif (payload.success && payload.customer) {
                    selectCustomer(payload.customer);
                    showQuickCreateModal.value = false;
                    quickCreateForm.reset();
                    quickCreateForm.clearErrors();
                    quickCreateForm.name = customerSearchQuery.value;
                }
            } catch {
                toast.error(createErrorMessage);
            }
        };

        return {
            clearCustomer,
            customerSearchFocused,
            customerSearchQuery,
            filteredCustomers,
            handleCustomerBlur,
            handleCustomerSearch,
            quickCreateCustomer,
            quickCreateForm,
            selectCustomer,
            selectedCustomer,
            setSelectedCustomer,
            showQuickCreateModal,
        };
    }