forked from vtex-apps/checkout-button-example
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Beatriz Cavalieri
authored and
Beatriz Cavalieri
committed
Jan 9, 2025
1 parent
d04accf
commit 207b6a1
Showing
1 changed file
with
136 additions
and
103 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,141 +1,174 @@ | ||
import React, { FC, useEffect } from 'react'; | ||
import React, { FC, useEffect } from 'react' | ||
|
||
const CheckoutCustomCep: FC = () => { | ||
const [postalCode, setPostalCode] = React.useState(''); | ||
const [postalCode, setPostalCode] = React.useState('') | ||
const [postalCodeFilled, setPostalCodeFilled] = React.useState(false) | ||
|
||
const handleInputCep = (e: React.ChangeEvent<HTMLInputElement>) => { | ||
let value = e.target.value; | ||
let value = e.target.value | ||
|
||
value = value.replace(/\D/g, ""); | ||
value = value.replace(/\D/g, '') | ||
|
||
if (value.length > 5) { | ||
value = value.replace(/^(\d{5})(\d)/, "$1-$2"); | ||
value = value.replace(/^(\d{5})(\d)/, '$1-$2') | ||
} | ||
|
||
if (value.length > 9) { | ||
value = value.slice(0, 9); | ||
value = value.slice(0, 9) | ||
} | ||
|
||
setPostalCode(value); | ||
}; | ||
setPostalCode(value) | ||
} | ||
|
||
const resetShippingData = (orderFormId: string | undefined) => { | ||
|
||
if (!orderFormId) { | ||
console.error('OrderFormId não encontrado.'); | ||
return; | ||
console.error('OrderFormId não encontrado.') | ||
return | ||
} | ||
|
||
const headers = new Headers(); | ||
headers.append('Content-Type', 'application/json'); | ||
const headers = new Headers() | ||
headers.append('Content-Type', 'application/json') | ||
|
||
const body = JSON.stringify({ | ||
clearAddressIfPostalCodeNotFound: true, | ||
}); | ||
}) | ||
|
||
const requestOptions: RequestInit = { | ||
method: 'POST', | ||
headers, | ||
body, | ||
redirect: 'follow' as RequestRedirect, | ||
}; | ||
|
||
fetch(`/api/checkout/pub/orderForm/${orderFormId}/attachments/shippingData`, requestOptions) | ||
.then((response) => response.json()) | ||
.then((data) => console.log('Resposta do servidor:', data)) | ||
.catch((error) => console.error('Erro ao atualizar shippingData:', error)); | ||
}; | ||
|
||
const updateShippingData = async (e: React.FormEvent<HTMLFormElement>) => { | ||
|
||
e.preventDefault(); | ||
|
||
//@ts-ignore | ||
const orderFormId = window?.vtexjs?.checkout?.orderFormId; | ||
|
||
const myHeaders = new Headers(); | ||
myHeaders.append("Content-Type", "application/json"); | ||
|
||
const raw = JSON.stringify({ | ||
selectedAddresses: [ | ||
{ | ||
addressType: 'residential', | ||
country: 'BRA', | ||
postalCode: postalCode, | ||
}, | ||
], | ||
clearAddressIfPostalCodeNotFound: true, | ||
logisticsInfo: [{itemIndex: 0, selectedDeliveryChannel: 'delivery', selectedSla: 'ENTREGA CARAPRETA'}] | ||
}); | ||
|
||
const requestOptions = { | ||
method: "POST", | ||
headers: myHeaders, | ||
body: raw, | ||
redirect: "follow" as RequestRedirect | ||
}; | ||
|
||
await fetch(`/api/checkout/pub/orderForm/${orderFormId}/attachments/shippingData`, requestOptions) | ||
.then((response) => response.text()) | ||
.then((result) => { | ||
console.log(result) | ||
|
||
//@ts-ignore | ||
vtexjs.checkout.getOrderForm() | ||
.done(function(orderForm: any) { }); | ||
|
||
window?.localStorage?.setItem('userEnteredZipCode', 'true'); | ||
|
||
const bodyElement = document.querySelector('body') | ||
bodyElement?.classList.remove('zip-code-not-entered') | ||
|
||
}) | ||
.catch((error) => console.error("erro no cep", error)); | ||
} | ||
|
||
fetch( | ||
`/api/checkout/pub/orderForm/${orderFormId}/attachments/shippingData`, | ||
requestOptions | ||
) | ||
.then(response => response.json()) | ||
.then(data => console.log('Resposta do servidor:', data)) | ||
.catch(error => console.error('Erro ao atualizar shippingData:', error)) | ||
} | ||
|
||
const updateShippingData = async (e: React.FormEvent<HTMLFormElement>) => { | ||
e.preventDefault() | ||
|
||
useEffect(() => { | ||
const userEnteredZipCode = window?.localStorage?.getItem('userEnteredZipCode') == "true" | ||
//@ts-ignore | ||
const orderFormId = window?.vtexjs?.checkout?.orderFormId | ||
|
||
const myHeaders = new Headers() | ||
myHeaders.append('Content-Type', 'application/json') | ||
|
||
const raw = JSON.stringify({ | ||
selectedAddresses: [ | ||
{ | ||
addressType: 'residential', | ||
country: 'BRA', | ||
postalCode: postalCode, | ||
}, | ||
], | ||
clearAddressIfPostalCodeNotFound: true, | ||
logisticsInfo: [ | ||
{ | ||
itemIndex: 0, | ||
selectedDeliveryChannel: 'delivery', | ||
selectedSla: 'ENTREGA CARAPRETA', | ||
}, | ||
], | ||
}) | ||
|
||
const requestOptions = { | ||
method: 'POST', | ||
headers: myHeaders, | ||
body: raw, | ||
redirect: 'follow' as RequestRedirect, | ||
} | ||
|
||
if (!userEnteredZipCode) { | ||
await fetch( | ||
`/api/checkout/pub/orderForm/${orderFormId}/attachments/shippingData`, | ||
requestOptions | ||
) | ||
.then(response => response.text()) | ||
.then(result => { | ||
console.log(result) | ||
|
||
//@ts-ignore | ||
vtexjs.checkout.getOrderForm().done(function(orderForm: any) {}) | ||
|
||
window?.localStorage?.setItem('userEnteredZipCode', 'true') | ||
|
||
const bodyElement = document.querySelector('body') | ||
bodyElement?.classList.remove('zip-code-not-entered') | ||
setPostalCodeFilled(true) | ||
}) | ||
.catch(error => console.error('erro no cep', error)) | ||
} | ||
|
||
const resetPostalCode = () => { | ||
//@ts-ignore | ||
const orderFormId = window?.vtexjs?.checkout?.orderFormId; | ||
resetShippingData(orderFormId); | ||
} | ||
}, []); | ||
resetShippingData(window?.vtexjs?.checkout?.orderFormId) | ||
window?.localStorage?.setItem('userEnteredZipCode', 'false') | ||
const bodyElement = document.querySelector('body') | ||
bodyElement?.classList.add('zip-code-not-entered') | ||
setPostalCodeFilled(false) | ||
setPostalCode('') | ||
} | ||
|
||
useEffect(() => { | ||
const userEnteredZipCode = | ||
window?.localStorage?.getItem('userEnteredZipCode') == 'true' | ||
|
||
if (!userEnteredZipCode) { | ||
//@ts-ignore | ||
const orderFormId = window?.vtexjs?.checkout?.orderFormId | ||
resetShippingData(orderFormId) | ||
} | ||
}, []) | ||
|
||
return ( | ||
<div className="custom-cep-container"> | ||
<form className="custom-cep-form" onSubmit={updateShippingData}> | ||
<label htmlFor="custom-ship-postalCode" className="custom-cep-label"> | ||
Digite o CEP para finalizar a compra* | ||
</label> | ||
<div className="custom-cep-container-input"> | ||
<input | ||
type="text" | ||
className="custom-ship-postal-code" | ||
required | ||
placeholder="Digite seu CEP" | ||
value={postalCode} | ||
onChange={handleInputCep} | ||
/> | ||
<button className="custom-cep-submit" type="submit"> | ||
<span className="custom-cep-span">Calcular</span> | ||
</button> | ||
{postalCodeFilled ? ( | ||
<div className="custom-cep-form"> | ||
<p className="custom-cep-label"> | ||
Digite o CEP para finalizar a compra* | ||
</p> | ||
<div className="custom-cep-container-input"> | ||
<span className="custom-ship-postal-code">{postalCode}</span> | ||
<button className="custom-cep-submit" onClick={resetPostalCode}> | ||
<span className="custom-cep-span">Alterar</span> | ||
</button> | ||
</div> | ||
</div> | ||
<p className="custom-cep-alert">*Preenchimento obrigatório</p> | ||
<a | ||
className="custom-search-cep" | ||
href="https://buscacepinter.correios.com.br/app/endereco/index.php?t" | ||
target="_blank" | ||
rel="noopener noreferrer" | ||
> | ||
Não sei meu CEP | ||
</a> | ||
</form> | ||
</div> | ||
); | ||
) : ( | ||
<form className="custom-cep-form" onSubmit={updateShippingData}> | ||
<label htmlFor="custom-ship-postalCode" className="custom-cep-label"> | ||
Digite o CEP para finalizar a compra* | ||
</label> | ||
<div className="custom-cep-container-input"> | ||
<input | ||
type="text" | ||
className="custom-ship-postal-code" | ||
required | ||
placeholder="Digite seu CEP" | ||
value={postalCode} | ||
onChange={handleInputCep} | ||
/> | ||
<button className="custom-cep-submit" type="submit"> | ||
<span className="custom-cep-span">Calcular</span> | ||
</button> | ||
</div> | ||
<p className="custom-cep-alert">*Preenchimento obrigatório</p> | ||
<a | ||
className="custom-search-cep" | ||
href="https://buscacepinter.correios.com.br/app/endereco/index.php?t" | ||
target="_blank" | ||
rel="noopener noreferrer" | ||
> | ||
Não sei meu CEP | ||
</a> | ||
</form> | ||
)} | ||
</div> | ||
) | ||
} | ||
|
||
export default CheckoutCustomCep; | ||
export default CheckoutCustomCep |