Skip to content

Commit

Permalink
Merge pull request #2 from beightone/SEL-3064
Browse files Browse the repository at this point in the history
Feature: Add custom block cep in checkout #/cart
  • Loading branch information
raphab8one authored Feb 7, 2025
2 parents 682530c + a3dbc28 commit d831fe5
Show file tree
Hide file tree
Showing 10 changed files with 243 additions and 90 deletions.
3 changes: 2 additions & 1 deletion manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@
},
"builders": {
"react": "2.x",
"pages": "0.x"
"pages": "0.x",
"styles": "2.x"
},
"scripts": {
"postreleasy": "vtex publish"
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,4 @@
"prettier": "^2.0.2",
"typescript": "^3.8.3"
}
}
}
215 changes: 215 additions & 0 deletions react/components/CheckoutCustomCep/index.tsx
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
41 changes: 7 additions & 34 deletions react/index.tsx
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;
1 change: 0 additions & 1 deletion react/orderFormExample.json

This file was deleted.

4 changes: 2 additions & 2 deletions react/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
"@types/react-dom": "^16.0.5",
"@types/react-helmet": "^5.0.5",
"@types/react-intl": "^2.3.5",
"carapreta.checkout-customizations": "https://sel2669--carapreta.myvtex.com/_v/private/typings/linked/v1/carapreta.checkout-customizations@0.0.3+build1723475448/public/@types/carapreta.checkout-customizations",
"carapreta.checkout-customizations": "https://sel3064--carapreta.myvtex.com/_v/private/typings/linked/v1/carapreta.checkout-customizations@0.0.4+build1734113698/public/@types/carapreta.checkout-customizations",
"eslint": "^6.4.0",
"eslint-config-vtex": "^11.0.0",
"eslint-config-vtex-react": "^5.0.1",
Expand All @@ -29,6 +29,6 @@
"typescript": "3.9.7",
"vtex.checkout": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.checkout@0.6.0/public/_types/react",
"vtex.render-runtime": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@7.45.0/public/@types/vtex.render-runtime",
"vtex.styleguide": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.styleguide@9.146.9/public/@types/vtex.styleguide"
"vtex.styleguide": "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.styleguide@9.146.13/public/@types/vtex.styleguide"
}
}
1 change: 1 addition & 0 deletions react/typings/global.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,3 +72,4 @@ interface Message {
status: string
text: string
}

9 changes: 9 additions & 0 deletions react/typings/sellers.ts
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
}
45 changes: 0 additions & 45 deletions react/utils/loggerDataDog.tsx

This file was deleted.

12 changes: 6 additions & 6 deletions react/yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -500,9 +500,9 @@ caniuse-lite@^1.0.30001043, caniuse-lite@^1.0.30001061:
resolved "https://registry.yarnpkg.com/caniuse-lite/-/caniuse-lite-1.0.30001084.tgz#00e471931eaefbeef54f46aa2203914d3c165669"
integrity sha512-ftdc5oGmhEbLUuMZ/Qp3mOpzfZLCxPYKcvGv6v2dJJ+8EdqcvZRbAGOiLmkM/PV1QGta/uwBs8/nCl6sokDW6w==

"carapreta.checkout-customizations@https://sel2669--carapreta.myvtex.com/_v/private/typings/linked/v1/carapreta.checkout-customizations@0.0.3+build1723475448/public/@types/carapreta.checkout-customizations":
version "0.0.3"
resolved "https://sel2669--carapreta.myvtex.com/_v/private/typings/linked/v1/carapreta.checkout-customizations@0.0.3+build1723475448/public/@types/carapreta.checkout-customizations#03af359a5625628c358febd30f92299ecac83f94"
"carapreta.checkout-customizations@https://sel3064--carapreta.myvtex.com/_v/private/typings/linked/v1/carapreta.checkout-customizations@0.0.4+build1734113698/public/@types/carapreta.checkout-customizations":
version "0.0.4"
resolved "https://sel3064--carapreta.myvtex.com/_v/private/typings/linked/v1/carapreta.checkout-customizations@0.0.4+build1734113698/public/@types/carapreta.checkout-customizations#d1abe3aad91a1ba14dd68e865ab0b37312bc6f0e"

case-sensitive-paths-webpack-plugin@^2.2.0:
version "2.3.0"
Expand Down Expand Up @@ -2585,9 +2585,9 @@ vtex-tachyons@^3.2.0:
version "7.45.0"
resolved "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.render-runtime@7.45.0/public/@types/vtex.render-runtime#d9c9c4bbe8efe698a6b6566cc22e9dd7687a2442"

"vtex.styleguide@http://vtex.vtexassets.com/_v/public/typings/v1/vtex.styleguide@9.146.9/public/@types/vtex.styleguide":
version "9.146.9"
resolved "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.styleguide@9.146.9/public/@types/vtex.styleguide#d1601fedfb665c6173334753171717da64e670bc"
"vtex.styleguide@http://vtex.vtexassets.com/_v/public/typings/v1/vtex.styleguide@9.146.13/public/@types/vtex.styleguide":
version "9.146.13"
resolved "http://vtex.vtexassets.com/_v/public/typings/v1/vtex.styleguide@9.146.13/public/@types/vtex.styleguide#f4ccbc54621bf5114ddd115b6032ae320f2eba55"

warning@^4.0.0, warning@^4.0.2, warning@^4.0.3:
version "4.0.3"
Expand Down

0 comments on commit d831fe5

Please sign in to comment.