From 9aeb019257787b355f7b51f401d7f417899252f5 Mon Sep 17 00:00:00 2001 From: Rafi Zadanly Date: Thu, 12 Jan 2023 17:12:31 +0700 Subject: form validation, fix cart, fix checkout, create address --- src/helpers/formValidation.js | 106 ++++++++++++++++++ src/pages/my/address/create.js | 178 +++++++++++++++++++++--------- src/pages/shop/cart.js | 239 +++++++++++++++++++---------------------- src/pages/shop/checkout.js | 9 +- src/styles/globals.css | 13 +++ 5 files changed, 361 insertions(+), 184 deletions(-) create mode 100644 src/helpers/formValidation.js (limited to 'src') diff --git a/src/helpers/formValidation.js b/src/helpers/formValidation.js new file mode 100644 index 00000000..10c36e01 --- /dev/null +++ b/src/helpers/formValidation.js @@ -0,0 +1,106 @@ +import { useCallback, useEffect, useState } from "react"; + +const validateForm = (data, queries, hasChangedInputs = null) => { + let result = { valid: true, errors: {} }; + + for (const query in queries) { + if (!hasChangedInputs || (hasChangedInputs && hasChangedInputs[query])) { + const value = data[query]; + const rules = queries[query]; + let errors = []; + let label = null; + for (const rule of rules) { + let emailValidationRegex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; + if (rule.startsWith('label:')) { + label = rule.replace('label:', ''); + } else if (rule === 'required' && !value) { + errors.push('tidak boleh kosong'); + } else if (rule === 'email' && !value.match(emailValidationRegex)) { + errors.push('harus format johndoe@example.com'); + } else if (rule.startsWith('maxLength:')) { + let maxLength = parseInt(rule.replace('maxLength:', '')); + if (value && value.length > maxLength) errors.push(`maksimal ${maxLength} karakter`); + } + } + if (errors.length > 0) { + result.errors[query] = (label || query) + ' ' + errors.join(', '); + } + } + } + + if (Object.keys(result.errors).length > 0) { + result.valid = false; + } + + return result; +} + +const useFormValidation = ({ initialFormValue = {}, validationScheme = {} }) => { + const [ formInputs, setFormInputs ] = useState(initialFormValue); + const [ formErrors, setFormErrors ] = useState({}); + const [ formValidation ] = useState(validationScheme); + const [ hasChangedInputs, setHasChangedInputs ] = useState({}); + + const handleFormSubmit = (event, func) => { + if (event) { + event.preventDefault(); + + // Make all input to be has changed mode to revalidate + const changedInputs = {}; + for (const key in formInputs) changedInputs[key] = true; + setHasChangedInputs(changedInputs); + + const { valid, errors } = validateForm(formInputs, formValidation, changedInputs); + setFormErrors(errors); + + if (valid) func(); + } + }; + + const setChangedInput = (name, value = true) => { + setHasChangedInputs((hasChangedInputs) => ({ + ...hasChangedInputs, + [name]: value + })); + }; + + const handleInputChange = (event) => { + setFormInputs((formInputs) => ({ + ...formInputs, + [event.target.name]: event.target.value + })); + setChangedInput(event.target.name); + }; + + const handleSelectChange = useCallback((name, value) => { + setFormInputs((formInputs) => ({ + ...formInputs, + [name]: value + })); + setChangedInput(name); + }, []); + + const handleFormReset = () => { + setFormInputs(initialFormValue); + setFormErrors({}); + setHasChangedInputs({}); + } + + useEffect(() => { + if (formInputs) { + const { errors } = validateForm(formInputs, formValidation, hasChangedInputs); + setFormErrors(errors); + } + }, [ formInputs, formValidation, hasChangedInputs ]) + + return { + handleFormReset, + handleFormSubmit, + handleInputChange, + handleSelectChange, + formInputs, + formErrors + }; + }; + +export default useFormValidation; \ No newline at end of file diff --git a/src/pages/my/address/create.js b/src/pages/my/address/create.js index 128da491..d68d1f76 100644 --- a/src/pages/my/address/create.js +++ b/src/pages/my/address/create.js @@ -4,23 +4,57 @@ import WithAuth from "../../../components/WithAuth"; import apiOdoo from "../../../helpers/apiOdoo"; import ReactSelect from "react-select"; import { useEffect, useState } from "react"; +import { useAuth } from "../../../helpers/auth"; +import useFormValidation from "../../../helpers/formValidation"; +import { toast } from "react-hot-toast"; +import { useRouter } from "next/router"; + +const initialFormValue = { + type: null, + name: '', + email: '', + mobile: '', + street: '', + city: null, + district: null, + subDistrict: null, + zip: '' +} + +const validationScheme = { + type: ['label:Label Alamat', 'required'], + name: ['label:Nama', 'required'], + email: ['label:Email', 'required', 'email'], + mobile: ['label:No. Handphone', 'required', 'maxLength:16'], + street: ['label:Alamat', 'required'], + city: ['label:Kota', 'required'], + zip: ['label:Kode Pos', 'required'] +}; export default function CreateAddress() { + const [auth] = useAuth(); + const router = useRouter(); + // Master Data const [cities, setCities] = useState([]); const [districts, setDistricts] = useState([]); const [subDistricts, setSubDistricts] = useState([]); // Input Data - const [city, setCity] = useState(null); - const [district, setDistrict] = useState(null); - const [subDistrict, setSubDistrict] = useState(null); - const [formValue, setFormValue] = useState({}); + const { + formInputs, + formErrors, + handleInputChange, + handleSelectChange, + handleFormSubmit, + handleFormReset + } = useFormValidation({ validationScheme, initialFormValue }); useEffect(() => { if (cities.length == 0) { const loadCities = async () => { let dataCities = await apiOdoo('GET', '/api/v1/city'); + dataCities = dataCities.map((city) => ({ value: city.id, label: city.name })); setCities(dataCities); }; loadCities(); @@ -28,122 +62,168 @@ export default function CreateAddress() { }, [cities]); useEffect(() => { - setDistrict(null); - if (city) { + handleSelectChange('district', null); + if (formInputs.city) { const loadDistricts = async () => { - let dataDistricts = await apiOdoo('GET', `/api/v1/district?city_id=${city.id}`); + let dataDistricts = await apiOdoo('GET', `/api/v1/district?city_id=${formInputs.city.value}`); + dataDistricts = dataDistricts.map((district) => ({ value: district.id, label: district.name })); setDistricts(dataDistricts); }; loadDistricts(); } - }, [city]); + }, [ formInputs.city, handleSelectChange ]); useEffect(() => { - setSubDistrict(null); - if (district) { + handleSelectChange('subDistrict', null); + if (formInputs.district) { const loadSubDistricts = async () => { - let dataSubDistricts = await apiOdoo('GET', `/api/v1/sub_district?district_id=${district.id}`); - console.log(dataSubDistricts); + let dataSubDistricts = await apiOdoo('GET', `/api/v1/sub_district?district_id=${formInputs.district.value}`); + dataSubDistricts = dataSubDistricts.map((subDistrict) => ({ value: subDistrict.id, label: subDistrict.name })); setSubDistricts(dataSubDistricts); }; loadSubDistricts(); } - }, [district]); - - const handleChange = (e) => { - setFormValue({ - ...formValue, - [e.target.name]: e.target.value - }); - }; + }, [ formInputs.district, handleSelectChange ]); + + const addressTypes = [ + { value: 'contact', label: 'Contact Address' }, + { value: 'invoice', label: 'Invoice Address' }, + { value: 'delivery', label: 'Delivery Address' }, + { value: 'other', label: 'Other Address' }, + ]; + + const onSubmit = async () => { + const parameters = { + ...formInputs, + city_id: formInputs.city?.value, + district_id: formInputs.district?.value, + sub_district_id: formInputs.subDistrict?.value, + type: formInputs.type?.value, + user_id: auth.id, + partner_id: auth.partner_id, + }; + + const address = await apiOdoo('POST', '/api/v1/partner', parameters); + if (address?.id) { + handleFormReset(); + toast.success('Berhasil menambahkan alamat'); + router.push('/my/address'); + } + } return ( -
+ handleFormSubmit(e, onSubmit)}> - handleSelectChange('type', value)} + value={formInputs?.type} /> +
{formErrors?.type}
+ - +
{formErrors?.name}
+ + +
{formErrors?.email}
+ +
{formErrors?.mobile}
+ +
{formErrors?.street}
+ state.menuIsOpen || state.isFocused ? '!border-yellow_r-9' : '' }} options={cities} - getOptionLabel={e => e.name} - getOptionValue={e => e.id} - onChange={(value) => setCity(value)} - value={city} + value={formInputs.city} + onChange={(value) => handleSelectChange('city', value)} /> +
{formErrors?.city}
+ state.menuIsOpen || state.isFocused ? '!border-yellow_r-9' : '' }} options={districts} - getOptionLabel={e => e.name} - getOptionValue={e => e.id} - onChange={(value) => setDistrict(value)} - value={district} - isDisabled={!city} + value={formInputs.district} + onChange={(value) => handleSelectChange('district', value)} + isDisabled={!formInputs.city} /> + state.menuIsOpen || state.isFocused ? '!border-yellow_r-9' : '' }} options={subDistricts} - getOptionLabel={e => e.name} - getOptionValue={e => e.id} - onChange={(value) => setSubDistrict(value)} - value={subDistrict} - isDisabled={!district} + onChange={(value) => handleSelectChange('subDistrict', value)} + value={formInputs.subDistrict} + isDisabled={!formInputs.district} /> + +
{formErrors?.zip}
diff --git a/src/pages/shop/cart.js b/src/pages/shop/cart.js index cdb79178..0c6bbdc3 100644 --- a/src/pages/shop/cart.js +++ b/src/pages/shop/cart.js @@ -149,129 +149,6 @@ export default function Cart() { setProducts([...productsToUpdate]); } - // Components - const CartEmpty = () => ( -
- -

