import React, { useEffect, useState } from 'react'; import { Head, Link, router, useForm } from '@inertiajs/react'; import { usePrevious } from 'react-use'; import { HiXCircle } from 'react-icons/hi'; import { dateToString, formatIDR } from '@/utils'; import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout'; import SearchInput from '@/Components/SearchInput'; import Button from '@/Components/Button'; import FormInputDate from '@/Components/FormInputDate'; import Pagination from '@/Components/Pagination'; import FormInput from '@/Components/FormInput'; import CustomerSelectionInput from '../Customer/SelectionInput'; import { Spinner } from 'flowbite-react'; export default function Sale(props) { const { _products: { data: products, links}, _page } = props const [loading, setLoading] = useState(false) const [search, setSearch] = useState('') const preValue = usePrevious(search) const { data, setData, post, processing, errors } = useForm({ date: dateToString(new Date()), customer_id: null, items: [] }) const addItem = (product) => { const isExist = data.items.find(item => item.id === product.id) if (isExist) { return } setData('items', data.items.concat({ ...product, qty: 1 })) } const removeItem = (id) => { setData('items', data.items.filter(item => item.id !== id)) } const setQuantityItem = (id, qty) => { setData('items', data.items.map(item => { if (item.id === id) { return { ...item, qty: qty, } } return item })) } const handleSubmit = () => { post(route('sale.store')) } const params = { q: search, page: _page } useEffect(() => { if (preValue) { setLoading(true) router.get( route(route().current()), { q: search, page: _page }, { replace: true, preserveState: true, onSuccess: () => { setLoading(false) }, } ) } }, [search]) console.log(data) const total = data.items.reduce((amt, item) => amt + (+item.qty * +item.price), 0) return (
setSearch(e.target.value)} value={search} />
{loading ? (
) : (
{products.map(item => (
addItem(item)} >
{item.name}
Rp. {formatIDR(item.price)}
))}
)}
setData('customer_id', id)} error={errors.customer_id} /> setData("date", date)} placeholder='Tanggal' error={errors.date} />
Nama
Jumlah
Subtotal
{data.items.map(item => (
{item.name}
setQuantityItem(item.id, e.target.value)} className="text-right" />
{formatIDR(item.qty * item.price)}
removeItem(item.id)}>
))}
Total:
{formatIDR(total)}
); }