Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/domains #1624

Open
wants to merge 12 commits into
base: main
Choose a base branch
from
Original file line number Diff line number Diff line change
@@ -1,19 +1,27 @@
import React from 'react';
import { shallow } from 'enzyme';
import { Heading, Text } from 'bonde-components/chakra';
import CertificateStatus from './CertificateStatus';
import { Button, Heading, Text } from 'bonde-components/chakra';
import LoadingIcon from '../../../icons/LoadingIcon';
import { CertificateStatus } from './CertificateStatus';

const authenticateSpy = jest.fn((values: any) => ({ data: {} }));

jest.mock('bonde-core-tools', () => ({
useMutation: () => [authenticateSpy],
gql: jest.fn()
}));

describe("CertificateStatus tests", () => {
const defaultMessage = 'Pode levar até 5 minutos para o certificado ser gerado e o endereço ficar disponível.';
const activeMessage = ["O endereço ", <b>nossas.link</b>, " está ativo e com certificado de segurança."];
const activeMessage = ["O endereço ", <b>www.nossas.link</b>, " está ativo e com certificado de segurança."];
const activeMessage2 = ["O endereço ", <b>www.nova-pagina.nossas.link</b>, " está ativo e com certificado de segurança."];
const inactiveMessage = 'Inativo';
const loadingMessage = 'Gerando certificado'
const failedMessage = 'Ops, falta configurar o ip'

it('should renders is ok', () => {
const wrapper = shallow(<CertificateStatus />);
expect(wrapper).toBeTruthy();

});

it('should render default/inactive status message', () => {
Expand All @@ -22,6 +30,7 @@ describe("CertificateStatus tests", () => {
expect(wrapper.find(Heading).props().children).toEqual('Status');
expect(wrapper.find(Text).at(0).props().children).toEqual(inactiveMessage);
expect(wrapper.find(Text).at(1).props().children).toEqual(defaultMessage);

});

it('should render message when certificate is in progress', () => {
Expand All @@ -33,7 +42,7 @@ describe("CertificateStatus tests", () => {
const wrapper = shallow(<CertificateStatus customDomain={customDomain} hostedZones={hostedZones} />);

expect(wrapper.find(LoadingIcon).at(0));
expect(wrapper.find(Text).at(0).props().children).toEqual(loadingMessage);
expect(wrapper.find(Text).at(0));
});

it('should render active status', () => {
Expand Down Expand Up @@ -71,7 +80,8 @@ describe("CertificateStatus tests", () => {

expect(wrapper.find(Heading).props().children).toEqual('Status');
expect(wrapper.find(Text).at(0).props().children).toEqual('Ativo');
expect(wrapper.find(Text).at(1).props().children).toEqual(activeMessage);
expect(wrapper.find(Text).at(1).props().children).toEqual(activeMessage2);

});

it('should render when ip is failed', () => {
Expand All @@ -84,5 +94,9 @@ describe("CertificateStatus tests", () => {

expect(wrapper.find(LoadingIcon).at(0));
expect(wrapper.find(Text).at(0).props().children).toEqual(failedMessage);
expect(wrapper.find(Button));

const button = wrapper.find(Button);
button.simulate('click');
})
});
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
import React from 'react';
import { Heading, Text, Stack, Flex } from 'bonde-components/chakra';
import { Heading, Text, Stack, Flex, Button, useToast } from 'bonde-components/chakra';
import CheckIcon from "../../../icons/CheckIcon"
import LoadingIcon from "../../../icons/LoadingIcon"
import { gql, useMutation, checkDNS } from 'bonde-core-tools';
import { connect } from 'react-redux';
import * as dnsControlActions from '../../../community/action-creators/dns-control';

const IP_LISTS = [
'54.85.56.248',
'3.236.227.166'
]

interface Certificate {
id: number;
Expand All @@ -24,15 +32,52 @@ interface HostedZone {
interface Properties {
customDomain?: string;
hostedZones?: HostedZone[];
updateDomain?: (dnsHostedZone: any, mobilization?: any) => void;
}

const CertificateStatus: React.FC<Properties> = ({ customDomain, hostedZones = [] }) => {
export const CertificateStatus: React.FC<Properties> = ({ updateDomain, customDomain, hostedZones = [] }) => {
const domain: any | undefined = hostedZones.filter(
(v) => customDomain?.endsWith(v.domain_name)
)[0];
const hasCertificate = domain?.certificates[0]?.is_active
const isExternalDomain = domain?.is_external_domain
const failedIp = !domain?.ns_ok && isExternalDomain
const failedIp = (!domain?.ns_ok && isExternalDomain) || (domain === undefined && customDomain)
const toast = useToast()

const [updateDnsHostedZone] = useMutation(
gql`
mutation ($id: Int!) {
update_dns_hosted_zones_by_pk(
pk_columns: { id: $id }, _set: { ns_ok: true }
) {
id
domain_name
ns_ok
}
}
`
);

const handleCheckDns = async () => {
if (await checkDNS(domain.domain_name, 'A', { ip: IP_LISTS })) {
const { data } = await updateDnsHostedZone({
variables: {
id: domain.id // "A" verifica por IP
}
})

updateDomain && updateDomain(
{
...domain,
...data.update_dns_hosted_zones_by_pk
}
);

toast({ title: 'Tudo certo!', description: 'Ip verificado', status: 'success', duration: 4000, isClosable: true });
} else {
toast({ title: 'Ops, IP não verificado', description: 'Aguarde mais alguns minutos e tente novamente', status: 'error', duration: 4000, isClosable: true })
}
}

return (
<Stack mt={6}>
Expand All @@ -49,7 +94,7 @@ const CertificateStatus: React.FC<Properties> = ({ customDomain, hostedZones = [
)}

{/* GERANDO CERTIFICADO */}
{customDomain && !domain?.certificates[0]?.is_active && !isExternalDomain && (
{customDomain && domain?.ns_ok && !domain?.certificates[0]?.is_active && (
<>
<Flex >
<LoadingIcon />
Expand All @@ -66,19 +111,24 @@ const CertificateStatus: React.FC<Properties> = ({ customDomain, hostedZones = [
<CheckIcon />
<Text fontSize="sm" color="green.200" fontWeight="bold" textTransform="uppercase">Ativo</Text>
</Flex>
<Text>O endereço <b>{domain?.domain_name}</b> está ativo e com certificado de segurança.</Text>
<Text>O endereço <b>{customDomain}</b> está ativo e com certificado de segurança.</Text>
</>
)}

{/* FALTOU CONFIGURAR IP */}
{failedIp && (
<Flex >
<LoadingIcon />
<Text fontSize="sm" fontWeight="bold" ml={2} textTransform="uppercase" color="gray.400">Ops, falta configurar o ip</Text>
</Flex>
<>
<Flex >
<LoadingIcon />
<Text fontSize="sm" fontWeight="bold" ml={2} textTransform="uppercase" color="gray.400">Ops, falta configurar o ip</Text>
</Flex>
<Text>Siga o passo a passo acima e <Button variant='link' textTransform='lowercase' onClick={handleCheckDns}
>clique aqui
</Button> para verificar novamente.</Text>
</>
)}
</Stack>
);
}

export default CertificateStatus;
export default connect(undefined, { updateDomain: dnsControlActions.updateDomain })(CertificateStatus);
Original file line number Diff line number Diff line change
Expand Up @@ -95,13 +95,11 @@ describe('FormPanel tests', () => {
describe('onSubmit validate', () => {
const mockUpdateMobilization = jest.fn();
const mockCreateDnsHostedZone = jest.fn();
const mockUpdateDnsHostedZone = jest.fn();
const mockCreateOrUpdateCertificate = jest.fn();

beforeEach(() => {
mockUseMutation.mockReturnValueOnce([mockUpdateMobilization]);
mockUseMutation.mockReturnValueOnce([mockCreateDnsHostedZone]);
mockUseMutation.mockReturnValueOnce([mockUpdateDnsHostedZone]);
mockUseMutation.mockReturnValueOnce([mockCreateOrUpdateCertificate]);
// jest.clearAllMocks();
});
Expand Down Expand Up @@ -160,13 +158,6 @@ describe('FormPanel tests', () => {

await form.props().onSubmit({ customDomain, isExternalDomain: true });

expect(mockCreateDnsHostedZone.mock.calls.length).toEqual(1);
expect(mockCreateDnsHostedZone.mock.calls[0][0]).toEqual({
variables: {
comment: `mobilization_id:${mobilization.id}`,
customDomain: customDomain
}
});
expect(mockUpdateMobilization.mock.calls.length).toEqual(1);
});

Expand All @@ -183,31 +174,30 @@ describe('FormPanel tests', () => {

await form.props().onSubmit({ customDomain, isExternalDomain: true });

expect(mockCreateDnsHostedZone.mock.calls.length).toEqual(1);
expect(mockUpdateMobilization.mock.calls.length).toEqual(0);
expect(mockUpdateMobilization.mock.calls.length).toEqual(1);
// Expect call toast failed message
expect(mockToast.mock.calls[0][0]).toEqual({
title: 'Falha ao submeter formulário',
description: 'Failed fetch!',
title: 'Falha ao atualizar o domínio',
description: 'Esse endereço já está sendo usado em outra página.',
status: 'error',
isClosable: true
});
});

it('should call updateDnsHostedZone IP is configured', async () => {
const customDomain = 'asdasdas.org';
mockCheckDNS.mockResolvedValueOnce(true);
const customDomain = 'testeteste.org';
// mockCheckDNS.mockResolvedValueOnce(true);
mockCreateDnsHostedZone.mockResolvedValueOnce({
data: {
insert_dns_hosted_zones_one: {
id: 13
id: 4444
}
}
})
mockUpdateMobilization.mockResolvedValueOnce({
data: {
update_mobilization_by_pk: {
id: 1,
id: 441,
custom_domain: customDomain
}
}
Expand All @@ -229,13 +219,6 @@ describe('FormPanel tests', () => {

await form.props().onSubmit({ customDomain, isExternalDomain: true });

expect(mockCreateDnsHostedZone.mock.calls.length).toEqual(1);
expect(mockUpdateDnsHostedZone.mock.calls.length).toEqual(1);
expect(mockUpdateDnsHostedZone.mock.calls[0][0]).toEqual({
variables: {
id: 13
}
});
expect(mockUpdateMobilization.mock.calls.length).toEqual(1);
// Expect call toast success message
expect(mockToast.mock.calls[0][0]).toEqual({
Expand Down Expand Up @@ -279,12 +262,6 @@ describe('FormPanel tests', () => {

expect(mockCheckDNS.mock.calls.length).toEqual(1);
expect(mockCreateDnsHostedZone.mock.calls.length).toEqual(0);
expect(mockUpdateDnsHostedZone.mock.calls.length).toEqual(1);
expect(mockUpdateDnsHostedZone.mock.calls[0][0]).toEqual({
variables: {
id: hostedZones[0].id
}
});
expect(mockUpdateMobilization.mock.calls.length).toEqual(1);
// Expect call toast success message
expect(mockToast.mock.calls[0][0]).toEqual({
Expand All @@ -299,7 +276,7 @@ describe('FormPanel tests', () => {
{ id: 14, domain_name: 'nossas.link', is_external_domain: false, name_servers: ['ok.dasd-ws.org', 'tsd-12.dasd-ws.uk'], ns_ok: true },
{ id: 13, domain_name: 'outrodominio.org', is_external_domain: true, ns_ok: true }
]
const customDomain = 'campanha.nossas.link';
const customDomain = 'campanha.nossas.liink';
mockCheckDNS.mockResolvedValueOnce(true);
mockUpdateMobilization.mockResolvedValueOnce({
data: {
Expand All @@ -326,21 +303,10 @@ describe('FormPanel tests', () => {

await form.props().onSubmit({ customDomain });

expect(mockCheckDNS.mock.calls.length).toEqual(0);
expect(mockCheckDNS.mock.calls.length).toEqual(1);
expect(mockCreateDnsHostedZone.mock.calls.length).toEqual(0);
expect(mockUpdateMobilization.mock.calls.length).toEqual(1);
expect(mockCreateOrUpdateCertificate.mock.calls.length).toEqual(1);
expect(mockCreateOrUpdateCertificate.mock.calls[0][0]).toEqual({
variables: {
dns_hosted_zone_id: hostedZones[0].id
}
});
// Expect call toast success message
expect(mockToast.mock.calls[0][0]).toEqual({
title: 'Domínio registrado com sucesso!',
status: 'success',
isClosable: true
});
expect(mockUpdateMobilization.mock.calls.length).toEqual(0);
expect(mockCreateOrUpdateCertificate.mock.calls.length).toEqual(0);
});
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ export const FormPanel: React.FC<FormPanelProperties> = ({
const onSubmit = async ({ customDomain, isExternalDomain = false }: { customDomain: string, isExternalDomain?: boolean }) => {
try {
const hostedZone = internalHostedZones.filter((hz) => customDomain.endsWith(hz.domain_name))[0];
if (isExternalDomain) {
if (isExternalDomain && mobilization.community_id) {
// Create dns hosted zone
const { data } = await createDnsHostedZone({
variables: {
Expand All @@ -127,7 +127,7 @@ export const FormPanel: React.FC<FormPanelProperties> = ({
}
} else {
if (!hostedZone?.ns_ok) {
if (await checkDNS(customDomain, 'NS', { ns: hostedZone.name_servers })) {
if (await checkDNS(customDomain, 'NS', { ns: hostedZone?.name_servers })) {
await updateDnsHostedZone({ variables: { id: hostedZone.id } })
}
}
Expand All @@ -141,7 +141,7 @@ export const FormPanel: React.FC<FormPanelProperties> = ({
const { data } = await createOrUpdateCertificate({ variables: { dns_hosted_zone_id: hostedZone.id } });
certificate = data?.create_or_update_certificate;
}

updateDomain && updateDomain(
{
...hostedZone,
Expand All @@ -151,12 +151,22 @@ export const FormPanel: React.FC<FormPanelProperties> = ({
);
toast({ title: 'Domínio registrado com sucesso!', status: 'success', isClosable: true });
} catch (err: any) {
toast({
title: 'Falha ao submeter formulário',
description: err?.message || err,
status: 'error',
isClosable: true
});
if (!customDomain) {
toast({
title: 'Falha ao atualizar o domínio',
description: 'O endereço não pode ficar em branco',
status: 'error',
isClosable: true
})
}
else {
toast({
title: 'Falha ao atualizar o domínio',
description: 'Esse endereço já está sendo usado em outra página.',
status: 'error',
isClosable: true
})
}
}
}

Expand Down Expand Up @@ -195,4 +205,4 @@ export const FormPanel: React.FC<FormPanelProperties> = ({
);
}

export default connect(undefined, { updateDomain: dnsControlActions.updateDomain })(FormPanel);
export default connect(undefined, { updateDomain: dnsControlActions.updateDomain })(FormPanel);