Keranjang belanja anda masih kosong.

- Mulai Belanja -
- ); - - const CartLoader = () => ( -
- -
- ); - - const CartWarningAlert = () => { -
- -
- -
- Mohon dicek kembali & pastikan pesanan kamu sudah sesuai dengan yang kamu butuhkan. Atau bisa hubungi kami. -
-
- }; - - const CartProductList = () => ( -
-
-

Daftar Produk Belanja

- Cari Produk Lain -
- {products.map((product, index) => ( -
-
toggleProductSelected(product.id)}> - - {product.parent.name} -
-
- - {product.parent.name} - -

- {product.code || '-'} - {product.attributes.length > 0 ? ` | ${product.attributes.join(', ')}` : ''} -

-
-

{currencyFormat(product.price.price_discount)}

- {product.price.discount_percentage > 0 && ( - <> - {product.price.discount_percentage}% -

{currencyFormat(product.price.price)}

- - )} -
-
-

{currencyFormat(product.quantity * product.price.price_discount)}

-
- - - blurQuantity(product.id, e.target.value)} - onChange={(e) => updateQuantity(product.id, e.target.value)} - value={product.quantity} - /> - -
-
-
-
- ))} -
- ); - - const ActionButton = () => ( -
-
-

Total

-

{getProductsSelected().length > 0 && ( - <>({ getProductsSelected().length } Barang) - )}

-

{currencyFormat(totalPriceBeforeTax + totalTaxAmount - totalDiscountAmount)}

-
- -
- - -
-
- ); - return ( <> - {isLoadingProducts && } + {isLoadingProducts && ( +
+ +
+ ) } - { !isLoadingProducts && products.length == 0 && } + { !isLoadingProducts && products.length == 0 && ( +
+ +

Keranjang belanja anda masih kosong.

+ Mulai Belanja +
+ ) } { !isLoadingProducts && products.length > 0 && ( <> @@ -298,13 +185,109 @@ export default function Cart() { - +
+ +
+ +
+ Mohon dicek kembali & pastikan pesanan kamu sudah sesuai dengan yang kamu butuhkan. Atau bisa hubungi kami. +
+
- +
+
+

Daftar Produk Belanja

+ Cari Produk Lain +
+ {products.map((product, index) => ( +
+
toggleProductSelected(product.id)}> + + {product.parent.name} +
+
+ + {product.parent.name} + +

+ {product.code || '-'} + {product.attributes.length > 0 ? ` | ${product.attributes.join(', ')}` : ''} +

+
+

{currencyFormat(product.price.price_discount)}

+ {product.price.discount_percentage > 0 && ( + <> + {product.price.discount_percentage}% +

{currencyFormat(product.price.price)}

+ + )} +
+
+

{currencyFormat(product.quantity * product.price.price_discount)}

+
+ + + blurQuantity(product.id, e.target.value)} + onChange={(e) => updateQuantity(product.id, e.target.value)} + value={product.quantity} + /> + +
+
+
+
+ ))} +
- +
+
+

Total

+

{getProductsSelected().length > 0 && ( + <>({ getProductsSelected().length } Barang) + )}

+

{currencyFormat(totalPriceBeforeTax + totalTaxAmount - totalDiscountAmount)}

+
+ +
+ + +
+
) } diff --git a/src/pages/shop/checkout.js b/src/pages/shop/checkout.js index 5eef98e5..54f93c44 100644 --- a/src/pages/shop/checkout.js +++ b/src/pages/shop/checkout.js @@ -30,7 +30,6 @@ export default function Checkout() { const [totalPriceBeforeTax, setTotalPriceBeforeTax] = useState(0); const [totalTaxAmount, setTotalTaxAmount] = useState(0); const [totalDiscountAmount, setTotalDiscountAmount] = useState(0); - const [isLoading, setIsLoading] = useState(true); const [finishCheckout, setFinishCheckout] = useState(null); const payments = [ @@ -106,10 +105,6 @@ export default function Checkout() { } }, [products]); - useEffect(() => { - if (addresses && products) setIsLoading(false); - }, [addresses, products]); - const submit = async () => { if (!selectedPayment) { toast.error('Mohon pilih metode pembayaran terlebih dahulu', { @@ -151,11 +146,11 @@ export default function Checkout() { ) : ( <> - {isLoading && ( + { !products && !addresses && (
- )} + ) } { products && addresses && ( <> diff --git a/src/styles/globals.css b/src/styles/globals.css index e90228bd..e223036b 100644 --- a/src/styles/globals.css +++ b/src/styles/globals.css @@ -115,6 +115,13 @@ html, body { ; } + .form-input[aria-invalid] { + @apply + border-red_r-10 + focus:border-red_r-10 + ; + } + .btn-yellow, .btn-light, .btn-red { @@ -400,4 +407,10 @@ html, body { !shadow-none !border-gray_r-7 ; +} + +.form-select__control--menu-is-open { + @apply + !border-yellow_r-9 + ; } \ No newline at end of file -- cgit v1.2.3