diff --git a/manifest.json b/manifest.json index 70261a4..2ea336e 100644 --- a/manifest.json +++ b/manifest.json @@ -12,7 +12,8 @@ }, "builders": { "react": "2.x", - "pages": "0.x" + "pages": "0.x", + "styles": "2.x" }, "scripts": { "postreleasy": "vtex publish" diff --git a/package.json b/package.json index efe2376..3f55bcb 100644 --- a/package.json +++ b/package.json @@ -33,4 +33,4 @@ "prettier": "^2.0.2", "typescript": "^3.8.3" } -} +} \ No newline at end of file diff --git a/react/components/CheckoutCustomCep/index.tsx b/react/components/CheckoutCustomCep/index.tsx new file mode 100644 index 0000000..43b5f40 --- /dev/null +++ b/react/components/CheckoutCustomCep/index.tsx @@ -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) => { + 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) => { + 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 ( + <> +
+ {postalCodeFilled ? ( +
+

+ Digite o CEP para finalizar a compra* +

+
+ {postalCode} + +
+
+ ) : ( +
+ +
+ + +
+

*Preenchimento obrigatório

+ + Não sei meu CEP + +
+ )} +
+ {errorModal && ( +
+
+ +

Desculpe

+

Ainda não atendemos a sua região

+ +
+
+ )} + + ) +} + +export default CheckoutCustomCep diff --git a/react/index.tsx b/react/index.tsx index 0eff02f..3f18868 100644 --- a/react/index.tsx +++ b/react/index.tsx @@ -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 ( + + ); } -export default CheckoutCheckingInformations +export default UniversalRenderProvider; diff --git a/react/orderFormExample.json b/react/orderFormExample.json deleted file mode 100644 index 21329f6..0000000 --- a/react/orderFormExample.json +++ /dev/null @@ -1 +0,0 @@ -{"orderFormId":"e68b71fb196842d9b9c65d959fe3e39d","salesChannel":"1","loggedIn":false,"isCheckedIn":false,"storeId":null,"checkedInPickupPointId":null,"allowManualPrice":false,"canEditData":true,"userProfileId":null,"userType":null,"ignoreProfileData":false,"value":135000,"messages":[],"items":[{"uniqueId":"CB3975B315E149A2BC26D0E6BCB8DD7A","id":"96","productId":"45","productRefId":"8349560862","refId":"79523795364","ean":null,"name":"Black Steel Film Camera","skuName":"Black Steel Film Camera","modalType":null,"parentItemIndex":null,"parentAssemblyBinding":null,"assemblies":[],"priceValidUntil":"2021-06-17T21:39:42.9421855Z","tax":0,"price":45000,"listPrice":45000,"manualPrice":null,"manualPriceAppliedBy":null,"sellingPrice":45000,"rewardValue":0,"isGift":false,"additionalInfo":{"brandName":"VTEX","brandId":"2000000","offeringInfo":null,"offeringType":null,"offeringTypeId":null},"preSaleDate":null,"productCategoryIds":"/3/12/","productCategories":{"12":"Cameras","3":"Electronics"},"quantity":3,"seller":"1","sellerChain":["1"],"imageUrl":"http://appliancetheme.vteximg.com.br/arquivos/ids/155762-55-55/camera-01.jpg?v=637080673910200000","detailUrl":"/black-steel-film-camera/p","components":[],"bundleItems":[],"attachments":[],"attachmentOfferings":[],"offerings":[],"priceTags":[],"availability":"available","measurementUnit":"un","unitMultiplier":1.0000,"manufacturerCode":null}],"selectableGifts":[],"totalizers":[{"id":"Items","name":"Items Total","value":135000}],"shippingData":{"address":null,"logisticsInfo":[{"itemIndex":0,"selectedSla":null,"selectedDeliveryChannel":null,"addressId":null,"slas":[],"shipsTo":["BRA"],"itemId":"96","deliveryChannels":[{"id":"delivery"}]}],"selectedAddresses":[],"availableAddresses":[],"pickupPoints":[]},"clientProfileData":null,"paymentData":{"installmentOptions":[{"paymentSystem":"17","bin":null,"paymentName":null,"paymentGroupName":null,"value":135000,"installments":[{"count":1,"hasInterestRate":false,"interestRate":0,"value":135000,"total":135000,"sellerMerchantInstallments":[{"id":"APPLIANCETHEME","count":1,"hasInterestRate":false,"interestRate":0,"value":135000,"total":135000}]}]}],"paymentSystems":[{"id":17,"name":"Promissory","groupName":"promissoryPaymentGroup","validator":{"regex":null,"mask":null,"cardCodeRegex":null,"cardCodeMask":null,"weights":null,"useCvv":false,"useExpirationDate":false,"useCardHolderName":false,"useBillingAddress":false},"stringId":"17","template":"promissoryPaymentGroup-template","requiresDocument":false,"isCustom":false,"description":null,"requiresAuthentication":false,"dueDate":"2020-06-24T23:56:33.9009616Z","availablePayments":null}],"payments":[],"giftCards":[],"giftCardMessages":[],"availableAccounts":[],"availableTokens":[]},"marketingData":null,"sellers":[{"id":"1","name":"treinamento","logo":""}],"clientPreferencesData":{"locale":"en-US","optinNewsLetter":false},"commercialConditionData":null,"storePreferencesData":{"countryCode":"BRA","saveUserData":true,"timeZone":"Eastern Standard Time","currencyCode":"BRL","currencyLocale":1046,"currencySymbol":"R$","currencyFormatInfo":{"currencyDecimalDigits":2,"currencyDecimalSeparator":",","currencyGroupSeparator":".","currencyGroupSize":3,"startsWithCurrencySymbol":true}},"giftRegistryData":null,"openTextField":null,"invoiceData":null,"customData":null,"itemMetadata":{"items":[{"id":"96","seller":"1","name":"Black Steel Film Camera","skuName":"Black Steel Film Camera","productId":"45","refId":"79523795364","ean":null,"imageUrl":"http://appliancetheme.vteximg.com.br/arquivos/ids/155762-55-55/camera-01.jpg?v=637080673910200000","detailUrl":"/black-steel-film-camera/p","assemblyOptions":[]}]},"hooksData":null,"ratesAndBenefitsData":{"rateAndBenefitsIdentifiers":[],"teaser":[]},"subscriptionData":null,"itemsOrdination":null} diff --git a/react/package.json b/react/package.json index 08d83ca..d730cdf 100644 --- a/react/package.json +++ b/react/package.json @@ -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", @@ -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" } } diff --git a/react/typings/global.d.ts b/react/typings/global.d.ts index 86c9ae9..8cd9f76 100644 --- a/react/typings/global.d.ts +++ b/react/typings/global.d.ts @@ -72,3 +72,4 @@ interface Message { status: string text: string } + diff --git a/react/typings/sellers.ts b/react/typings/sellers.ts new file mode 100644 index 0000000..31ba0b9 --- /dev/null +++ b/react/typings/sellers.ts @@ -0,0 +1,9 @@ +export interface ISellers { + id: string + sellers: ISeller[] +} +interface ISeller { + id: string + name: string + logo: string +} diff --git a/react/utils/loggerDataDog.tsx b/react/utils/loggerDataDog.tsx deleted file mode 100644 index 2505a0a..0000000 --- a/react/utils/loggerDataDog.tsx +++ /dev/null @@ -1,45 +0,0 @@ -export class Logger { - private sendLog(logBody: any) { - fetch('https://beightone.myvtex.com/_v0.0/api/send-log ', { - method: 'POST', - body: JSON.stringify({ ...this.coreLog(), ...logBody }), - }) - } - - private coreLog() { - //@ts-ignore - const { NODE_ENV } = window.vtex.renderRuntime.query.origin - // const { NODE_ENV, VTEX_APP_ID, VTEX_APP_VERSION } = process.env - - const logBody = { - traceId: '', - source: 'vtex', - env: NODE_ENV, - version: '0.5.7' ?? '', - index: 'integration', - hostname: window.location.hostname, - service: 'carapreta.checkout-customizations', - operationId: 'string', - account: 'string', - message: 'NO_MESSAGE', - content: 'NO_CONTENT', - status: 'info', - } - - console.info('INITIAL_LOG', logBody) - - return logBody - } - - public info(title: string, content: any, traceId?: string) { - this.sendLog({ message: title, content, status: 'info', traceId }) - } - - public warn(title: string, content: any, traceId?: string) { - this.sendLog({ message: title, content, status: 'warn', traceId }) - } - - public error(title: string, content: any, traceId?: string) { - this.sendLog({ message: title, content, status: 'error', traceId }) - } -} \ No newline at end of file diff --git a/react/yarn.lock b/react/yarn.lock index fddadaa..5a5a795 100644 --- a/react/yarn.lock +++ b/react/yarn.lock @@ -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" @@ -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"