Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
6.8 kB
2
Indexable
Never
/*
Licensed Materials - Property of IBM
694906H
(c) Copyright IBM Corp.  2020 All Rights Reserved

US Government Users Restricted Rights - Use, duplication or disclosure restricted
by GSA ADP Schedule Contract with IBM Corp.
*/

import React, { useMemo, useEffect } from 'react';
import { useHistory, useLocation } from 'react-router-dom';
import * as S from './OrderCompleted.styles';
import { LayoutSpacing } from '@exo/frontend-components-core';
import { Row, Column, Breadcrumb } from '@exo/frontend-components-base';
import { useCheckoutMarketPlaceContext } from '@exo/frontend-features-checkout-marketplace-logic/client/context/CheckoutContext';
import { SummaryProducts } from '@exo/frontend-features-checkout-marketplace-logic/client/components/SummaryProducts/SummaryProducts';
import { SummaryPayment } from '@exo/frontend-features-checkout-marketplace-logic/client/components/SummaryPayment/SummaryPayment';
import { WarningInforOrder } from '../../components/ErrorPage/WarningInforOrder';
import { useWindowDimensions } from '../../../../../account/account-logic/client/hooks/useWindowDimensions';
import { BankingBillet } from '../../components/OrderCompletedPage/BankingBillet';
import { PaymentMethodType } from '@exo/frontend-features-checkout-marketplace-logic/client/util/defaultFunctionUtil';
import { Pix } from '../../components/OrderCompletedPage/Pix';
import { CreditCard } from '../../components/OrderCompletedPage/CreditCard';
import { TagManagerUtils, ActionType, Event } from '@exo/frontend-utils';
import { useSessionContext } from '@exo/frontend-common-session-context';
import { useTagueamento } from '@exo/contexts/hooks/marketplace/useTagueamento';
import { useGetProductCart } from '@exo/frontend-features-checkout-marketplace-logic/client/hooks/useGetProductCart';

const paymentType = {
  braspag_pagador_boleto: 'Boleto bancário',
  braspag_pagador_creditcard: 'Cartão de crédito',
  aarin_pix: 'PIX',
  checkmo: 'Financiamento bancário'
};

export const OrderCompleted = ({}: Props) => {
  const history = useHistory();
  const { width } = useWindowDimensions();
  const { session, cartId } = useCheckoutMarketPlaceContext();
  const sessionContext = useSessionContext();

  let stateObj: any = {};
  const orderNumber = stateObj.placeOrder?.orderNumber || 0;
  const paymentMethodType = paymentType[stateObj.paymentType];

  const { loading } = useGetProductCart(cartId);

  useEffect(() => {
    TagManagerUtils.pageview(
      ActionType.PageView,
      'compra-finalizada',
      TagManagerUtils.getUserStatus(sessionContext),
      '/checkout/order-completed',
      'web',
      null,
      { userId: TagManagerUtils.getUserId(sessionContext) }
    );
  }, []);

  const cartItens = stateObj?.cart?.me?.carts[0]?.lineItems;

  const mappedProduct_ids = cartItens?.map(prod => {
    return prod?.partnumber;
  });

  const { data: dataProducts } = useTagueamento({ ids: mappedProduct_ids });

  const productInfos = dataProducts?.getTagueamento?.map(prod => {
    const itemQuantity = cartItens.find(item => item.partnumber === prod.id)?.quantity;

    return {
      item_id: prod.id,
      item_name: prod.name,
      affiliation: prod?.affiliation,
      currency: 'BRL',
      item_brand: prod.brand,
      item_category: prod.category,
      price: prod.price,
      quantity: itemQuantity
    };
  });

  useEffect(() => {
    TagManagerUtils.pageview(
      ActionType.PageView,
      'compra-finalizada',
      TagManagerUtils.getUserStatus(sessionContext),
      '/checkout/order-completed',
      'tela',
      null,
      { userId: TagManagerUtils.getUserId(sessionContext) }
    );

    TagManagerUtils.tagecommerce(
      Event.Purchase,
      productInfos,
      null,
      null,
      null,
      stateObj?.cart?.me?.carts[0]?.mp_info?.orders[0]?.selected_shipping_type?.label,
      stateObj?.cart?.me?.carts[0]?.grandTotal?.value,
      paymentMethodType,
      orderNumber
    );
  }, [loading]);

  const location = useLocation() as any;

  const qs = new URLSearchParams(location.search);

  const result = qs.get('error');

  if (result && result === 'true') {
    return <WarningInforOrder />;
  }

  if (location.state === undefined) {
    history.push('/loja');
  } else {
    stateObj = {
      placeOrder: location.state.placeOrder,
      cart: location.state.cart,
      price: location.state.price,
      paymentType: location.state.paymentType
    };
  }

  const prescriptionMessage = () => {
    const productsNeedPrescription = stateObj?.cart?.me?.carts[0]?.lineItems?.find(
      item => item.product.precisa_de_receita
    );
    const textInfoOrder = `Obrigado! Seu pedido número ${orderNumber} foi feito e será processado após o pagamento do ${paymentMethodType.toLowerCase()}${
      productsNeedPrescription ? ' e receita agronômica anexada.' : '.'
    }`;

    return textInfoOrder;
  };

  const args = {
    path: [
      {
        url: '#',
        label: 'Pedido realizado'
      }
    ],
    className: ''
  };

  const SummaryProductsAndPayment = () =>
    useMemo(() => {
      return (
        <>
          <SummaryProducts
            cart={stateObj.cart}
            title="Resumo da compra"
            isOrderFinishedPage
            orderId={orderNumber?.toLocaleString()}
          />
          <S.SummaryPayment>
            <SummaryPayment priceContigence={stateObj.price} />
          </S.SummaryPayment>
        </>
      );
    }, []);

  return (
    <>
      <LayoutSpacing size="sm" />
      <S.Container>
        <Row>
          <Column>
            <Breadcrumb key={'breadcrumb'} {...args} hasHomePage className="breadcrumb" />
          </Column>
        </Row>

        <S.Grid>
          <S.Title>Pedido realizado</S.Title>
        </S.Grid>

        {paymentMethodType === PaymentMethodType.BANKINGBILLET && (
          <BankingBillet
            stateObj={stateObj}
            session={session}
            width={width}
            history={history}
            SummaryProductsAndPayment={SummaryProductsAndPayment}
            prescriptionMessage={prescriptionMessage}
          />
        )}

        {paymentMethodType === PaymentMethodType.PIX && (
          <Pix
            stateObj={stateObj}
            session={session}
            width={width}
            history={history}
            SummaryProductsAndPayment={SummaryProductsAndPayment}
            prescriptionMessage={prescriptionMessage}
          />
        )}

        {paymentMethodType === PaymentMethodType.CARD && (
          <CreditCard
            session={session}
            history={history}
            SummaryProductsAndPayment={SummaryProductsAndPayment}
            prescriptionMessage={prescriptionMessage}
          />
        )}
      </S.Container>
    </>
  );
};

type Props = {};