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.
Merge pull request #2 from beightone/SEL-3064
Feature: Add custom block cep in checkout #/cart
- Loading branch information
Showing
10 changed files
with
243 additions
and
90 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
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 |
---|---|---|
|
@@ -33,4 +33,4 @@ | |
"prettier": "^2.0.2", | ||
"typescript": "^3.8.3" | ||
} | ||
} | ||
} |
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 |
---|---|---|
@@ -0,0 +1,215 @@ | ||
import React, { FC, useEffect } from 'react' | ||
import { ISellers } from '../../typings/sellers' | ||
|
||
const CheckoutCustomCep: FC = () => { | ||
const [postalCode, setPostalCode] = React.useState('') | ||
const [postalCodeFilled, setPostalCodeFilled] = React.useState(false) | ||
const [errorModal, setErrorModal] = React.useState(false) | ||
|
||
const handleInputCep = (e: React.ChangeEvent<HTMLInputElement>) => { | ||
let value = e.target.value | ||
|
||
value = value.replace(/\D/g, '') | ||
|
||
if (value.length > 5) { | ||
value = value.replace(/^(\d{5})(\d)/, '$1-$2') | ||
} | ||
|
||
if (value.length > 9) { | ||
value = value.slice(0, 9) | ||
} | ||
|
||
setPostalCode(value) | ||
} | ||
|
||
const resetShippingData = (orderFormId: string | undefined) => { | ||
if (!orderFormId) { | ||
console.error('OrderFormId não encontrado.') | ||
return | ||
} | ||
|
||
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() | ||
const checkRegionServed = await fetch( | ||
`/api/checkout/pub/regions?country=BRA&postalCode=${postalCode}` | ||
) | ||
|
||
if (!checkRegionServed.ok) { | ||
throw new Error(`HTTP error ${checkRegionServed.status}`) | ||
} | ||
const sellersByRegion: ISellers[] = await checkRegionServed.json() | ||
const hasSellers = sellersByRegion[0].sellers.length > 0 | ||
if (!hasSellers) { | ||
setErrorModal(true) | ||
return | ||
} | ||
//@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 => { | ||
//@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 | ||
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"> | ||
{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> | ||
) : ( | ||
<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> | ||
{errorModal && ( | ||
<div className="modal-zip-code-not-error-wrapper"> | ||
<div className="modal-zip-code-not-entered-content"> | ||
<button | ||
className="btn-close-modal" | ||
onClick={() => { | ||
setErrorModal(false) | ||
setPostalCode('') | ||
}} | ||
></button> | ||
<h2>Desculpe</h2> | ||
<p>Ainda não atendemos a sua região</p> | ||
<button | ||
className="btn-try-again" | ||
onClick={() => { | ||
setErrorModal(false) | ||
setPostalCode('') | ||
}} | ||
> | ||
Tentar outro CEP | ||
</button> | ||
</div> | ||
</div> | ||
)} | ||
</> | ||
) | ||
} | ||
|
||
export default CheckoutCustomCep |
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,38 +1,11 @@ | ||
import { Component } from 'react' | ||
import React, { FC } from 'react'; | ||
|
||
import { Logger } from './utils/loggerDataDog' | ||
import CheckoutCustomCep from './components/CheckoutCustomCep'; | ||
|
||
const logger = new Logger() | ||
|
||
class CheckoutCheckingInformations extends Component<{}, CheckoutCheckingInformationsState> { | ||
constructor(props: any) { | ||
super(props) | ||
this.state = { | ||
orderForm: null, | ||
} | ||
} | ||
|
||
setOrderForm = (_: any, orderForm: OrderForm) => { | ||
this.setState({ orderForm }) | ||
const postalCode = orderForm.shippingData.address.postalCode | ||
console.log(postalCode, orderForm) | ||
logger.info(`CHECKOUT_DATA_INFORMATION ${postalCode}`, JSON.stringify(orderForm)) | ||
} | ||
|
||
componentDidMount() { | ||
$(window).on('orderFormUpdated.vtex', this.setOrderForm) | ||
} | ||
|
||
componentWillUnmount() { | ||
$(window).off('orderFormUpdated.vtex', this.setOrderForm) | ||
} | ||
render() { | ||
return null | ||
} | ||
} | ||
|
||
interface CheckoutCheckingInformationsState { | ||
orderForm: OrderForm | null | ||
const UniversalRenderProvider: FC = () => { | ||
return ( | ||
<CheckoutCustomCep /> | ||
); | ||
} | ||
|
||
export default CheckoutCheckingInformations | ||
export default UniversalRenderProvider; |
This file was deleted.
Oops, something went wrong.
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
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 |
---|---|---|
|
@@ -72,3 +72,4 @@ interface Message { | |
status: string | ||
text: string | ||
} | ||
|
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 |
---|---|---|
@@ -0,0 +1,9 @@ | ||
export interface ISellers { | ||
id: string | ||
sellers: ISeller[] | ||
} | ||
interface ISeller { | ||
id: string | ||
name: string | ||
logo: string | ||
} |
This file was deleted.
Oops, something went wrong.
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